text:
Nested "switch" statements menu
I know that menus were discussed perhaps a thousand times here and everywhere. But using a ready solution is not something that I'm looking for because I know I won't learn the concept if I use them. Hence the question.
I am trying to build a simple timer with a setup menu. The timer code works so that part of the code is not a problem. The menu is an adaption of a code I found online which I understand, and for the most part, works as long as I am in level 1. My menu will have 2 levels. the structure of the menu is something like this:
Option 1: Display Timer 1
Option 2: Display Timer 2
Option 3: Reset Timer 1
Option 4: Reset Timer 2
Option 5: Set Timer 1 Action Delay

Option 5.1: Delay01
Option 5.2: Delay02
Option 5.3: Delay03
Option 5.4: Back

Option 6: Set Timer 2 Action Delay

Option 6.1: Delay01
Option 6.2: Delay02
Option 6.3: Delay03
Option 6.4: Back

The menu will be displayed with an I2C 1602 LCD Screen, and navigation will be by way of 3 push buttons: Up, Down, and Select.
I am using a nested "switch case" statement to navigate between the menus.
So as long as I'm in level 1, everything works. the times are displayed, reset works, and all is well. The moment I go to a submenu, the first option in the submenu is selected immediately and the display shows the parent menu.
I am putting the menu code in a function, the submenu code in another function. Once the menu with a submenu is selected, it calls the submenu function.
My current code is as follows: [Note: Updated with a function to handle screen updates based on @jsotola]
#include <LiquidCrystal_I2C.h>
#include <Wire.h>

#include <EEPROM.h>     //EEPROM Functions: EEPROM Module
#include <Arduino.h>    //EEPROM Functions: for type definitions

LiquidCrystal_I2C lcd(0x27,16,2);

//Globals:
int page_counter    =   1 ; //To move between pages
int page_counter_s  =   1;  //submenu

int up = 2;             //Up button
int down = 3;           //Down button
int selection = 4;      //Select button
int LED =   13;

int pageCount   =   7;  //Main Menu

//Main Menu
boolean last_up         =   LOW;
boolean last_down       =   LOW;
boolean last_select     =   LOW;

boolean current_up      =   LOW;
boolean current_down    =   LOW;
boolean current_select  =   LOW;

boolean last_up_s     =   LOW;
boolean last_down_s     =   LOW;

boolean current_up_s    =   LOW;
boolean current_down_s  =   LOW;

String line1;
String line2;

//---- De-bouncing function for all buttons----//
boolean debounce(boolean last, int pin){
  boolean current = digitalRead(pin);
  if (last != current){
    delay(5);
    current = digitalRead(pin);
  }
  return current;
}

//LCD Function

void printlcd(){
    lcd.setCursor(0,0);
    lcd.print(line1);
    lcd.setCursor(0,1);
    lcd.print(line2);
}

//Menu Function
void Menus(){

    current_up = debounce(last_up, up);         //Debounce for Up button
    current_down = debounce(last_down, down);   //Debounce for Down button
    current_select = debounce(last_select, selection); //Debounce for Select button
    //----Page counter function to move pages----//

        //Page Up
        if (last_up == LOW && current_up == HIGH){  //When up button is pressed
          lcd.clear();                     //When page is changed, lcd clear to print new page

            if(page_counter < pageCount){             //Page counter never higher than 3(total of pages)
                page_counter= page_counter +1;   //Page up
            }
            else{
                page_counter = pageCount;
            }
        }

        last_up = current_up;

        //Page Down
        if (last_down== LOW && current_down == HIGH){ //When down button is pressed
          lcd.clear();                     //When page is changed, lcd clear to print new page
          if(page_counter >1){              //Page counter never lower than 1 (total of pages)
          page_counter= page_counter -1;   //Page down

          }
          else{
          page_counter= 1;
         }
        }

        last_down = current_down;

//------- Switch function to write and show what you want---//
  switch (page_counter) {

    case 1:{ //Each case is a menu option

      line1 = "Counter 01:";
      line2 = "100 Hrs";
      printlcd();
    }
    break;

    case 2:{ //Each case is a menu option
      line1 = "Counter 02:";
      line2 = "70 Hrs";
      printlcd();
    }
    break;

    case 3:{ //Each case is a menu option
      line1 = "Reset 01:";
      line2 = "";
      printlcd();

      //Action:
      if (last_select == LOW && current_select == HIGH){ //When down button is pressed
            lcd.clear();
            line1 = "Success!";
            line2 = "C01 Reset";
            printlcd();

            digitalWrite(LED,HIGH);
            delay(500);
            digitalWrite(LED,LOW);

            delay(3000);
            lcd.clear();

        }
    }
    break;

    case 4:{ //Each case is a menu option
      line1 = "Reset 02:";
      line2 = "";
      printlcd();

      //Action:
      if (last_select == LOW && current_select == HIGH){ //When down button is pressed
            lcd.clear();
            line1 = "Success!";
            line2 = "C02 Reset";
            printlcd();

            digitalWrite(LED,HIGH);
            delay(500);
            digitalWrite(LED,LOW);

            delay(3000);
            lcd.clear();

        }
    }
    break;

    case 5:{ //Each case is a menu option

        line1 = "Set 01";
        line2 = "Interval";
        printlcd();

      //Action:
        if (last_select == LOW && current_select == HIGH){ //When down button is pressed
            lcd.clear();
            submenu();
        }
    }
    break;

    case 6:{ //Each case is a menu option
        line1 = "Set 02";
        line2 = "Interval";
        printlcd();

      //Action:
        if (last_select == LOW && current_select == HIGH){ //When down button is pressed
            lcd.clear();
            submenu();
        }
    }

    case 7:{ //Each case is a menu option
        line1 = "Exit service";
        line2 = "mode";
        printlcd();

      //Action:
        if (last_select == LOW && current_select == HIGH){ //When down button is pressed

            lcd.clear();
            line1 = "Exiting";
            line2 = "Please Wait";
            printlcd();

            digitalWrite(LED,HIGH);
            delay(500);
            digitalWrite(LED,LOW);
            delay(500);

            delay(3000);
            lcd.clear();
            }
    }
    break;

  }//switch end

}

void submenu(){

    current_up_s = debounce(last_up, up);         //Debounce for Up button
    current_down_s = debounce(last_down, down);   //Debounce for Down button
    current_select = debounce(last_select, selection); //Debounce for Select button
    //----Page counter function to move pages----//

        //Page Up
        if (last_up == LOW && current_up_s == HIGH){  //When up button is pressed
          lcd.clear();                     //When page is changed, lcd clear to print new page

            if(page_counter_s < 8){             //Page counter never higher than 3(total of pages)
                page_counter_s = page_counter_s +1;   //Page up
            }
            else{
                page_counter_s = 8;
            }
        }

        last_up = current_up_s;

        //Page Down
        if (last_down == LOW && current_down_s == HIGH){ //When down button is pressed
          lcd.clear();                     //When page is changed, lcd clear to print new page
          if(page_counter >1){              //Page counter never lower than 1 (total of pages)
          page_counter_s = page_counter_s -1;   //Page down

          }
          else{
          page_counter_s = 1;
         }
        }

        last_down = current_down_s;

//------- Switch function to write and show what you want---//
  switch (page_counter_s) {

    case 1:{ //Each case is a menu option

      line1 =   "Set dealy to:";
      line2 =   "100 hrs";
      printlcd();
      //Action:
      if (last_select == LOW && current_select == HIGH){ //When down button is pressed
            lcd.clear();
            line1 = "New Delay:";;
            line2 = "100 hrs";
            printlcd();

            digitalWrite(LED,HIGH);
            delay(500);
            digitalWrite(LED,LOW);
            delay(3000);
            lcd.clear();
        }
    }
    break;

    case 2:{ //Each case is a menu option

      line1 =   "Set dealy to:";
      line2 =   "200 hrs";
      printlcd();
      //Action:
      if (last_select == LOW && current_select == HIGH){ //When down button is pressed
            lcd.clear();
            line1 = "New Delay:";
            line2 = "200 hrs";
            printlcd();

            digitalWrite(LED,HIGH);
            delay(500);
            digitalWrite(LED,LOW);
            delay(3000);
            lcd.clear();
        }
    }
    break;

    case 3:{ //Each case is a menu option

      line1 =   "Set dealy to:";
      line2 =   "300 hrs";
      printlcd();
      //Action:
      if (last_select == LOW && current_select == HIGH){ //When down button is pressed
            lcd.clear();
            line1 = "New Delay:";
            line2 = "300 hrs";
            printlcd();

            digitalWrite(LED,HIGH);
            delay(500);
            digitalWrite(LED,LOW);
            delay(3000);
            lcd.clear();
        }
    }
    break;

    case 4:{ //Each case is a menu option

      line1 =   "Set dealy to:";
      line2 =   "400 hrs";
      printlcd();
      //Action:
      if (last_select == LOW && current_select == HIGH){ //When down button is pressed
            lcd.clear();
            line1 = "New Delay:";
            line2 = "400 hrs";
            printlcd();

            digitalWrite(LED,HIGH);
            delay(500);
            digitalWrite(LED,LOW);
            delay(3000);
            lcd.clear();
        }
    }
    break;

    case 5:{ //Each case is a menu option

      line1 =   "Set dealy to:";
      line2 =   "500 hrs";
      printlcd();
      //Action:
      if (last_select == LOW && current_select == HIGH){ //When down button is pressed
            lcd.clear();
            line1 = "New Delay:";
            line2 = "500 hrs";
            printlcd();

            digitalWrite(LED,HIGH);
            delay(500);
            digitalWrite(LED,LOW);
            delay(3000);
            lcd.clear();
        }
    }
    break;

    case 6:{ //Each case is a menu option

      line1 =   "Set dealy to:";
      line2 =   "600 hrs";
      printlcd();
      //Action:
      if (last_select == LOW && current_select == HIGH){ //When down button is pressed
            lcd.clear();
            line1 = "New Delay:";
            line2 = "600 hrs";
            printlcd();

            digitalWrite(LED,HIGH);
            delay(500);
            digitalWrite(LED,LOW);
            delay(3000);
            lcd.clear();
        }
    }
    break;

    case 7:{ //Each case is a menu option

      line1 =   "Set dealy to:";
      line2 =   "700 hrs";
      printlcd();
      //Action:
      if (last_select == LOW && current_select == HIGH){ //When down button is pressed
            lcd.clear();
            line1 = "New Delay:";
            line2 = "700 hrs";
            printlcd();

            digitalWrite(LED,HIGH);
            delay(500);
            digitalWrite(LED,LOW);
            delay(3000);
            lcd.clear();
        }
    }
    break;

    case 8:{ //Each case is a menu option

      line1 =   "Back";
      line2 =   "";
      printlcd();
      //Action:
      if (last_select == LOW && current_select == HIGH){ //When down button is pressed
            lcd.clear();
            line1 = "Returning";
            line2 = "";
            printlcd();

            digitalWrite(LED,HIGH);
            delay(500);
            digitalWrite(LED,LOW);
            delay(3000);
            lcd.clear();
        }
    }
    break;

  }//switch end

}

void setup() {
  // put your setup code here, to run once:
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0,0);
  lcd.print("Menu Test");
  delay(3000);
  lcd.clear();
}

void loop() {

  Menus();
}

So, my first question is: What is going wrong with the submenu?
and my second question is: in the submenu, how do I exit back to main menu?
Any assistance will be much appreciated.
Thank You.

your LCD screen display code repeats multiple times with differing parameters ..... use a function that accepts two strings for the two lines and a boolean for clearing screen

@jsotola Hi. I have updated the code with a function to handle the screen printing. the code is in the question. The issue is still there. When I select option 5 or option 6 of the main menu, the program directly sets the delay to option 5.1 without allowing the user to navigate then select.

the function i was talking about is in this form printlcd("Set 02", "Interval", true); ..... that would display the two lines ... the true means clear screen ..... see https://arduino.stackexchange.com/questions/3059/functions-with-string-parameters .... read the comment at the accepted answer

the break statements should be inside the case block (inside the {} brackets) .........checking your code for logic errors

@jsotola Thank you very much. I'll look into the function and put the break statements inside the case blocks. Did you find any logic errors?

use pointers bro it will handle your problem though

you can use a menu library, there are many on github... my fav. ofcoz https://github.com/neu-rah/ArduinoMenu


text:
How to exit while loop using keypad?
I can't seem to be able to escape a while loop using a keypad button. I've tried the solution from this thread: https://forum.arduino.cc/index.php?topic=79932.0
Here's my code:
void alarm(){
  char customKey = customKeypad.getKey();

  while (customKey == NO_KEY){
    customKey = customKeypad.getKey();
    lcd.noDisplay();
    delay(750);// change for faster flash
    lcd.display();
    delay(750);// change for faster flash
  }
  lcd_home_screen();
}

I tried both == and != for the while (customKey == NO_KEY)
Additional info:
I am calling this alarm function from another function inside my Loop.
Here's the complete code:
void loop() {
  // keypad
  char customKey = customKeypad.getKey();
  if (customKey == 'A'){
    main_program(5);
  }
}

int main_program(int duration){
  timer(duration);
  alarm();
}

Because you're using delay() within your while loop you have to ensure that you are pressing the key at the precise moment it is read.
You should not use delay().
Instead take a look at the BlinkWithoutDelay example in the IDE. And also consider implementing a Finite State Machine to know both if you're blinking and what state you're blinking currently is in.

Your solution of BlinkWithoutDelay makes a lot of sense and is more reachable for my level of knowledge, thank you. My blockage now is the problem that I cannot bool the lcd.Display and noDisplay functions. In the BlinkWithoutDelay example, the code checks for low or high pin output, but in my case I have to check if my lcd is on Display or noDisplay. How can i check that? I'll post the new code if what I just wrote is not clear.

Nevermind, I made it work with a dummy boolean variable. BlinkWithoutDelay was the way to go. Thank you!

To elaborate on Majenko's answer,  you can create some enumeration types for the states, e.g.
enum EAlarmState
{
   On,
   Off
};

EAlarmState _alarmState = EAlarmState::Off;

enum EBlinkState
{
    BlinkOn,
    BlinkOff,
};

EBlinkState _blinkState = EBlinkState::BlinkOff;

unsigned int long _lastBlinkTime = 0;

The _blinkState and _lastBlinkTime state will not be checked when _alarmState is off.
Now you can use something like this to check the states and the keypad (pseudo code):
void loop()
{
    checkKeypad();

    switch (_alarmState)
    {
    case EAlarmStateOn:
       if (millis() - _lastBlinkTime) >= 750)
       {
          `Blink off code`
          switch(_blinkState)
          {
          case EBlinkStateOn:
             _lastBlinkTime = millis();
             'Blink off code'
             _blinkState = EBlinkState::Off;
             break;

          `same for case EBlinkStateOff'
             break;

          default: // Error
             break;
          }
       }

And also create state checking and changing for the alarm itself.
It looks like a lot of code (and it will be), so split it in sub functions. But the most important is that the code is fairly easy to read (and thus maintain).

I tried to copy/paste your code, but since I don't understand what is going on, I could not make it work. I pasted the top part of your code before the Setup() function, and the bottom part in the while loop inside my alarm() function. I now face the following error msg "expected initializer before '_blinkState'

I forgot the semi colon after the second enum. I don't have a compiler at hand

You also should get rid of the while statement. Don't block your code for long or indetermined time.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Is Arduino Ethernet shield compatible with arduino due?
Arduino Due's operating voltage is 3.3 volt and Ethernet shield operates on 5 volt supply. So my question is that this Ethernet shield will work on an Arduino Due and also if it will not harm the Arduino Due board due exceeding the operating voltage?

The Arduino Ethernet shield (or at least V2 of it) is based on a W5500 chip which itself features "3.3V operation with 5V I/O signal tolerance".  In other words, the core of it already is a 3.3v device, just one that can tolerate connection to a 5v Arduino.
Of course the shield is more than just the chip.  A very quick look isn't showing any glaringly obvious uses of 5v levels on the board in a place where a 3.3v Arduino derivative wouldn't expect them.
However, you should review the the full schematics and make your own determination that these are applicable to the specific board you plan to use and do not place 5v level on any signal the Due could not accommodate.
It's unfortunate that the shield documentation doesn't seem to say anything about compatibility, but worth noting the the Ethernet Library has some specifics for the SAM family of chips one of which is used on the Due.

The Ethernet Shield V1 was based on the W5100 chip.  This may not have 5v tolerant inputs, as it appears to use level translation on the input side.  But it is also powered from 3.3v, so likely the outputs would be fine for a Due.  An interesting question is if the V1 shield would be damaged if connected to a 5v Arduino with a sketch that erroneously drove MISO high as an output.

Of course it will harm your due. Now for that problem you could use a 3.3v to 5v and vice versa level converter.

This is simply false.  The W5500 features "3.3V operation with 5V I/O signal tolerance"

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Vcc measurement with internal 1.1V reference fails on 3.3V powered Atmega328
I need to monitor a battery plugged to an ATmega running on standalone mode.
I use the "ATmega on a breadboard (8 MHz internal clock)" bootloader.
More info here
When the ATmega is powered with 5V the sketch outputs good values : arround 5100 mV.
But when I power it with 3.3V the sketch gives strange values : arround 178619 mV.
Here is my code Inspired from here
void setup()
{
  Serial.begin(9600);
  Serial.println(F("Internal Voltage Sensor"));
}

void loop()
{
  Serial.println( readVcc());
  delay(1000);
}

long readVcc()
{
  long voltage=0;
  uint8_t wADC;

  // Read 1.1V reference against AVcc
  // set the reference to Vcc and the measurement to the internal 1.1V reference
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  ADCSRA |= _BV(ADEN);  // enable the ADC

  delay(20); // Wait for Vref to settle

  ADCSRA |= _BV(ADSC); // Start conversion
  while (bit_is_set(ADCSRA,ADSC)); // measuring

  // Reading register "ADCW" takes care of how to read ADCL first and ADCH then.
  wADC = ADCW;

  voltage = 11253000L / wADC; // Calculate Vcc (in mV); 1125.3 = 1.1*1023*1000
  return voltage; // Vcc in millivolts
}

I don't understand what's going on. The returned value with Vcc=3.3V should be lower than with VCC=5V. Something like 3300 mV !

Try adding some more Serial.printlns to you code. E.g. Serial.println(wADC);

ADCL is the lower byte, ADCH is the higher byte, and the must be read ADCL first and then ADCH. The ADCW tells the compiler to read the two bytes in the right order. Using ADCW is of course easier, and even better, because it can't go wrong... unless you try to put 16 bits of ADCW into a byte and throw away the higher byte. Make wADC a uint16_t.

Thanks for your answers!
Jot gave the solution: wADC must be a uint16_t.
Here is the corrected code :
void setup()
{
  Serial.begin(9600);
  Serial.println(F("Internal Voltage Sensor"));
}

void loop()
{
  Serial.println(readVcc());
  delay(1000);
}

long readVcc()
{
  long voltage=0;
  uint16_t wADC;

  // Read 1.1V reference against AVcc
  // set the reference to Vcc and the measurement to the internal 1.1V reference
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  ADCSRA |= _BV(ADEN);  // enable the ADC

  delay(20); // Wait for Vref to settle

  ADCSRA |= _BV(ADSC); // Start conversion
  while (bit_is_set(ADCSRA,ADSC)); // measuring

  // Reading register "ADCW" takes care of how to read ADCL first and ADCH then.
  wADC = ADCW;

  voltage = 1125300L / wADC; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000
  return voltage; // Vcc in millivolts
}

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Can I generate 5 sec delay within an interrupt program?
void buttonPressed()
{
  if(ledOn)
  {
    ledOn = false;
    digitalWrite(13,LOW);
  }else
  {
    ledOn = true;
    digitalWrite(13,HIGH);
  }

  vout=analogRead(sensor);
  vout=(vout*500)/1023;
  tempc=vout; // Storing value in Degree Celsius
  tempf=(vout*1.8)+32; // Converting to Fahrenheit
  lcd.setCursor(0,0);
  lcd.print("ROOM TEMPERATURE");

  lcd.setCursor(0,1);
  lcd.print("C = ");
  lcd.print(tempc);

  lcd.print("  F = ");
  lcd.print(tempf);
  Serial.print("f ");
  Serial.print(tempf);
}

here is the code of interrupt and i want to monitor the sensor value for about 5second.

You don't need interrupts for any of that. Your main loop just needs to test the switch, eg.
void loop ()
  {
  if (digitalRead (button) == HIGH)  // assuming LOW means pressed
     return;

  // read thermocouple here

  // display results

  delay (5000);

  }

I want to print the value of the thermistor on lcd using interrupts and i want the value to stay about 5 secs

You are misusing interrupts in what you are attempting. See my page about interrupts. You simply should not be attempting to print or delay inside an interrupt routine. The most you should do is detect that the switch is pressed:
volatile bool switchIsPressed = false;

// Interrupt Service Routine (ISR)
void buttonPressed()
  {
  switchIsPressed = true;
  }  // end of buttonPressed ISR

Now in your main loop you detect that the switch is pressed and take your reading. If you want to do something else "remember" the time you showed the value, like this:
unsigned long whenTemperatureDisplayed = 0;

void loop ()
  {
  if (switchIsPressed && whenTemperatureDisplayed == 0)
    {
    // take reading ...
    // display reading ...
    whenTemperatureDisplayed = millis ();  // when we displayed the reading
    switchIsPressed = false;               // ready for next time
    }  // end of if switch was pressed

  if (whenTemperatureDisplayed != 0 &&
      millis () - whenTemperatureDisplayed >= 5000) // 5 seconds are up
    {
    // stop displaying the reading ...
    whenTemperatureDisplayed = 0;
    }  // end of if time is up

  // do other stuff here

  }  // end of loop

I am making a temperature monitoring device Thermocouple is the main sensor and I am using thermistor for room temperature sensing. I want to print the value of the thermistor on lcd using interrupts and i want the value to stay about 5 secs. the code is working but i am unable to make a delay of about 5sec while staying on the interrupt

the code is working but i am unable to make a delay of about 5sec - it's working but it isn't, huh? The "not working" part is the part you have to completely rewrite. It isn't almost working. You are not doing it in a way that will work. See amended answer.

My amended answer does not do any delays, and thus you will not have any trouble doing other things, as well as displaying the temperature for 5 seconds.

It's bad practice to use a delay within a timer, and 5 seconds is a huge amount of time. Also print statements and possibly lcd print statements I would not advice.
What is better, is to calculate the value, store it in a global variable (vout?). Than set a boolean that a new value has been calculated.
Your main program checks the boolean and does all the print/lcd code.
If you think you might miss values, than create a global array where you add values in your interrupt, and let the main program process the array.

I am making a temperature monitoring device Thermocouple is the main sensor and I am using thermistor for room temperature sensing. I want to print the value of the thermistor on lcd using interrupts and i want the value to stay about 5 secs. the code is working but i am unable to make a delay of about 5sec while staying on the interrupt.

You can use a delay of 5 sec in your main, or what's even better is to use millis(). Check the blink Arduino program for an example.

delaying 5 sec in my main would cause a delay in the monitored value. I want the sensed temperature to be accurate with time and as well as the interrupt to stay about 5sec.

If you wait 5 sec in interrupt, your main is interrupted for 5 sec and will not do anything, until the interrupt ends. Interrupt would not help you the way you think it would. Use waiting without delay in main and do your measuring/displaying just there.

@PeouseDutta  delaying 5 sec in my main would cause a delay in the monitored value - delaying 5 seconds in the interrupt will also cause a delay in the monitored value, so you haven't achieved anything by delaying there. If you succeed in delaying inside the interrupt no other code will execute during that delay.

I have tried using the above code
unsigned long startMillis = millis();
while (millis() - startMillis < 5000);
but every time I press the buttom the LCD gets freezed. I don't know what to do!

if you do that, you have the same as a delay... you should not use a while but an IF statement, and than do something you want to do every 5  s.

Strictly speaking, yes you CAN generate 5 second delay in interrupt. But you really, really should NOT do it.
And if you are going to do it anyway, it could not be easily done with delay(), as Arduino supports only one level of interrupts and delay depends on interrupts enabled. (which can also be cheated away, but it should not be).
The right thing is use interrupt for fast detection of key pressed and manage other parts in loop(), see https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay how to wait in main, while doing other work.
Also using lcd and Serial inside interrupt can bring a lot of problems, especially if you are using it also in loop() (as the key can be pressed anytime and interrupt can well -interrupt- such commands in the loop and then make your output all wrong and possibly crash your program on the way too.)

Read http://gammon.com.au/interrupts if you want to know more about interrupts and why your idea is not the best possible way.
Question: Can I hit really hard my thumb with heavy hammer?
Answer: Yes, you can, but you really should not do it. There are much better ways for using thumbs and hammers.


text:
PushButton as LED Switch (does not work)
 #define LED 1//This pin goes to the LED
 #define SWITCH 7//From Switch$

void setup() {
      pinMode(LED,OUTPUT);
      pinMode(SWITCH,INPUT);
}
int state=0;//Initializing values of all three
int val;
int lastval=LOW;

void loop(){
      val=digitalRead(SWITCH);//Reads if switch is on or off
      if(val==HIGH&&lastval==LOW){//Basically activates if the button was just pressed
        state=1-state;//Changes state after button is pressed
        digitalWrite(LED,state);//Enforces changed state to LED on or off
        delay(50);//Just a simplistic debouncing
      }
      lastval=val;//Store last value
}

SO basically, it does turn on and off sometimes, but not always on the button press. It seems a wee bit arbitrary. I wait for a second between presses.
Any help at all is apprecaited

Can you please post that code in a more readable format?   I notice that you don't have any code to deal with switch bounce.  That's something you should look up.  Google "Arduino debounce".  I also notice that you're not using the internal pull-up resistors.  Do you have pull-up or pull-down resistors on your button?  How is it wired?

Hey Delta_G, thank you for taking the time to respond. I have tried to redo the code on the question, but could not get the indents to work properly, sorry.
I have used a delay to deal with the bouncing, in a very rudimentary fashion.
I have it wired to a 10kOhm resistor in series with the LED between 1 and GND.
Finally I have a wire going to a pushbutton from the 5V supply, and from the button to the Pin 7 (Input pin, or SWITCH in the code).

Sounds like your input is floating. Read the Arduino tutorial on buttons.

Thank you Mr. Majenko. I will read up on this and see what I can do about it. Would you have any suggestions about dealing with such an input, as I see several on google and was wondering which would be recommended.

Just wanted to update on the fact that adding _PULLUP next to my switch input in pinMode, and connecting the switch to ground did the trick. I am not 100% sure on why this is true, but thank you very much for your help, Mr. Majenko, and Mr. Keijzers.

Based on your response to my comment, it sounds like you have a floating input.  When the button is NOT pressed, the pin isn't connected to ground or 5V so it is floating and picking up whatever stray electrical signals happen to be bouncing around the room.
The easiest way to handle buttons on an Arduino is to wire them between the pin and ground.  Then in the code you use INPUT_PULLUP instead of INPUT for the pinMode call.  Once you've done that then the pin will reliably read HIGH when the button is NOT pushed and will read LOW when the button IS pushed.  Note that this is backwards of how newbies tend to think, but is really the more common way to handle a button.

Thank you very much Delta_G, the explanation was really helpful. Can the floating cause stray signals to interfere on the scale of a few volts as well?

I think the problem is in the lastval assignment and checking. During the bouncing, lastval will probably change several times. Within these changes the if statement is checked. If an even amount of changes are detected, the LED will change 4 times (being OFF again if it was OFF and On when On). Even if the user clicked possibly only one time. When an uneven amount of changes are detected it will be ok. So it's kind of luck when it works.
Use a proper debouncing technique (checking for some time if the switch is high or low and act on that directly).
Also do not use a boolean to flip that way, if you want it use a proper boolean:
boolean state;

...

state = !state;

However, I suggest using something like:
digitalWrite(LED, state ? HIGH : LOW); // HIGH if state is true, else LOW

And change the if condition in a proper debouncing check (plenty of examples, e.g. Arduino debouncing switch).

In the lastval assignment, I have pushed the assignment of the last val out by 50ms by delaying the running of the rest of the code. Shouldn't that mean that lastval only changes 50ms later? You are probably exactly right, as it does seem to be luck when it works, but I can't grasp why the delay wouldn't avoid it.
Also, I will change the state as prescribed. Thanks a bunch Mr. Keijzers.

You are right ... probably Majenko has the real reason: your input might be floating ... try adding a pullup or pull down resistor (as a test, print the state continuously, remove the delay temporarily and check if the button really shows false or true when you depress and press it).


text:
Voice recognition without module, is it possible?
I'm trying to figure out how to process a voice signal for simple purposes. Wherever I look people using or suggesting recognition modules for Arduino.
What I'm wondering: is this possible to make a simple command recognition with Arduino, without modules?
I just simply want to attach a microphone to my Arduino and after I convert it I want to handle signal and program it in MATLAB or in an Arduino itself. How can I achieve that?
As you can see I'm newbie in this. Any help is appreciated. Thanks!

Perhaps, for an extremely crude meaning thereof - years ago, Radio Shack used to sell a fixed function IC that purported to recognize a few commands.  But how is an algorithms question far beyond the scope of the Arduino site.  If you wanted to seriously do this, you'd start by proving your algorithms on a PC taking data from the sound card, while keeping the limitations of a platform like the ATmega in mind.

No, it's not possible. The Arduino is not powerful enough to run the algorithms needed.
You need something with far more processing power, memory and storage. Something like a Raspberry Pi, maybe, or a desktop PC.
Or just use one of the many commonly available VR modules you can buy on the internet for next to nothing.

The erroneous idea than an Arduino is not a computer is only viable in people who aren't trying to learn to use an Arduino, which presumably excludes the entire audience here.  Those that are need to quickly learn that Arduino programming is computer programming constrained by limited resources.  In the process they might discover that they're well on their way to being able to program their PC as well (apparently almost all the way there if they use something like Processing)

@ChrisStratton There are certain fundamental differences between an Arduino and the popular conception of what a computer is. Most notably is the lack of an operating system. The device that everyone thinks of as a computer (aka PC, Mac, Whatever) runs an operating system. Agreed, there are devices that blur the line between a "computer" and an "embedded computing device", such as the Pi, but the Arduino is so far away from that line that you can completely ignore it.

No, you can't - because it's not a line but rather a spectrum.  Some peole run operating systems like freertos on basic Arduinos.  Some of the same hardware that better runs freertos can also run Linux.  Some of the hardware that better runs Linux can also run other PC operating systems...  To actually understand these things, you have to be willing to see how they fall in connection to one another - treat them in isolation, and you'll never truly understand either.

@ChrisStratton I know that, and you know that. The users that struggle to even comprehend that they have the computing equivalent of a robin reliant in their hands really don't need to know that sort of thing. They need to be told that they have a robin reliant, not a jaguar. They think that just because it's a programmable device it's capable of the same things as the computer on their desk. It's not. And no amount of arguing about spectrums, etc, is going to change that. Ever. Ever ever. Full stop. Exclamation mark. 5 seconds of basic reading would set them straight, but they don't.

Sadly, that's never an easy thing to do as it seems like. I have tried with microphone , amplifier, ADC , and an EEPROM to store patterns of voltage produced by a human voice for different people. But it looked unreliable in the end. EasyVR is a popular voice recognition module usually used with UNO.


text:
Powering arduino and node mcu
I want to power up my Arduino and my Nodemcu via 12 V , 1 A power adapter (it's an AC to DC power Adapter).
Recently I have two voltages regulators: a 5 V for nodemcu and 9 V for Arduino Uno.
The question is does the 1A affect both boards or not?

In principle not. However, the voltage regulators may become quite hot, since you are going down from 12 V to 9 V and 5 V (especially the step from 9 V to 5 V is quite a lot). It depends on the current (in (milli)Amps) how hot they get.
For the adapter it does not matter, if it is 1 A or 10 A, the microcontrollers will only take whatever they need. Only if the adapter can deliver less than needed by both microcontrollers there is a problem.
The voltage regulators are not of switching type I guess, so they will use the same amount of amperes. Assuming the Arduino Uno takes 300 mA (at 5 V) and the NodeMCU 200 mA (at 12 V), you can add them together: 200 mA + 300 mA = 500 mA. Since this is less than 1 A the adapter can deliver, you are ok.


text:
FastLED fill_rainbow - Unexpected red pixel
I'm using FastLEDs builtin fill_rainbow function for generating a rainbow spectrum on an LED strip. The issue is, I get a random red pixel midway through the yellow region. I've tried it on 3 different Arduino nano's, and two different LED-strips. Here's the code:
#include <FastLED.h>

#define DATA_PIN 2
#define NUM_LEDS 114
CRGB leds[NUM_LEDS];

uint8_t hue = 0;

void setup() {
  Serial.begin(115200);
  FastLED.addLeds<WS2812B, DATA_PIN, GRB>(leds, NUM_LEDS);

  fill_rainbow( leds, NUM_LEDS, hue, 1);
  for(int i=0; i<NUM_LEDS; i++) {
    Serial.print(i);
    Serial.print(' ');
    Serial.print(leds[i].r);
    Serial.print(' ');
    Serial.print(leds[i].g);
    Serial.print(' ');
    Serial.println(leds[i].b);
  }

  CHSV hsv;
  CRGB rgb;
  //rgb = hsv;
}

void loop() {
  fill_rainbow( leds, NUM_LEDS, hue, 1);
  FastLED.show();
}

Here pixel number 60 gets the rgb code 160, 0, 0. When it should have something like 160, 150, 0.
The strangest part of all is that I can get rid of the problem in two ways, either by uncommenting the line rgb = hsv;, or by commenting out the fill_rainbow function in the loop function. This strange behavior leads me to believe im somehow messing up a pointer or misusing a FastLED feature. Additionally the fill_rainbow function is very simple and relies on FastLEDs hsv to rgb typecasting, which is another reason to believe I'm doing something wrong.
So help me out here, am i doing something silly, or have I discovered a bug with FastLEDs hsv to rgb converter?

Issues with a specific third-party library are best raised with the author of the library. Raise an issue here.

@Majenko Sure, but the reason for posting the question is i suspect i made a mistake, as explained in the latter part of the question. I'm hoping to get some feedback on weather I have made a mistake before posting an issue at the developer.

I just copied your exact code and ran it with 600 of my LEDs. I have WS2812B as well, and using the same data pin coincidentally.
I haven't experienced your red LED issue. I then ran it again on my LEDs after adding
 hue++;

at line 33.
Only problem I can see is that the last 30 LEDs at the end of the rainbow kind of flicker. Groups of 10 LEDs spontaneously flicker at once, then another 10, and so on. This could be a problem with my LEDs though because they were the cheapest one's I could find on ebay 2 years ago. The code seems to work fine for me though!

It seems that this is caused by a compiler bug when compiling with the default -Os (optimize for size) option.
see Issue : fill_rainbow() - Unexpected red pixel #668
A workaround is to change the optimization level to -O3 for fill_rainbow, ie :
#pragma GCC push_options       // Disable the size optimization
#pragma GCC optimize ("-O3")   // to prevent the “red pixel” problem
void fill_rainbow( struct CRGB * pFirstLED, int numToFill,
                  uint8_t initialhue,
                  uint8_t deltahue )
{
    CHSV hsv;
    hsv.hue = initialhue;
    hsv.val = 255;
    hsv.sat = 240;
    for( int i = 0; i < numToFill; i++) {
        pFirstLED[i] = hsv;
        hsv.hue += deltahue;
    }
}
#pragma GCC pop_options // Enable the prior optimization

You would have to edit colorutils.cpp (the file where fill_rainbow lives above) in the FastLED source in your \libraries directory.


text:
Arduino Gesture Sensor error:No such file or directory
I cloned https://github.com/sparkfun/APDS-9960_RGB_and_Gesture_Sensor
and copied the libraries into the Arduino libraries folder. I then launched Arduino and selected the example. I opened the file GestureTest and when I started upload I received this error:

GestureTest.ino:49:31: fatal error: SparkFun_APDS9960.h: No such file or directory
compilation terminated.

I checked the SparkFun_APDS9960.h and I found it in the Gesture_Sensor/Libraries/src folder.
Is there a solution to resolve this error?

SparkFun made a poor choice for the folder structure of that repository. Likely this has caused you to incorrectly install the library. Please follow these instructions:

Download the latest release from https://github.com/sparkfun/APDS-9960_RGB_and_Gesture_Sensor/releases. Currently it is https://github.com/sparkfun/APDS-9960_RGB_and_Gesture_Sensor/archive/V_H1.0_L1.4.2.zip.
Unzip the downloaded file.
Rename the folder APDS-9960_RGB_and_Gesture_Sensor-V_H1.0_L1.4.2/Libraries/Arduino to SparkFun_APDS9960. This is not absolutely necessary but "Arduino" is not a very descriptive name for a library folder and the Arduino IDE works best when the library folder name matches the primary header file name so this is best practices.
Copy the SparkFun_APDS9960 folder to {sketchbook folder}/libraries. You can find the location of the sketchbook folder at File > Preferences > Sketchbook location.
Restart the Arduino IDE if it's running (not necessary with recent versions of the Arduino IDE).

Note that the folder structure of this library requires Arduino 1.6.x or newer.
UPDATE: I submitted a pull request to put the library in an appropriately named folder. This won't change the instructions above until the next release but it does remove the need to rename the folder if you are cloning the repository or downloading from the tip of the repository rather than a release.


text:
Declaring Variables in a For Loop
I am trying to use a for loop for getting readings on two parallax ping sensors and want to find the difference between both readings.
But am having trouble doing so. Whenever I declare print ping(1), I don't actually get the value of ping(1). How can I have two variables for ping(0) and ping(1) that I can call whenever I want and have them be accurate.
Code
int ultraSoundSignalPins[] = {5,7};
int tx = 4;
char *pingString[] = {"Ping1 ","Ping2 "}; // just something to print to indicate direction

void setup()
{
 Serial.begin(9600);
}

void loop()
{

 unsigned long ultrasoundValue;
 for(int i=0; i < 2; i++)
 {
   ultrasoundValue = ping(i);
   Serial.print(pingString[i]);
   Serial.print(ultrasoundValue);
   Serial.print("cm, ");
   delay(500);

 }
}

//Ping function
unsigned long ping(int i)
{
 unsigned long echo;

 pinMode(ultraSoundSignalPins[i], OUTPUT); // Switch signalpin to output
 pinMode(tx, OUTPUT);
 digitalWrite(ultraSoundSignalPins[i], LOW); // Send low pulse
 digitalWrite(tx, LOW);
 delayMicroseconds(2); // Wait for 2 microseconds
 digitalWrite(ultraSoundSignalPins[i], HIGH); // Send high pulse
 digitalWrite(tx, HIGH);
 delayMicroseconds(5); // Wait for 5 microseconds
 digitalWrite(ultraSoundSignalPins[i], LOW); // Holdoff
 pinMode(ultraSoundSignalPins[i], INPUT); // Switch signalpin to input
 digitalWrite(ultraSoundSignalPins[i], HIGH); // Turn on 0pullup resistor
 echo = pulseIn(ultraSoundSignalPins[i], HIGH); //Listen for echo
 return (echo / 29.1); //convert to CM then to inches
}

Your question is not very clear. Where did you put the print statement, what did you expect, and what did get printed instead?

I'd convert ultrasoundValue into an array, just like ultraSoundSignalPins. That way you can retrieve both values using ultraSoundSignalPins[0] and ultraSoundSignalPins[1]

can you maybe lead me to how i would do that

unsigned long ultrasoundValue[2] and ultrasoundValue[i] = ping(i);.


text:
ISR executes twice if data coming through SoftwareSerial
I am using Arduino Pro Mini to get GPS info from a u-blox NEO-M8N chip and display it on a Adafruit OLED display. NEO-M8N has a PPS(pulse per second) output which is aligned to GPS's second. Because UART and deserialization is slow, I use PPS signal to make time displays more accurately. The PPS(time pulse) signal and UART message are coming like this:

On my Arduino, SoftwareSerial RX/TX is on pin 7/8 (but only use pin 7 because Arduino has no message to send to NEO-M8N), and the interrupt(PPS) is on pin 2. If I just connect pin 7, display update once per second as intended; if I just connect pin 2, time increased by one second per second as intended. BUT if connect them both, ((time will increased more than one second per second) and ( processGPS() will lost sync with upcoming UBX(u-blox message format) message)) occasionally.
And here is the entire code:
#include <SoftwareSerial.h>
#include <Adafruit_SSD1306.h>

#define OLED_RESET 9
Adafruit_SSD1306 display(OLED_RESET);

#if (SSD1306_LCDHEIGHT != 64)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif

// Connect the GPS RX/TX to arduino pins 7 and 8
SoftwareSerial S_Serial = SoftwareSerial(7,8);
int intpin = 2;
volatile int state = LOW;

const unsigned char UBX_HEADER[] = { 0xB5, 0x62 };

struct NAV_PVT {
  unsigned char cls;
  unsigned char id;
  unsigned short len;
  unsigned long iTOW;
  unsigned short year;
  byte month;
  byte day;
  byte hour;
  byte miniute;
  byte sec;
  unsigned char valid;
  unsigned long tAcc;
  long nano;
  byte fixType;
  unsigned char flag;
  unsigned char flag2;
  byte numSV;
  long lon;
  long lat;
  long height;
  long hMSL;
  unsigned long hAcc;
  unsigned long vAcc;
  long velN;
  long velE;
  long velD;
  long gSpeed;
  long headMot;
  unsigned long sAcc;
  unsigned long headAcc;
  unsigned short pDop;
  byte reserved1[6];
  long headVeh;
  byte reserved2[4];
};

NAV_PVT pvt;

void calcChecksum(unsigned char* CK) {
  memset(CK, 0, 2);
  for (int i = 0; i < (int)sizeof(NAV_PVT); i++) {
    CK[0] += ((unsigned char*)(&pvt))[i];
    CK[1] += CK[0];
  }
}

bool processGPS() {
  static int fpos = 0;
  static unsigned char checksum[2];
  const int payloadSize = sizeof(NAV_PVT);

  while ( S_Serial.available() ) {
    byte c = S_Serial.read();
    if ( fpos < 2 ) { //SYNC
      if ( c == UBX_HEADER[fpos] )
        fpos++;
      else
        fpos = 0;
    }
    else {
      if ( (fpos-2) < payloadSize )
        ((unsigned char*)(&pvt))[fpos-2] = c;

      fpos++;

      if ( fpos == (payloadSize+2) ) {
        calcChecksum(checksum);
      }
      else if ( fpos == (payloadSize+3) ) {
        if ( c != checksum[0] )
          fpos = 0;
      }
      else if ( fpos == (payloadSize+4) ) {
        fpos = 0;
        if ( c == checksum[1] ) {
          return true;
        }
      }
      else if ( fpos > (payloadSize+4) ) {
        fpos = 0;
      }
    }
  }
  return false;
}

void pps()
{
  state=!state;
}

void PrintScreen()
{
  display.clearDisplay();

  //Size 2
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(0,0);
  float sik = (pvt.gSpeed / 100) / 3.6f;
  if (sik<100)
    display.print(" ");
  if (sik<10)
    display.print(" ");
  display.print(sik,1);//SpeedInKph
  display.setCursor(84,0);
  if (pvt.numSV<10)
    display.print(" ");
  display.print(pvt.numSV);//SV

  //Size 1
  display.setTextSize(1);
  display.setCursor(60,8);
  display.print("km/h");
  display.setCursor(63,0);
  display.print("CHL");
  display.setCursor(108,8);
  display.print("SVs");
  display.setCursor(108,0);
  switch (pvt.fixType){
    case 0:
      display.print("N.F");
      break;
    case 2:
      display.print("2D");
      break;
    case 3:
      display.print("3D");
      if ((byte)pvt.flag & 2)
        display.print("+");
      break;
    default:
      display.print("INV");
      break;
  }

  long  temp;
  //Line 1
  display.setCursor(0,16);
  if (pvt.lat >= 0)
    temp = pvt.lat;
  else
    temp = -pvt.lat;
  if (temp >= 1000000000)
    display.print("lat:");
  else
    if (temp >= 100000000)
      display.print("lat: ");
    else
      display.print("lat:  ");
  display.print(temp / 10000000);display.print(".");
  long temp2 = 1000000;
  temp = temp % 10000000;
  while ((temp / temp2 == 0)&&(temp2>1))
  {
    display.print("0");
    temp2 /= 10;
  }
  display.print(temp);
  if (pvt.lat >= 0)
    display.print("N");
  else
    display.print("S");
  temp = 10000;
  while (((pvt.pDop / temp) == 0)&&(temp>1))
  {
    display.print(" ");
    temp /= 10;
  }
  display.println(pvt.pDop);

  //Line2
  if (pvt.lon >= 0)
    temp = pvt.lon;
  else
    temp = -pvt.lon;
  if (temp >= 1000000000)
    display.print("lon:");
  else
    if (temp >= 100000000)
      display.print("lon: ");
    else
      display.print("lon:  ");
  display.print(temp / 10000000);display.print(".");
  temp2 = 1000000;
  temp = temp % 10000000;
  while ((temp / temp2 == 0)&&(temp2>1))
  {
    display.print("0");
    temp2 /= 10;
  }
  display.print(temp);
  if (pvt.lon >= 0)
    display.print("E");
  else
    display.print("W");
  display.println(" HEAD");

  //Line3
  display.print("hMSL:");
  if (pvt.hMSL < 0)
    pvt.hMSL = -pvt.hMSL;
  temp = 10000000;
  while (((pvt.hMSL / temp) == 0)&&(temp>1000))
  {
    display.print(" ");
    temp /= 10;
  }
  display.print((pvt.hMSL % 100000000) / 1000);display.print(".");
  if ((pvt.hMSL % 1000) < 100)
    display.print("0");
  if ((pvt.hMSL % 1000) < 10)
    display.print("0");
  display.print(pvt.hMSL % 1000);
  display.print("|");
  temp = pvt.headMot / 100000;
  if (temp < 100)
    display.print(" ");
  if (temp < 10)
    display.print(" ");
  display.print(temp);display.print(".");
  temp2 = (pvt.headMot%100000)/1000;
  if (temp2<0)
    temp2 = -temp2;
  if (temp2<10)
    display.print("0");
  display.println(temp2);

  //Line4
  display.print("h,vAcc:");
  if (pvt.hAcc >= 100000)
    display.print("  >100");
  else
  {
    display.print(pvt.hAcc / 1000);display.print(".");
    if (pvt.hAcc % 1000 < 100)
      display.print("0");
    if (pvt.hAcc % 1000 < 10)
      display.print("0");
    display.print(pvt.hAcc % 1000);
  }
  display.print(",");
  if (pvt.vAcc >= 100000)
    display.print(" >100");
  else
  {
    display.print(pvt.vAcc / 1000);display.print(".");
    if (pvt.vAcc%1000 < 100)
      display.print("0");
    if (pvt.vAcc%1000 < 10)
      display.print("0");
    display.print(pvt.vAcc%1000);
  }
  display.println("m");

  //Line5
  display.print("V:");
  if (pvt.gSpeed < 1000000)
    display.print(" ");
  if (pvt.gSpeed < 100000)
    display.print(" ");
  if (pvt.gSpeed < 10000)
    display.print(" ");
  display.print((pvt.gSpeed % 10000000)/1000);display.print(".");
  if (pvt.gSpeed % 1000 < 100)
    display.print("0");
  if (pvt.gSpeed % 1000 < 10)
    display.print("0");
  display.print(pvt.gSpeed % 1000);
  display.print("m/s");
  if (pvt.sAcc < 1000000)
  {
    if (pvt.sAcc < 100000)
      display.print(" ");
    if (pvt.sAcc < 10000)
      display.print(" ");
    display.print("~");
    display.print(pvt.sAcc / 1000);display.print(".");
    if (pvt.sAcc % 1000 < 100)
      display.print("0");
    if (pvt.sAcc % 1000 < 10)
      display.print("0");
    display.println(pvt.sAcc % 1000);
  }
  else
  display.println(" ~>100");

  //Line6
  if ((pvt.year<10000)&&(pvt.year>=1000))
    display.print(pvt.year);
  else
    display.print("????");
  display.print("/");
  if ((pvt.month<=12)&&(pvt.month>=1))
  {
    if (pvt.month < 10)
      display.print("0");
    display.print(pvt.month);
  }
  else
    display.print("??");
  display.print("/");
  if ((pvt.day<=31)&&(pvt.day>=1))
  {
    if (pvt.day < 10)
      display.print("0");
    display.print(pvt.day);
  }
  else
    display.print("??");
  if (pvt.valid & 0x04)
    display.print("UTC");
  else
    display.print("INV");
  if ((pvt.hour<=23)&&(pvt.hour>=0))
  {
    if (pvt.hour < 10)
      display.print("0");
    display.print(pvt.hour);
  }
  else
    display.print("??");
  display.print(":");
  if ((pvt.miniute<=59)&&(pvt.miniute>=0))
  {
    if (pvt.miniute < 10)
      display.print("0");
    display.print(pvt.miniute);
  }
  else
    display.print("??");
  display.print(":");
  if ((pvt.sec<=60)&&(pvt.sec>=0))
  {
    if (pvt.sec < 10)
      display.print("0");
    display.print(pvt.sec);
  }
  else
    display.print("??");

  display.display();
}

void PrintSec()
{
  pvt.sec = (pvt.sec + 1)%60;
  display.fillRect(114,56,12,8,BLACK);
  display.setCursor(114,56);
  if (pvt.sec<10)
    display.print("0");
  display.println(pvt.sec);
  display.display();
  state = LOW;
}

void setup()
{
  S_Serial.begin(9600);
  pinMode(intpin, INPUT);
  attachInterrupt(digitalPinToInterrupt(intpin), pps, RISING);
  // by default, we'll generate the high voltage from the 3.3v line internally! (neat!)
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  // init done
}

void loop() {
  if (state == HIGH)
    PrintSec();
  if ( processGPS() )
    PrintScreen();
}

I found a similar issue here (Interrupt Service Routine Executes Twice ATmega88), but since ISR only executes once if I connect pin 2 alone, I think the cause might be something else.
Is it a software issue or a hardware issue? How to fix it?

How can you tell that time is increased more than one second per second? You you show some of the Serial output you get on your PC?

I show the time on an oled display, looks like this and the seconds was increased twice in one second sometimes, and other information on the display just froze. Normally, the lon(titude), lat(titude) and other positioning info are jittering all the time, so it is obvious when something goes wrong.

The ISR just won't be called twice from one interrupt. However your code is complex enough that what you observe is possible. For example, if state is HIGH, then you print the seconds, followed by reading the GPS (which also prints the seconds). This may well cause the seconds to update twice.

1) First, deferring PrintSec to loop through the volatile state, which is set by the ISR, actually takes more time to update the display.  You might as well just test the pin in loop:
void setup()
{
  S_Serial.begin(9600);
  pinMode(intpin, INPUT);

  // by default, we'll generate the high voltage from the 3.3v line internally! (neat!)
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
}

void loop() {

         bool state    = digitalRead(intPin);
  static bool oldState = false;

  // Watch for change
  if (oldState != state) {
    oldState = state;

    // RISING edge?
    if (state)
      PrintSec();
  }

  if ( processGPS() )
    PrintScreen();
}

2) "But I might miss a PPS!" you exclaim.  The bad news is that if you can't finish PrintScreen in time to get back to testing the pin, then you're Trying To Do Too Much.
You might want to consider incremental updates of the display.  If you have the previous pieces (i.e., an extra NAV_PVT struct), you could compare each piece to see if it has changed.  If it has, it's ok to spend time writing it.  Just add an extra test to each piece:
NAV_PVT pvt, prevPVT;
static bool firstTime = true;
  .
  .
  .
void PrintScreen()
{
  if (firstTime)
    display.clearDisplay();

  //Size 2
  display.setTextSize(2);
  display.setTextColor(WHITE);

  //  Update the Speed?
  if (firstTime || (pvt.gSpeed != prevPVT.gSpeed)) {
    display.setCursor(0,0);
    float sik = (pvt.gSpeed / 100) / 3.6f;
    if (sik<100)
      display.print(" ");
    if (sik<10)
      display.print(" ");
    display.print(sik,1);//SpeedInKph
  }

At the end of PrintScreen, do this:
  display.display();

  prevPVT   = pvt;
  firstTime = false;
}

For most updates, only the seconds field would get written.
Clearing the screen and drawing the labels could probably happen just once in setup.

3) I would suggest a more efficient and reliable software serial library.  SoftwareSerial disables all interrupts for the entire 10-bit character time, once the start bit is received.  This makes it both vulnerable and intrusive to other interrupts, like PinChange and SPI.  Ick.  If you can use pins 8 & 9, AltSoftSerial is the best choice.
If you can't use those pins, and you're not using the USB port to connect to a host, could you use Serial input (pin 0) for the GPS?  The GPS would have to be disconnected to do USB programming, but it could stay connected if you're using an ISP.

4) You need a more robust way to restart UBX packet framing, even if chars are lost.  I would suggest something like this:
void loop() {
  if (state == HIGH) {
    PrintSec();
    fpos = 0; // new packet coming soon, ditch old partial packet
  }
  if ( processGPS() )
    PrintScreen();
}

At least that will keep you in sync.  Without it, packet completion might not happen until after a 2nd PPS occurs (and 2nd packet begins arriving).  Maybe this explains the symptoms you're seeing?

I tried 3) first, and the hardware serial input works much better and never lose chars. But meanwhile, second was increased twice per second constantly. You are right, PrintSec was deferred to the loop, so the use of interrupt is meaningless. I tried 1) then, but the second still got increase twice sometimes.  I found this article, it says "Pin Change Interrupt Request 2 (pins D0 to D7)" shared the same interrupt vector, so I use pin 12 to receive PPS instead. The second will only get increase twice once every 3min now.

If i understand you correctly you have 2 ways that increase your seconds,

when software serial receives data
When PPM pin goes high

And when each of theese are run separately things work, but when you use them together seconds increase by 2 each time ?
wouldnt this suggest that your program only should use one of theese to increase your seconds.

No, I just have one way to increase my seconds, when PPS pin goes high. I GET the seconds from serial data. That is, when the PPS goes high, seconds++; when serial data comes, seconds = seconds_from_gps.

Maybe showing your complete code will clarify for us what is going on.

Ok, I just edited it.

You sure about this line: pvt.sec = (pvt.sec + 1)%60;

It increase the second by one. Use pvt.sec instead of a local variable to save some space.


text:
LM335Z temperature sensor gives very varying values
I'm trying to get consistent values from the LM335Z temperature sensor. But it behaves very strange.
I'm using an arduino nano and it's powered via USB from a Raspberry Pi. The circuit also has two little reed relays (SIP-1A05), a button and a potentiometer.
It's connected like this:

Additionally I'm using analogReference(EXTERNAL) in an attempt to get consistent values, so I've connected the Arduinos 5V output to the reference voltage pin.
Here's the code for reading the thermometer:
int getTemperature() {
  int rawvoltage = analogRead(0);
  float millivolts = (rawvoltage / 1024.0) * 5000;
  float kelvin = (millivolts / 10);
  float celsius = kelvin - 273.15;
  return round(celsius);
}

Then it just waits for me to say "get" in the serial monitor and it replies with:
void sendData(){
  String data = (String)getTemperature();
  data += ',';
  data += (String)map(getTablePos(), 0, 1023, 0, 100); //Potentiometer
  data += ',';
  data += (String)getTableActive(); //1 or 0
  Serial.println(data);
}

I also read somewhere that the first couple of readings are unreliable, and that you should read a couple of times in startup, which I do:
for(int i = 0; i < 10; i++){
    analogRead(0);
    delay(1);
  }

Yesterday the termometer reported 37 degrees. Today it started by reporting 49 degrees. After asking for the temperature a couple of times it said 56. Then now, about an hour later it says 52. And if one of they relays is active it says 77 degrees.
My two other (non Arduino) thermometers have ben on a steady 25 all this time.
What should I do to get reliable values from the LM335z?

Edit
Added dots to the intersections of the circuit diagram for better readability.
I've also found a way to get the thermometer to work, kind of. I removed the external analog reference and only have one 1kOhm resistor for the LM335Z.
Then I have this code instead:
const float cal = 4.62; //Voltage between 5V and GND, measured with multimeter

float getTemperature() {
    float input = (float) analogRead(0);
    input = (input*cal)/1024.0;
    return (input/0.01)-273.15;
}

It worked perfectly standalone on an Arduino Uno powered via USB3.0. When I moved it over into my project with the Nano it gave a few degrees off, but that can be combated by just subtracting the difference I guess.
Then I tried switching to a USB2.0-port on my keyboard, and the values started jumping all over the place.
Here's a comparison using Arduinos rather spartan plotter:

Left: USB2.0 via keyboard hub. Right: Front panel USB3.0.
Also, the temperature dubbels when a relay is on.
How do I tackle this? I'd like keep powering it from my Raspberry pi 3, if possible.

You may want to use a more stable reference. You're checking the 5V of the Arduino by taking it's 5V output to the analog-reference input? You could also just use the default in that case. You could use the internal "bandgap reference" which should always be 1.1V, even when the input voltage varies (which might be the case, I don't think it's a steady 5V?).

@Paul doesn't the thermometer and the potentiometer I have connected need to output between 0v and 1.1v if I use internal?

I believe not, you can check it againsts the 1.1V read this article by our user Majenko for more information (https://hackingmajenkoblog.wordpress.com/2016/02/01/making-accurate-adc-readings-on-the-arduino/#more-12)

According to your schematic, one of the LM335Z's leads is floating. The pins are meant to be Vcc, Gnd, and output; the output should go to an Analog input.
You wrote that Aref was tied to +5 but you've drawn it as going to one end of the pot with the other end of the pot grounded. The pot's wiper goes to A1 (assuming the pin hasn't been set to some other function).
In short, check your circuit. Try wiring up the sensor to +5, Gnd, and your DVM. Then replace the DVM with A0. At that point you'll have confirmed the sensor circuit, leaving only the code and the external analog circuitry. While I only skimmed the code I don't see anything that would give flaky results. I think you're seeing analog noise, probably due to one or more of the floating sensor pin, an inconsistent or noisy Aref, and pickup in the analog input from the sensor.
Update:
I based my connections description on this diagram

, from this datasheet. In all of those diagrams, the Resistor-Zener connection is shown as the output and no pins are shown floating. But I did see that pin labeled as adj, for what reason I don't know. That's really why I recommended getting the sensor working by itself first.
I see your +5V to Aref connection now. The usual convention for indicating a connection at such a crossing is to put a dot on the intersection, just as the output pin's connection is shown in the above diagram.

All the tutorials have shown that you only use two pins, and the datasheet says that it has adj + -. And adj is for offsetting if the value if off.
The pot is connected to the same 5V line as Aref, I don't now exactly how you show that lines are connected but I didn't draw a little loop in that intersection.

Thanks for expanding on your reply. I tried that without success. However, I found old code from when I first fiddled with the sensor, and that worked to some extent. I've updated the main post with details.


text:
Connect ethernet cable wires directly to pins
Is it possible to uncrimp a RJ45 plug and connect the wires directly to the Arduino pins? I guess I'd have to decrypt the ethernet signal then on my Arduino which might not have enough processing power at command for such a task.
I don't want to do it with an Ethernet shield, so please don't link any in the answers.

If it was that easy there wouldn't be any Ethernet shields around.  Ethernet is a complex system with specialist electrical requirements. It can't be interfaced direct.

I'm curious what you are trying to achieve.  Would you mind explaining?

@Butters i simply wanted to avoid the need of a shield and then i was curious if it would be possible. nothing exciting unfortunately :)

Does it need to be Etherenet, or is wireless okay?  You may be able to use the Adafruit Huzzah ESP8266 breakout.  Very flexible little chip, and way cheaper than an Uno and Ethernet shield.

I'm posting this question here because I do not have enough rep. Would you still be able to pass the communications through an unmanaged switch?

anything's possible: https://www.youtube.com/watch?v=XKnyAYKP434

Electrically, you don't have to worry about anything, as the previous answer stated, but Ethernet (Even 100Mbps FastEthernet, much less Gigabit) is way too fast for the Arduino to read.  digitalRead() is roughly 100x too slow, it takes roughly 4 microseconds, and even doing direct port reads is 5x too slow.  This doesn't take into account another operations, much less the fact that the clocks on the Arduino's don't run that fast.
100Mbps FastEtherent runs at roughly 31MHz, or 31,000,000 Hz.  That is FAST compared to our Arduino's, which have a clock speed of only 16MHz.
To answer your question in a word, no, it is not possible to do what you ask.

Ethernet is LVDS and requires isolation. You need some kind of extra hardware to turn that LVDS into a +5/GND signal. There is no ground in LVDS, so you cannot interface to it directly.

As others have stated, it's not physically possible for an Arduino to encode or decode standard Ethernet protocol messages over CAT5 cable with wires at one end connected directly to the Arduino pins, and the other plugged into a standard Ethernet device.
Standard Ethernet runs at least 10 Mbit/s for 10BASE-T, each bit Manchester encoded, so effectively 20 Mbit/s. See "TCP/IPv4 and Ethernet 10BASE-T/
100BASE-TX Debugging" for a lot of photos of what the standard Ethernet protocol looks like on an oscilloscope screen.
An Arduino running at 16 MHz can't sample a pin at 20 Mbit/s.
However, Arduinos can easily transmit and receive messages using a variety of other, slower communication protocols.
Devices that use such protocols can often be wired directly to the Arduino pins, with the Arduino programmed appropriately with that protocol.
Occasionally people use CAT5 cable (commonly called "ethernet cable") to carry those non-Ethernet messages from one device to another.
Sometimes people wire a RJ45 socket (also called a 8p8c socket) directly to an Arduino and corresponding RJ45 socket wired directly to the other device (often with a big "THIS IS NOT ETHERNET" warning on both sockets), and use standard off-the-shelf CAT5 patch cables with standard RJ25 plugs (also called 8p8c plugs) to carry those non-Ethernet messages between the sockets.
(For example, the connection between the Arduino-compatible "Motherboard 1.2 Generation 3" and the "Stepper Motor Driver 2.3 Generation 3" used in some early RepRaps; the TechZone Thermocouple A-D converter and other 1-wire devices that use the 1WRJ45 standard; etc.
As far as I can tell, none of the many CAT5 cables Nate connected to various Arduinos in "Lessons from Rebuilding Illumitune" actually carry any Ethernet messages.)
Sometimes people cut and strip the ends of CAT5 cable, using them as a convenient bundle of wires that can be used pretty much like any wire.
Hooking wires directly between two Arduinos (or an Arduino and some other device using some non-Ethernet protocol) often seems to work when both are plugged into the same power supply and connected by a short cable. The "extra hardware" people use to interface between an Arduino and a Ethernet network or CANbus or RS485 bus or MIDI or etc. helps avoid a variety of problems that happen when two devices are plugged into different power supplies or have long cable runs between them or both.

I am by no means an expert on this, this answer is ~20 minutes of me googling things, but I would say that in theory it is probably possible to do this with an arduino, at least at the lower transfer rates anyway, and certainly from a "will it kersplode my board" point of view - probably not since ethernet runs at +/- 2v (ish) and ~10mA (ish). However:
The ethernet protocol is exceedingly complex, with many layers needed to actually communicate with anything useful, all of which you would have to implement from scratch (there won't be a library to just drop in) and I'm not completely convinced that an entirely software-based implementation of the stack would fit on the arduino (but I could definitely be wrong there - and actually, on further thought, this probably is wrong, but I reckon I couldn't write it so it fit, but I'm a reasonably average human being).
Arduino is all about hacking and re-inventing wheels just for the fun of it but I am absolutely certain that there is no fun to be had re-engineering Ethernet and TCP/IP and all of the stuff in betweeen from scratch (obviously my opinion, I enjoy all sorts of things others don't, so YMMV).
My suggestion would be - if you don't like ethernet shields, look into getting a 'raw' ethernet controller chip (like the one soldered onto an ethernet shield) and build it directly into whatever device you're trying to make first, that'll give you plenty of exposure to how ethernet works at that level, then you can decide if you're still up for re-inventing the brain that invented the wheel. Good luck!

okay .. i might wanna reconsider if i want to do it without the shield :D I was just wondering if someone has ever done that .. would be a cool project for someone who wants to study TCP/IP though. thanks for the insight

What are you trying to achieve? There might be a more straightforward way to do it using the usb/serial connection to a computer or similar.


text:
Ping IP address using ESP8266 connected to Arduino
I want to make a system using NeoPixels, an Arduino and an ESP8266 module to ping IP addresses on my network to determine if certain people are on our Wi-Fi (I'll be pinging mobile phones).
I'm finding it hard to find any help as to how to ping IP addresses from an Arduino using the ESP8266 module. I did find the ICMP Ping library, but it uses the Ethernet shield, and I'm quite new to Arduino so I don't even know if I could modify the library in any way.
If anyone could help me on my way, that'd be great!

I'm not sure the AT firmware has ICMP facilities. You may need to write your own firmware.

AT+PING? https://cdn.sparkfun.com/assets/learn_tutorials/4/0/3/4A-ESP8266__AT_Instruction_Set__EN_v0.30.pdf, 16.
AT+PING – Function Ping, pp. 55.

From what I could find, it seems theres a command for pinging a server. It returns the number of milliseconds taken for the server to respond. The command is: AT+PING="web site" or AT+PING=<ip addr>, from 2 separate sources. You'll have to test them to see which (if not both) is correct.

This answer does not answer your question, but it implements the device you are describing. Unfortunately I don't have enough reputation to comment, so I will post it as an answer.
As people said before, ping is not a reliable option to scan the network. On Linux you can use dedicated (software) tools to scan the network, but even they struggle to reliably detect (some) mobile devices. So I wanted my router to do the work for me (at least it should reliably know which devices are logged into the Wi-Fi, right?).
Fortunately I have a Fritz!Box that provides an API to communicate with. Based on that API and an ESP8266 I build such a device you described in your question: [15min] Weasley Clock / Who is Home Indicator - based on TR-064 (beta).
To do that I wrote a library for Arduino to uses that API: Aypac/Arduino-TR-064-SOAP-Library.

It's too long for a comment anyway. :) I think we'll let it stand.

Not all devices (including) phones respond to ICMP Ping. This may differ for each (mobile) OS and version and phone make and model. But assuming your phone does respond to ping...
If you use the ESP with just the default firmware (a waste of a perfectly capable microcontroller), then indeed use the AT+PING command from the other answers.
If you use the ESP directly, you may be out of luck. Both the nocemcu lua firmware and the arduino api for esp seem to lack icmp ping functionality.


text:
MQ7 Flying Fish output format
I am new to Arduino project. I used MQ7 flying fish sensor to sense the CO.

Ok now I connected everything as mentioned in various tutorials, such as Arduino CO Monitor Using MQ-7 Sensor.
Also wrote this code based on the following tutorial
const int mq7Pin=0;//the AOUT pin of the CO sensor goes into analog pin A0 of the arduino

int mq7value;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);//sets the baud rate
  pinMode(mq7Pin, INPUT);
}

void Heat(){
  Serial.println("Heating sensor");
  analogWrite(mq7Pin,255);
  delay(60000);
  Serial.println("Reducing the voltage");
  analogWrite(mq7Pin,71); //HIGH*1.4v/5v => 255*1400/5000
  delay(90000);
}

void Read(){
  mq7value=analogRead(mq7Pin);
}

void Print(){
  Serial.print("CO : ");
  Serial.println(mq7value);
}

void loop() {
  // put your main code here, to run repeatedly:
  Heat();
  Read();
  Print();
  delay(60000);
}

After this I got the following output:
Heating sensor

Reducing the voltage

CO : 82

Heating sensor

Reducing the voltage

CO : 246

I used the sensor in a hall and I got 82 in clean air.
After that I used smokes from incense sticks, and I got 246 as sensor value.
So my question is in what format did sensor returned these values? Are they in PPM format?
If not, how can I convert it?

Looking at the datasheet, The output is logarithmic to the PPM. But you'd need to calibrate the outputs first, to get a accurate PPM value. I'm also not sure what the potentiometer and opamp(?) on that breakout are doing.

Sir any resources on how to calculate it. Most of the tutorial I saw prints  sensor value as ppm.

The link that you provided demonstrates/explains how to calibrate/adjust the voltage to PPM

I suspect some tutorials just slap a "ppm" after the value, and call it a day.

Thank you guys. I was confused with various tutorial saying the value was ppm. I know it was not that simple. And I also many tutorial with different kind of ppm calculation formula. Thank you for solving this confusion.


text:
HM-10 send and receive data and checking received value
I am wondering what is wrong with my code below. I have 2 issues.
The first issue, I am checking if c equals "hi" and if it does then display said hi. I currently see the output of c when it hits Serial.println(c); but never see the said hi even though Serial.println(c); does say "said hi".
The second issue is that when I start up the Arduino I am sending the AT command using bluetooth.println("AT");, but all it seems to do is display AT on the phone instead of OK as it should.

#include <SoftwareSerial.h>

SoftwareSerial bluetooth(8,9); // RX, TX

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.println("PC Side Connected");
  bluetooth.begin(9600);
  while (!bluetooth) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  bluetooth.println("Bluetooth Side Connected");
  bluetooth.println("AT"); // just a check
}

void loop() { // run over and over
  String c;
  if (bluetooth.available()) {
    //What is sent back from the BT module
    c = bluetooth.readStringUntil('\n');
    delay(10);
    Serial.println(c);
    if (c.equals('hi')) {
      Serial.println("said hi");
    }
  }
  if (Serial.available()) {
    //Send back data to Bluetooth module
    bluetooth.write(Serial.read());
  }
}

There’s nothing wrong with reading it just checking the value within the if statement.

@AltAir Why? .read() reads a single char not a string.

Could you edit the question and include the exact output please?

@MarkSmith picture added in the OP.

The first issue, I am checking if c equals "hi" and if it does then display said hi.

This is not how you compare:
  if (c.equals('hi')) {

Single quotes indicate a single (or multi-byte) character.  A character string (lower-case) is enclosed by double quotes:
  if (c == "hi") {

But it's better to avoid the String class (more info here).
To eliminate the String class, use char arrays instead (aka "C strings") and accumulate characters until the newline is received.  There are many, many C string functions for manipulating and searching.  In this specific case, you would use strcmp or strstr for comparison:
#include <AltSoftSerial.h>

AltSoftSerial bluetooth; // pin 8 is RX, pin 9 is TX

char btResponse[ 20 ];
uint8_t count;
const uint8_t BT_MAX = sizeof(btResponse);

void setup() {
  Serial.begin(9600);

  Serial.println("PC Side Connected");
  bluetooth.begin(9600);

  bluetooth.println("Bluetooth Side Connected");
  bluetooth.println("AT"); // just a check
}

void loop()
{
  if (bluetooth.available()) {
    // Read what is sent back from the BT module
    char c = bluetooth.read();

    if (c == '\n') {
      btResponse[ count ] = '\0'; // NUL-terminate the character array

      // Use C string functions to parse the response

      if (strcmp( btResponse, "hi" ) == 0) {
        Serial.println("only said hi");

      } else if (strstr( btResponse, "hi" ) != nullptr) {
        Serial.println("said hi, among other things...");

      }

      // And if there is a comma in there somewhere, display all comma-separated fields
      if (strchr( btResponse, ',' ) != nullptr) {
        uint8_t fieldNumber = 0;

        char *field = strtok( btResponse, "," );
        while (field != nullptr) {

          Serial.print( "Field " );
          Serial.print( fieldNumber );
          Serial.print( " = " );
          Serial.println( field );

          // Some fields might be numbers.  Parse them into integers.
          if ( isdigit( field[0] ) ) {
            int value = atoi( field );
            Serial.print( "  value = " );
            Serial.println( value );
          }

          // get next field
          field = strtok( nullptr, "," );
          fieldNumber++;
        }
      }

      // Reset the counter to receive another response
      count = 0;

    } else if (c >= ' ') {
      // Accumulate another non-control char, if there's room
      if (count < BT_MAX-1) {
        btResponse[ count++ ] = c;
      }
    }
  }

  if (Serial.available()) {
    // Send data to Bluetooth module
    bluetooth.write( Serial.read() );
  }
}

Notice that it shows how to use strtok to break the response string into individual fields, if a comma character is somewhere in the line.  For example, entering this:
hi,123,456

... produces this output:
said hi, among other things...
Field 0 = hi
Field 1 = 123
  value = 123
Field 2 = 456
  value = 456

It also uses AltSoftSerial for the BT connection.  SoftwareSerial is very inefficient, and it cannot send and receive at the same time.  It will lose received data while it is transmitting to the BT.  This can also interfere with other parts of your sketch or other libraries.
This answer has a good summary of the alternatives and how to select one.  Since you are already using pins 8 & 9, it would be easy to switch to the AltSoftSerial library.  All of the mentioned libraries are available from the Arduino IDE Library Manager, under the menu Sketch -> Include Library -> Manage Libraries.


text:
Data received by Arduino from ESP8266 01 Module is not complete
I am sending some data from ESP8266 01 module to Arduino. But the data received by Arduino is not complete.
Below are the images of the output from ESP8266 01 module and Arduino.

Here is the ESP8266 01 Module code:-
#include <ESP8266WiFi.h>
#include<String.h>

char c,e;                       //stores the bytes coming from the server
int DEBUG = 0;

int co=0;                       //control the sending of Alert

const char* ssid     = "ssid";            //your SSID of WIFI
const char* password = "password";       // password of Wifi
//--------------------------------------------

const char* host = "api.thingspeak.com";

void setup() {
  //dht.begin();
    Serial.begin(115200);
    delay(10);
  // We start by connecting to a WiFi network

    if (DEBUG){
      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);
  }

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    if (DEBUG){
      Serial.print(".");
    }
  }

    if (DEBUG){
      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
    }
}

int value = 0;

void loop() {
  delay(1000);
  ++value;

  if (DEBUG){
    Serial.print("connecting to ");
    Serial.println(host);
  }

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }

  if (DEBUG){
    Serial.print("Requesting URL: ");
  }

//============================================================================================================
//                                Sending Control info to arduino Serially
//============================================================================================================
  // This will send the request to the server
  client.print(String("GET ")  + "/channels/******/feeds.json?api_key=*****************&results=2 HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");         // get information about device control
  unsigned long timeout = millis();
  while (client.available() == 0) {
    if (millis() - timeout > 5000) {
      Serial.println(">>> Client Timeout !");
      client.stop();
      return;
    }
  }

  // Read all the lines of the reply from server and print them to Serial
  while(client.available()){
    String line = client.readStringUntil('\r');
    Serial.print(line);                         // received by arduino serially
  }
 //Serial.println("closing connection");
}

Here is the Arduino code:-
    //This sketch in the implementation of home automation
#include <SoftwareSerial.h>// import the serial library
#include<String.h>
//-----------------------------------------
//    pin definations
//-----------------------------------------
#define Light 2              // pin 2 to control light
#define fan 3                 // pin 3 to control fan
//------------------------------------------
//       variables
//------------------------------------------
char e;
int p=0,q=0;        //these variables prevent switching ON/OFF of already turned ON/OFF devices
int DEBUG = 1;

SoftwareSerial home_monitor(10, 11); // RX, TX

char control_data; // the data transmitted over Bluetooth

void setup() {
  // put your setup code here, to run once:
  home_monitor.begin(115200);
  Serial.begin(9600);
  pinMode(13,OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (home_monitor.available()){
     control_data=home_monitor.read();   // getting control information from ESP8266 serially
     e=control_data;
     if (DEBUG){
      Serial.print(control_data);
     }
     //Serial.print(e);
 //============================================================================================================
 //                                        Device Control
 //============================================================================================================

 // Performing required operations based on the value of channel
    //-------------------------------------------------------------
    //                        LIGHT
    //-------------------------------------------------------------

    if(e=='0'&&p==0)         //Light ON
    {
      if (DEBUG){
        Serial.println("Light ON");
      }
      digitalWrite(Light,LOW);
      p=1;
    }
     if(e=='1'&&p==1)        //Light off
    {
      if (DEBUG){
        Serial.println("Light OFF");
      }
      digitalWrite(Light,HIGH);
      p=0;
    }

    //-------------------------------------------------------------
    //                        Heater
    //-------------------------------------------------------------

    if(e=='2'&&q==0)
    {
      if (DEBUG){
        Serial.println("Fan ON");
      }
      digitalWrite(fan,LOW);
      q=1;
    }
    if(e=='3'&&q==1)
    {
      if (DEBUG){
        Serial.println("Fan OFF");
      }
      digitalWrite(fan,HIGH);
      q=0;
    }
  }
}

You are using client.print() and the Arduino uses home_monitor.read() to receive the message (if I understood correctly). What I did in my sketch was change the home_monitor.read() to home_monitor.readStringUntil('\n').
Also before your ESP sends a message via client.print() it is recommended to run the client.flush() method so it waits until all outgoing characters in the buffer have been sent, before sending the next.
When using the ESP you should be aware of the useful yield() method (call it at the end of the loop). This let's the ESP get his background duties finished before going on (not calling this method may result in some issues.


text:
How to fix the Break Beam Sensor programming issue that says "USB Device Disabled"?
I am trying to use the Adafruit Metro Mini as Arduino (can be used the same way) to program an IR Break Beam sensor and a stepper motor. I connected the beam sensor to the breadboard and plugged the Arduino into my computer. But  my MAC pops up with the notification:

"USB Device Disabled - Unplug the device using too much power to
  re-enable USB Devices."

What is the problem causing the issue? Did I short circuit something? I attached photos to my circuit to the post.

Thanks so much in advance.

"USD device"?? Are you sure that shouldn't be "USB device"? Does the problem still occur if you take the Metro Mini out of the breadboard?

The stepper motor driver is installed with the error (shifted) to the breadboard.
The electrolytic capacitor at the output of the voltage stabilizer in reverse polarity.
Power to  Adafruit Metro Mini is put in inverse polarity ...


text:
How to convert hex to ASCII
I am receiving bytes, converting them into hex and now I need to convert the hex to ASCII. Can it be done on an Arduino? Or do I need something else?
I am new to programming with Arduino.

Is this connected to your earlier question? It is not clear, what you mean. In your previous code you are explicitly sending an ASCII version of hex (human readable hex).

i am receiving bytes and then converting them into hex or displaying them as hex ,and now i want to display them as ascii , is that possible ? sorry for this maybe dumb questions but i want to learn.

Can you show your (relevant) code, the location where you want to convert it, and describe how the output should look like?

If you have a byte variable b, you can

write(b) it as it is. if it is ASCII code of a readable character, the Serial Monitor will display it as that character, for example for 65 it will printt 'A'
print it as decimal number with print(b). for 65 it will print "65"
print it as hexadecimal number with print(b, HEX). for 65 it will print "41"
print it as a number in other base with print(b, base), for example print(b, 2) will print 1000001 if b is 65 in decimal


text:
HTTP request as bytes
I need to send this line of HTTP request as bytes. What is the correct way?
client.write(byte(" <? xml version: '1.0' encoding='utf-8'?><VideoOverlay><normalizedScreenSize><normalizedScreenWidth>704</normalizedScreenWidth><normalizedScreenHeight>576</normalizedScreenHeight></normalizedScreenSize><attribute><transparent>false</transparent><flashing>false</flashing></attribute><fontSize>adaptive</fontSize><frontColorMode>auto</frontColorMode><alignment>customize</alignment><TextOverlayList><TextOverlay><id>1</id><enabled>true</enabled><displayText>dsadasdasdas</displayText><positionX>0</positionX><positionY>480</positionY></TextOverlay></TextOverlayList><DateTimeOverlay><enabled>true</enabled><positionY>544</positionY><positionX>0</positionX><dateStyle>MM-DD-YYYY</dateStyle><timeStyle>24hour</timeStyle><displayWeek>true</displayWeek></DateTimeOverlay><channelNameOverlay><enabled>true</enabled><positionY>64</positionY><positionX>16</positionX></channelNameOverlay></VideoOverlay>"));

To be more clear this is my C# code for the request
byte[] data = encoder.GetBytes(" <? xml version: '1.0' encoding='utf-8'?><VideoOverlay><normalizedScreenSize><normalizedScreenWidth>704</normalizedScreenWidth><normalizedScreenHeight>576</normalizedScreenHeight></normalizedScreenSize><attribute><transparent>false</transparent><flashing>false</flashing></attribute><fontSize>adaptive</fontSize><frontColorMode>auto</frontColorMode><alignment>customize</alignment><TextOverlayList><TextOverlay><id>1</id><enabled>true</enabled><displayText>" + textBox1.Text + "</displayText><positionX>0</positionX><positionY>480</positionY></TextOverlay></TextOverlayList><DateTimeOverlay><enabled>true</enabled><positionY>544</positionY><positionX>0</positionX><dateStyle>MM-DD-YYYY</dateStyle><timeStyle>24hour</timeStyle><displayWeek>true</displayWeek></DateTimeOverlay><channelNameOverlay><enabled>true</enabled><positionY>64</positionY><positionX>16</positionX></channelNameOverlay></VideoOverlay>");

This is my full C# working code
 ServicePointManager.Expect100Continue = false;
        ASCIIEncoding encoder = new ASCIIEncoding();
        byte[] data = encoder.GetBytes(" <? xml version: '1.0' encoding='utf-8'?><VideoOverlay><normalizedScreenSize><normalizedScreenWidth>704</normalizedScreenWidth><normalizedScreenHeight>576</normalizedScreenHeight></normalizedScreenSize><attribute><transparent>false</transparent><flashing>false</flashing></attribute><fontSize>adaptive</fontSize><frontColorMode>auto</frontColorMode><alignment>customize</alignment><TextOverlayList><TextOverlay><id>1</id><enabled>true</enabled><displayText>" + textBox1.Text + "</displayText><positionX>0</positionX><positionY>480</positionY></TextOverlay></TextOverlayList><DateTimeOverlay><enabled>true</enabled><positionY>544</positionY><positionX>0</positionX><dateStyle>MM-DD-YYYY</dateStyle><timeStyle>24hour</timeStyle><displayWeek>true</displayWeek></DateTimeOverlay><channelNameOverlay><enabled>true</enabled><positionY>64</positionY><positionX>16</positionX></channelNameOverlay></VideoOverlay>");
        Uri a = new Uri("http://192.168.0.64");
        HttpWebRequest request = WebRequest.Create("http://192.168.0.64/ISAPI/System/Video/inputs/channels/1/overlays") as HttpWebRequest;
        request.Method = "PUT";
        request.Credentials = new NetworkCredential("admin", "12345qwerty");
        request.ContentLength = 888;
        request.ContentType = "application / x - www - form - urlencoded; charset = UTF - 8";
        request.ContentLength = data.Length;
        request.GetRequestStream().Write(data, 0, data.Length);
        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
        response.Close();

This is the Arduino version
#include <Ethernet.h>
#include <SPI.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 0, 177 };
byte server[] = { 192,168, 0, 64}; // Google
String big_string="<?xml versiding='rlay>";
EthernetClient client;

void setup()
{
  Ethernet.begin(ip);
  Serial.begin(9600);

  delay(1000);

  Serial.println("connecting...");

  if (client.connect(server, 80)) {
    Serial.println("connected");
    client.println("POST /ISAPI/System/Video/inputs/channels/1/overlays HTTP/1.0");
    client.println("Host: 192.168.0.64");
    client.println("User-Agent: arduino-ethernet");
    client.println("Authorization: Basic YWRtaW46MTIzNDVxd2VydHk=");
   client.println("Content-Type: application / x - www - form - urlencoded; charset = UTF - 8");

    client.println("content-length:888");
    // client.println();
    //client.println(big_string.length());
    client.write(" <? xml version: '1.0' encoding='utf-8'?><VideoOverlay><normalizedScreenSize><normalizedScreenWidth>704</normalizedScreenWidth><normalizedScreenHeight>576</normalizedScreenHeight></normalizedScreenSize><attribute><transparent>false</transparent><flashing>false</flashing></attribute><fontSize>adaptive</fontSize><frontColorMode>auto</frontColorMode><alignment>customize</alignment><TextOverlayList><TextOverlay><id>1</id><enabled>true</enabled><displayText>dsadasdasdas</displayText><positionX>0</positionX><positionY>480</positionY></TextOverlay></TextOverlayList><DateTimeOverlay><enabled>true</enabled><positionY>544</positionY><positionX>0</positionX><dateStyle>MM-DD-YYYY</dateStyle><timeStyle>24hour</timeStyle><displayWeek>true</displayWeek></DateTimeOverlay><channelNameOverlay><enabled>true</enabled><positionY>64</positionY><positionX>16</positionX></channelNameOverlay></VideoOverlay>");

     //client.println();
    //client.print(big_string);
    // client.println();

  } else {
    Serial.println("connection failed");
  }
}

void loop()
{
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  if (!client.connected()) {

    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    for(;;)
      ;
  }
}

why do you think that you have to send the request as bytes?

Because i have a c# aplication that works with sending the request as bytes , in order for the ip camera to read them , and now i need to do the same for the arduino

why do you think that a string character, such as an x is not a byte?

this appears to be an example of an X-Y problem ...... you are asking for help with what you consider to be a solution to your problem, but you withhold the details of the original problem

first reduce the C# code. remove lines with request.ContentLength = 888 and request.ContentType. they are wrong so could be ignored. Uri a = new Uri("http://192.168.0.64"); is not used. remove it

post your Arduino version too

I posted my Arduino version

remove the trailing space from " <xml. in C# version you send correct Content-length. In arduino you send 888. the type must by without spaces application/x-www-form-urlencoded

I changed it , still nothing

For one it's <?xml version='1.0' encoding='utf-8'?> and "Content-Type: application/x-www-form-urlencoded; charset=UTF-8"``. Secondly you specify the content-length to be 888, while the string above is 895 characters long. Thirdy the data you send isn't actually application/x-www-form-urlencoded`, but most likely the server doesn't care about this. Lastly, you haven't told us what the actual problem is. What doesn't work? Where does the C# code come into play here?

My problem is that nothing is sent to the camera , i need the arduino to send text to the ip camera display

Characters are bytes. ASCII codes of characters are the values. There is no difference between client.print(str) and client.write(str, strlen(str)). And client.write(str) is the same too.
In C# or Java the constant string is of type String. It is an object. You must call a method of the object to get the raw char/byte array. In Arduino a constant string is of type const char* a.k.a. const char[] which is on low level the same as const byte* or const byte[]
Equivalent of C#
byte[] data = encoder.GetBytes("some string");
for ASCII characters (not UTF) in C is
byte data[] = "some string";

I read that (client.write) send bytes and (client.pritnln) sends string and chars etc , i understand your answer.  but i think it needs to be like my c# code that i edited in my question

in C# the constant string is of type String. it is an object. You must call a function to get the char/byte array. in Arduino a constant string is of type const char* a.k.a. const char[] which is on low level the same as const byte* or const byte[]

And what would be the way to do this ? sorry i am not that good in programming and i am having a little hard time with the bytes array

without byte(. it does wrong

One more question what about the Json library ? can it be used for this problem ?

this is xml, not json

you have a working C# code and can't rewrite it to Arduino?

Yeah i have the full working code on c# but cant rewrite it to Arduino

I posted it in my question