text:
need help in code to send sms to multiple contacts using arduino, gsm800, push button

When button 1 is pressed, the message should be sent to 4 members. But we are receiving the message for one member and after some delay for the other members. But receiving to all members of contacts given in the code (Here numbers are not mentioned)
#include <LiquidCrystal.h>

int ButtonValue1=0;
int ButtonValue2=0;
int ButtonValue3=0;
int ButtonValue4=0;

int Button1=8;
int Button2=9;
int Button3=10;
int Button4=11;
int buz=12;
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);

void okcheck()
{
  unsigned char rcr;
  do{
    rcr = Serial.read();
  }while(rcr != 'K');
}

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

  pinMode(buz,OUTPUT);
  pinMode(Button1,INPUT);
  pinMode(Button2,INPUT);
  pinMode(Button3,INPUT);
  pinMode(Button4,INPUT);

  digitalWrite(12, HIGH);

  lcd.begin(16, 2);
  lcd.clear();
  lcd.print("INNOVATIVE CLG");
  lcd.setCursor(0, 1);
  lcd.print("BUS INFO SYSTEM");

  delay(1000);
}

void loop()
{
  ButtonValue1=digitalRead(Button1);
  ButtonValue2=digitalRead(Button2);
  ButtonValue3=digitalRead(Button3);
  ButtonValue4=digitalRead(Button4);

  if(ButtonValue1!=0)
  {
    lcd.clear();
    lcd.print("BUS STARTED...");
    Serial.write("AT\r\n");         okcheck();
    Serial.write("ATE0\r\n");         okcheck();
    Serial.write("AT+CMGF=1\r\n");         okcheck();
    Serial.write("AT+CNMI=1,2,0,0\r\n");         okcheck();
    Serial.write("AT+CSMP=17,167,0,0\r\n");         okcheck();
    Serial.write("AT+CMGS=\"+91...........\"\r");
    delay(100);
    Serial.write("GUD MNG.. BUS STARTED FROM STARTING POINT\r");
    delay(100);
    Serial.write(0x1A);
    delay(1000);delay(1000);
    Serial.write("AT+CMGS=\"+91...........\"\r");
    delay(100);
    Serial.write("GUD MNG.. BUS STARTED STARTING POINT\r");
    delay(100);
    Serial.write(0x1A);
    delay(1000);delay(1000);
    Serial.write("AT+CMGS=\"+91...........\"\r");
    delay(100);
    Serial.write("GUD MNG.. BUS STARTED STARTING POINT\r");
    delay(100);
    Serial.write(0x1A);
    delay(1000);delay(1000);
    Serial.write("AT+CMGS=\"+91...........\"\r");
    delay(100);
    Serial.write("GUD MNG.. BUS STARTED STARTING POINT\r");
    delay(100);
    Serial.write(0x1A);
    delay(1000);delay(1000);
  }
  if(ButtonValue2!=0)
  {
    lcd.clear();
    lcd.print("BUS IS @ 1st stage");
    Serial.write("AT\r\n");         okcheck();
    Serial.write("ATE0\r\n");         okcheck();
    Serial.write("AT+CMGF=1\r\n");         okcheck();
    Serial.write("AT+CNMI=1,2,0,0\r\n");         okcheck();
    Serial.write("AT+CSMP=17,167,0,0\r\n");         okcheck();
    Serial.write("AT+CMGS=\"+91...........\"\r");
    delay(1000);
    Serial.write("BUS IS @ 1st stage\r");
    delay(1000);
    Serial.write(0x1A);
    delay(1000);delay(1000);
    Serial.write("AT+CMGS=\"+91...........\"\r");
    delay(1000);
    Serial.write("BUS IS @ 1st stage\r");
    delay(1000);
    Serial.write(0x1A);
    delay(1000);delay(1000);
    Serial.write("AT+CMGS=\"+91...........\"\r");
    delay(1000);
    Serial.write("BUS IS @ 1st stage\r");
    delay(1000);
    Serial.write(0x1A);
    delay(1000);delay(1000);
  }
  if(ButtonValue3!=0)
  {
    lcd.clear();
    lcd.print("BUS IS @ 2nd stage");
    Serial.write("AT\r\n");         okcheck();
    Serial.write("ATE0\r\n");         okcheck();
    Serial.write("AT+CMGF=1\r\n");         okcheck();
    Serial.write("AT+CNMI=1,2,0,0\r\n");         okcheck();
    Serial.write("AT+CSMP=17,167,0,0\r\n");         okcheck();
    Serial.write("AT+CMGS=\"+91...........\"\r");
    delay(1000);
    Serial.write("BUS IS @ 2nd stage\r");
    delay(1000);
    Serial.write(0x1A);
    delay(1000);delay(1000);
    Serial.write("AT+CMGS=\"+91...........\"\r");
    delay(1000);
    Serial.write("BUS IS @ 2nd stage\r");
    delay(1000);
    Serial.write(0x1A);
    delay(1000);delay(1000);
  }
  if(ButtonValue4!=0)
  {
    lcd.clear();
    lcd.print("BUS IS @ COLLEGE");
    digitalWrite(buz,LOW);
    delay(1000);
    digitalWrite(buz,HIGH);
  }
}

I suggest you write a sendSMS(const char *number, const char *message) function...

You need to refactor you code, It has become just too complicated for this kind of straight linear code! Your code must be organized better, Don't Repeat Yourself (DRY); just by doing this you may find your error(s).
First lets fix your variables:
#include <LiquidCrystal.h>
#define NUMBUTTS 4
int ButtonValues[NUMBUTTS]= {0,0,0,0};
int Buttons[NUMBUTTS]= {8,9,10,11};
int buz=12;
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);

and add some new ones
String numbers[NUMBUTTS] =
{
    "+91234567890",
    "+91234567890",
    "+91234567890",
    "+91234567890",
}

String msgs[NUMBUTTS-1] =
{
   "GUD MNG.. BUS STARTED FROM STARTING POINT\r",
   "BUS IS @ 1st stage\r",
   "BUS IS @ 2nd stage\r",
}

next lets clean up your function:
void okcheck()
{
    unsigned char rcr = 0;
    while(rcr != 'K') // rcr can't be 'K' when it starts as 0
        rcr = Serial.read();
}

Setup needs to be changed now that we changed your vars:
void setup()
{
    Serial.begin(9600);

    pinMode(buz,OUTPUT);
    digitalWrite(buz, HIGH);

    for(int i=0; i<NUMBUTTS; i++)
        pinMode(Buttons[i],INPUT);

    lcd.begin(16, 2);
    lcd.clear();
    lcd.print("INNOVATIVE CLG");
    lcd.setCursor(0, 1);
    lcd.print("BUS INFO SYSTEM");

    delay(1000);
}

now we need to extract duplicated code and put it in a function:
// common starting code.
void preamble()
{
    Serial.write("AT\r\n");
    okcheck();

    Serial.write("ATE0\r\n");
    okcheck();

    Serial.write("AT+CMGF=1\r\n");
    okcheck();

    Serial.write("AT+CNMI=1,2,0,0\r\n");
    okcheck();

    Serial.write("AT+CSMP=17,167,0,0\r\n");
    okcheck();
}

// common message code
void send_sms(String& msg)
{
    String prefix = "AT+CMGS=\"";
    preamble();

    for(int i=0;i<NUMBUTTS;i++)
    {
        Serial.write(prefix+numbers[i]+"\"\r");
        delay(100);

        Serial.write(msg);
        delay(100);

        Serial.write(0x1A);
        delay(2000)
    }
}

now we need to fix up loop():
void loop()
{
    for(int i=0; i<NUMBUTTS; i++)
    {
        ButtonValues[i]=digitalRead(Buttons[i]);
    }

    for(int i=0; i<NUMBUTTS-1; i++)
    {
        if(ButtonValues[i]!=0)
        {
            lcd.clear();
            lcd.print(msgs[i]);
            send_sms(msgs[i]);
        }
    }

    //special case for button4
    if(ButtonValue[3]!=0)
    {
         lcd.clear();
         lcd.print("BUS IS @ COLLEGE");
         digitalWrite(buz,LOW);
         delay(1000);
         digitalWrite(buz,HIGH);
    }
}

Now your program logic is separate from the code that sends the messages, and you can test each in isolation from each other. You can test that send_sms() actually sends SMSs. Then you can see if your logic does what you think it does; by either replacing send_sms() with a test stub, or just by inspection.
With clean code it should be easier to spot your problem. The code looks like it should work, so I would guess that the modem itself may be causing the delays, maybe it takes a while to send a message and you are queuing them up and it takes a few seconds to get through each one, its possible that not all get send because one or more gets dropped while it is busy sending another. Hard to know without looking at the documentation for your module.
Your diagram looks like it is hooked up wrong, you have TX-> RX, but MOSI -> TX; Serial.read() reads from RX not MOSI, so i don't know how checkok() doesn't just loop forever, since you left the arduino RX floating.

The code has occurred error while compiling. There is no declaration of ButtonValue(3) in the code, but it is used in the special case for button 4.

@PavanKumar ButtonValue_s_ is an array and ButtonValues[3] is definitely in the code; there is no guarantee that i didn't make a typo or error you might have to fix.


text:
How do I use 4 inputs on the Arduino as a binary decoder?
How do I use 4 input lines as a binary decoder? I would like to read the 4 inputs (16 variations) and based on that choose one of 16 output behaviors?
I need to be able to set my “Ten Moon Phase Indicator” (MPI ECP) circuit project to the phase of the Moon as seen in the sky on this day, or to a specific time as indicated in one of the many apps available on the Internet. Currently the MPI ECP resets to the start of the Full Moon loop, as it is the only loop available. (this code works) NOTE: Due to the circuit & Arduino processor power consumption for this application, a eternal power will be necessary.
To resolve this problem my intent is to use four of the available 14 I\O on the Arduino Uno as INPUT's employing four debounced toggle switches (with pull up resistors): (0) Off, (1) as On. The other ten available I/O's to be used for the ten Moon display OUTPUT LED's or to control ten relays.
What I would like the sketch program to accomplish:

digitalRead pins 0, 1, 12, 13
Depending on 1 of 16 resulting four on/off combinations that are possible, run a specific loop.

This is what I came up with: (note, the code does not compile, I'm new)
 void setup()  {
 pinMode(2, OUTPUT);   // New     Waxing:
 pinMode(3, OUTPUT);   // Young  Waxing:
 pinMode(4,OUTPUT);   // Crescent Waxing:
 pinMode(5, OUTPUT);   // Quarter Waxing:
 pinMode(6, OUTPUT);   // Gibbous Waxing:
 pinMode(7,OUTPUT);   // Full Moon:
 pinMode(8, OUTPUT);   // Gibbous Wanning:
 pinMode(9, OUTPUT);   // Quarter Wanning:
 pinMode(10, OUTPUT);  // Crescent Wanning:
 pinMode(11, OUTPUT);  // Old Wanning:
 pinMode(13, INPUT);  // Switch 4
 pinMode(12,INPUT);     // Switch 3
 pinMode(1, INPUT);     // Switch 2
 pinMode(0,INPUT);      // Switch 1

 } void loop() {
 int Reading = digitalRead;
Reading = digitalRead (12); Reading = digitalRead (13);
Reading = digitalRead (1);   Reading = digitalRead (0);

 if  (digitalRead(0) == HIGH; digitalRead (1)==
   HIGH; digitalRead(12) == HIGH; (digitalRead(13) == HIGH);  { } else
    {   // loop Full Moon Start   digitalWrite(7, HIGH);  // FULL MOON ON
  delay(5000);
  digitalWrite(7, LOW);    // FULL MOON OFF
        delay(10);
   digitalWrite(8,HIGH);   // WAN GIBBOUS MOON ON
        delay(5000);
 digitalWrite(8, LOW);    // WAN GIBBOUS MOON OFF
          delay(10);
  digitalWrite(9, HIGH);   // 3RD QUARTER MOON ON
          delay(5000);
   digitalWrite(9, LOW);     // 3RD QUARTER MOON OFF
          delay(10);
  digitalWrite(10, HIGH);    // WAN CRESENT MOON ON
         delay(5000);
  digitalWrite(10, LOW);     // WAN CRESENT MOON OFF
          delay(10);
  digitalWrite(11, HIGH);     // OLD MOON ON
         delay(5000);
 digitalWrite(11, LOW);      // OLD MOON OFF
          delay(5000);
   digitalWrite(2, HIGH);  // NEW MOON ON
          delay(5000);
  digitalWrite(2, LOW);   // NEW MOON OFF
          delay(10);
 digitalWrite(3, HIGH);  // YOUNG MOON ON
          delay(5000);
   digitalWrite(3, LOW);  // YOUNG MOON OFF
          delay(100);
 digitalWrite(4, HIGH);   // WAX CRESCENT MOON ON
         delay(5000);
   digitalWrite(4, LOW);    // WAX CRESCENT MOON OFF
          delay(10);
  digitalWrite(5, HIGH);   // FIRST QUARTER ON
          delay(5000);
   digitalWrite(5, LOW);     // FIRST CRESCENT OFF
          delay(10);
 digitalWrite(6, HIGH);   // WAX GIBBOUS ON
         delay(5000);
  digitalWrite(6, LOW);    // WAX GIBBOUS OFF
          delay(10);

// loop for New moon Reset   if  (digitalRead(0) == LOW;digitalRead (1)==LOW; digitalRead(12) == LOW;(digitalRead(13) ==
    LOW);
  { } else   // loop New Moon Start
 digitalWrite(2, HIGH);  // NEW MOON ON
          delay(5000);
   digitalWrite(2, LOW);   // NEW MOON OFF
          delay(10);
   digitalWrite(3, HIGH);  // YOUNG MOON ON
          delay(5000);
   digitalWrite(3, LOW);    // YOUNG MOON OFF
          delay(100);
   digitalWrite(4, HIGH);   // WAX CRESCENT MOON ON
         delay(5000);
   digitalWrite(4, LOW);    // WAX CRESCENT MOON OFF
          delay(10);
   digitalWrite(5, HIGH);   // FIRST QUARTER ON
          delay(5000);
  digitalWrite(5, LOW);     // FIRST CRESCENT OFF
          delay(10);
  digitalWrite(6, HIGH);   // WAX GIBBOUS ON
         delay(5000);
   digitalWrite(6, LOW);    // WAX GIBBOUS OFF
          delay(10);
  digitalWrite(7, HIGH);  // FULL MOON ON
        delay(5000);
   digitalWrite(7, LOW);    // FULL MOON OFF
        delay(10);
   digitalWrite(8,HIGH);   // WAN GIBBOUS MOON ON
        delay(5000);
   digitalWrite(8, LOW);    // WAN GIBBOUS MOON OFF
          delay(10);
   digitalWrite(9, HIGH);   // 3RD QUARTER MOON ON
          delay(5000);
   digitalWrite(9, LOW);     // 3RD QUARTER MOON OFF
          delay(10);
  digitalWrite(10, HIGH);    // WAN CRESENT MOON ON
         delay(5000);
   digitalWrite(10, LOW);     // WAN CRESENT MOON OFF
          delay(10);
  digitalWrite(11, HIGH);     // OLD MOON ON
         delay(5000);
   digitalWrite(11, LOW);      // OLD MOON OFF
          delay(5000);
 { } else  { // Young moon Reset Start
 if  (digitalRead(0) == LOW; digitalRead (1)==LOW; digitalRead(12) ==
    LOW;(digitalRead(13) == HIGH;
 )
   { } else  // loop New Moon Start
         digitalWrite(3, HIGH);
  // YOUNG MOON ON
          delay(5000);
   digitalWrite(3, LOW);    // YOUNG MOON OFF
          delay(100);
  digitalWrite(4, HIGH);   // WAX CRESCENT MOON ON
         delay(5000);
  digitalWrite(4, LOW);    // WAX CRESCENT MOON OFF
          delay(10);
   digitalWrite(5, HIGH);   // FIRST QUARTER ON
          delay(5000);
  digitalWrite(5, LOW);     // FIRST CRESCENT OFF
          delay(10);
  digitalWrite(6, HIGH);   // WAX GIBBOUS ON
         delay(5000);
  digitalWrite(6, LOW);    // WAX GIBBOUS OFF
          delay(10);
 digitalWrite(7, HIGH);    // FULL MOON ON
        delay(5000);
   digitalWrite(7, LOW);    // FULL MOON OFF
        delay(10);
   digitalWrite(8,HIGH);   // WAN GIBBOUS MOON ON
        delay(5000);
  digitalWrite(8, LOW);    // WAN GIBBOUS MOON OFF
          delay(10);
  digitalWrite(9, HIGH);   // 3RD QUARTER MOON ON
          delay(5000);
 digitalWrite(9, LOW);     // 3RD QUARTER MOON OFF
          delay(10);
  digitalWrite(10, HIGH);    // WAN CRESENT MOON ON
         delay(5000);
   digitalWrite(10, LOW);     // WAN CRESENT MOON OFF
          delay(10);
  digitalWrite(11, HIGH);     // OLD MOON ON
         delay(5000);
  digitalWrite(11, LOW);      // OLD MOON OFF
          delay(5000);
         digitalWrite(2, HIGH);   // NEW MOON ON
          delay(5000);
   digitalWrite(2, LOW);       // NEW MOON OFF
          delay(10);
  }
 // Waxing Crescent Reset Start if  (digitalRead(0) == LOW; digitalRead (1)== LOW; digitalRead(12) ==
    HIGH; digitalRead(13) == HIGH;)    { } else  // Waxing Crescent Moon
    reset Start
  digitalWrite(4, HIGH);   // WAX CRESCENT MOON ON
         delay(5000);
   digitalWrite(4, LOW);    // WAX CRESCENT MOON OFF
          delay(10);
 digitalWrite(5, HIGH);   // FIRST QUARTER ON
          delay(5000);
   digitalWrite(5, LOW);     // FIRST CRESCENT OFF
          delay(10);
   digitalWrite(6, HIGH);   // WAX GIBBOUS ON
         delay(5000);
  digitalWrite(6, LOW);    // WAX GIBBOUS OFF
          delay(10);
  digitalWrite(7, HIGH);    // FULL MOON ON
        delay(5000);
   digitalWrite(7, LOW);    // FULL MOON OFF
        delay(10);
  digitalWrite(8,HIGH);   // WAN GIBBOUS MOON ON
        delay(5000);
   digitalWrite(8, LOW);    // WAN GIBBOUS MOON OFF
          delay(10);
  digitalWrite(9, HIGH);   // 3RD QUARTER MOON ON
          delay(5000);
   digitalWrite(9, LOW);     // 3RD QUARTER MOON OFF
          delay(10);
 digitalWrite(10, HIGH);    // WAN CRESENT MOON ON
         delay(5000);
   digitalWrite(10, LOW);     // WAN CRESENT MOON OFF
          delay(10);
  digitalWrite(11, HIGH);     // OLD MOON ON
         delay(5000);   digitalWrite(11, LOW);      // OLD MOON OFF
         delay(5000);
   digitalWrite(2, HIGH);   // NEW MOON ON
          delay(5000);
   digitalWrite(2, LOW);      // NEW MOON OFF
          delay(10);
   digitalWrite(3, HIGH);  // YOUNG MOON ON
          delay(5000);
   digitalWrite(3, LOW);       // YOUNG MOON OFF
          delay(100);
  }
  // First Quarter Moon Reset if  (digitalRead(0) == LOW; digitalRead(1) == HIGH; digitalRead(12) ==
    HIGH; digitalRead(13) == HIGH;)   { else  {
  //FIRST QUARTER  Moon
    reset Start
digitalWrite(5, HIGH);   // FIRST QUARTER ON
          delay(5000);
   digitalWrite(5, LOW);     // FIRST CRESCENT OFF
          delay(10);
   digitalWrite(6, HIGH);   // WAX GIBBOUS ON
         delay(5000);
  digitalWrite(6, LOW);    // WAX GIBBOUS OFF
          delay(10);
  digitalWrite(7, HIGH);  // FULL MOON ON
        delay(5000);
   digitalWrite(7, LOW);    // FULL MOON OFF
        delay(10);
   digitalWrite(8,HIGH);   // WAN GIBBOUS MOON ON
        delay(5000);
  digitalWrite(8, LOW);    // WAN GIBBOUS MOON OFF
          delay(10);
  digitalWrite(9, HIGH);   // 3RD QUARTER MOON ON
          delay(5000);
   digitalWrite(9, LOW);     // 3RD QUARTER MOON OFF
          delay(10);
  digitalWrite(10, HIGH);    // WAN CRESENT MOON ON
         delay(5000);
   digitalWrite(10, LOW);     // WAN CRESENT MOON OFF
          delay(10);
  digitalWrite(11, HIGH);     // OLD MOON ON
         delay(5000);
  digitalWrite(11, LOW);      // OLD MOON OFF
          delay(5000);
  digitalWrite(2, HIGH);   // NEW MOON ON
          delay(5000);
  digitalWrite(2, LOW);    // NEW MOON OFF
          delay(10);
   digitalWrite(3, HIGH);  // YOUNG MOON ON
          delay(5000);
   digitalWrite(3, LOW);    // YOUNG MOON OFF
          delay(100);
   digitalWrite(4, HIGH);   // WAX CRESCENT MOON ON
         delay(5000);
  digitalWrite(4, LOW);        // WAX CRESCENT MOON OFF
          delay(10);
 }
// code would continue with other loops. Thanks for looking at  my 16 RESET problem, email me. Any suggestions would be appreciated

edit your code to be readable!

If the code doesn't compile, the compiler shows some error messages. Include them in your question.

If the code does compile, does it do what you want it to? If not, what does it do?

you have a lot of unnecessarily repeating code ..... put these three lines in a function digitalWrite(X, HIGH); delay(5000); digitalWrite(X, LOW);  .... then just call the function with a pin number as an argument

Edit your question, with a simple title (not a long winded explanation and commentary), put your question in the main body of text, and explain what exactly is wrong with your code. Take a look at other highly voted questions on the site to see how to write a good clear question. And indent your code correctly

a skeleton solution:
int in[] = {0,1,12,13};
int out[] = {2,3,4,5,6,7,8,9,10,11};
...
void setup()
{
    for(int i=0; i < 4; i++)
        pinMode(in[i], INPUT)

    for(int i=0; i < 10; i++)
        pinMode(out[i], OUTPUT)
}
...
void do0 {...};
void do1 {...};
void do2 {...};
void do3 {...};
void do4 {...};
void do5 {...};
void do6 {...};
void do7 {...};
void do8 {...};
void do9 {...};
void do10 {...};
void do11 {...};
void do12 {...};
void do13 {...};
void do14 {...};
void do15 {...};
...
void loop()
{
    int addr = 0;
    for(int i=0; i<4; i++)
       addr |= digitalRead(in[i]) << i;

    switch(addr)
    {
    case 0:
       do0();
       break;
    case 1:
       do1();
       break;
    case 2:
       do2();
       break;
    case 3:
       do3();
       break;
    case 4:
       do4();
       break;
    case 5:
       do5();
       break;
    case 6:
       do6();
       break;
    case 7:
       do7();
       break;
    case 8:
       do8();
       break;
    case 9:
       do9();
       break;
    case 10:
       do10();
       break;
    case 11:
       do11();
       break;
    case 12:
       do12();
       break;
    case 13:
       do13();
       break;
    case 14:
       do14();
       break;
    case 15:
       do15();
       break;
    }
}

This may be a little too advanced for the OP but... reading esoterik’s
answer, I couldn't help the urge to transform that big switch/case into
an array lookup. Admittedly, the syntax for declaring the array of
function pointers is a little bit esoteric. ;-)
void loop()
{
    // List of implemented behaviors.
    static void (* const behaviors[])() = {
        do0, do1, do2,  do3,  do4,  do5,  do6,  do7,
        do8, do9, do10, do11, do12, do13, do14, do15
    };

    // Build the index of the requested behavior.
    int addr = 0;
    for (int i = 0; i < 4; i++)
       addr |= digitalRead(in[i]) << i;

    // Now do it.
    behaviors[addr]();
}

Edit: To address the OP's issue. I may have missed something, but it
looks to me like all the cases do the exact same thing: loop through the
outputs, turn each one on, wait 5 seconds, then turn it off. The only
difference between the cases is the index of the output that is turned
on first. In this case, all this repetitive code can be factored into a
single loop as follows:
// Turn on then off all the outputs in turn,
// starting from the given index.
void loop_outputs(int start_index)
{
    int index = start_index;
    for (int count = 0; count < 10; count++) {

        // Light up that LED for 5 s.
        digitalWrite(out[index], HIGH);
        delay(5000);
        digitalWrite(out[index], LOW);
        delay(10);

        // Go to the next one, wrapping index 10 -> 0.
        if (++index == 10) index = 0;
    }
}

I thought about function pointers, but figured they were to complicated for this.

Note that A0 to A5 are available as for digitalRead() also. I normally initialize them as
byte pin14 = 14; // make the name mean something to you

pinMode (pin14, INPUT_PULLUP);

Then you can read it as

if (digitalRead(pin14) == LOW){

// pin is connected to Gnd

}

Or if you use D14-17 for your 4 inputs, you can read all 4 with a PORT read, and act on that (you still use pinMode() to initialize them):
byte addressByte = PORTC & 0x0F; // result is 0 to 15 based on state of the 4 pins

(I think PORTC is A0 to A5, might want to check that)
then read them and act accordingly. Way cleaner than a while bunch of digitalRead()s and if() statements.
switch(addressByte){

case 0:

// whatever happens

:

:

case 15:

// whatever happens
}

“I think PORTC is A0 to A5”. The OP is using an Uno, and this is indeed correct on that board.

source: Stack Exchange

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

sort: votes


text:
Reading bytes from a file on SD Card - Understanding Buffer
I have the following piece of code which opens a Bitmap from the SD card and outputs the width to the serial monitor.
#include <SPI.h>
#include <SD.h>

File bitmap;

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

  Serial.println("Initializing SD card...");
  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  bitmap = SD.open("/TEST2.BMP");

  int width[0]; // why can't I just write "int width;"
  bitmap.seek(18);
  bitmap.read(width, 4);
  Serial.println(width[0]); // and "Serial.println(width);"
}

void loop() {

}

It works perfectly fine but I don't understand why I have to declare the buffer for the width as int width[0];. I tried int width; but then the output is just 0.

You don't have to, it's just one way of doing it.
Basically the read function needs a pointer to a buffer to store the data in.  By using an array with one entry you get a pointer to a buffer that is big enough for one (32-bit) integer. And you then get an "easy" way of accessing that one integer within that buffer.
Another way would be to just use a simple integer and pass a pointer to that integer to read:
uint32_t width; // Use a fixed size integer for portability
bitmap.seek(18);
bitmap.read(&width, sizeof(width)); // Use sizeof for portability
Serial.println(width);

I think I have a bit of insight:
An array is a pointer. Thus,
int arr[0];
is equivalent of
int * simple;
So. read(arr...  or read(&simple...

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


text:
ADXL345 Data Rate seems to depend more upon Baud rate than the actual Data Rate that I set
I have an Arduino UNO that is connected to an ADXL345. The problem is I need to collect data at 50Hz at least. The ADXL345 according to its Data sheet can go up to 3200Hz without any problem. I am using the Adafruit library using I2C interface but the accelerometer does not go above 10-12Hz as reported by the getDataRate() function of Adafruit library.
Im trying to set the data rate like this:
accel.setDataRate(ADXL345_DATARATE_100_HZ);

The strange thing is that the data rate is depended more upon increasing the baud rate at the beginning of my setup function. If I set this to 38400 I get around 90-92 readings every second. I have setup my code in a way that every measurement from the accelerometer is recorded with the timestamp down to seconds. This is a snapshot of the output from the serial monitor.
Data Rate:    9 Hz
------------------------------------
Sensor:       ADXL345
Driver Ver:   1
Unique ID:    12345
Max Value:    -156.91 m/s^2
Min Value:    156.91 m/s^2
Resolution:   0.04 m/s^2
------------------------------------

Range:         +/- 8  g

84.00,18:40:4,15/7/2018,0.59,9.14,2.82
85.00,18:40:4,15/7/2018,0.59,9.14,2.86
86.00,18:40:4,15/7/2018,0.63,9.10,2.86
87.00,18:40:4,15/7/2018,0.55,9.10,2.82
88.00,18:40:4,15/7/2018,0.55,9.10,2.82
89.00,18:40:4,15/7/2018,0.59,9.10,2.82
90.00,18:40:4,15/7/2018,0.59,9.10,2.82
91.00,18:40:4,15/7/2018,0.55,9.10,2.86
92.00,18:40:4,15/7/2018,0.55,9.10,2.86
93.00,18:40:4,15/7/2018,0.63,9.10,2.90
94.00,18:40:4,15/7/2018,0.63,9.10,2.90
95.00,18:40:4,15/7/2018,0.63,9.06,2.82
96.00,18:40:4,15/7/2018,0.63,9.06,2.82
97.00,18:40:4,15/7/2018,0.59,9.06,2.82
98.00,18:40:4,15/7/2018,0.59,9.06,2.82
99.00,18:40:4,15/7/2018,0.59,9.10,2.82

Is it a problem with the code, or the adxl345?

You do know that sending data through serial takes time, don't you?
You are sending 41 bytes per reading. The serial port has a 64 byte buffer. By the second reading the buffer is full and all printing blocks until there is room in the buffer.
At 38400 baud that's sending 3840 bytes per second. With 41 bytes per reading that's 93.66 readings per second (not including the time taken to do the actual reading) that you can squeeze down the serial port.
Either run at a faster speed, or reduce the quantity of data you're sending per reading - or do both.

Sure I increased the baud rate now to 115200 without changing the data rate of ADXL345, now I get around 280-290 readings on my Serial Monitor per second which means that this bottleneck has been removed?, but getDataRate still shows 9Hz when it is actually set to 100Hz.

Also why am I getting 280-290 readings when they should be somewhere around 100 readings per second?

How often you read has no bearing on how often the ADXL samples. You just get multiple readings the same.

The value returned by getDataRate isn't a Hz value - it's a number that equates to one of the ADXL_DATARATE_x_HZ enumerations. https://github.com/adafruit/Adafruit_ADXL345/blob/master/Adafruit_ADXL345_U.h#L77

Oh I got it, thanks :) Just one last query though, I need to collect data at 50Hz for an activity tracking machine learning algorithm, which from my understanding meant for every second 50 values in the x,y,z axes have to be collected. If I adjust baud rate so that I get 'around' 50 values every second in the serial monitor, does that mean the values line up with the actual Data Rate of the accelerometer?

You should use the interrupt output (or the data ready signal in the ADXL's registers) to get each data point when it has actually been produced.

Alright, thanks for putting me down the right path, will look into this.


text:
Best practice to declare a 'static' text and save memory
I'm working on a project where I need to create a JSON to send back state of an object. I created the code to achieve it and all works fine, but I used this to declare the JSON fields:
static const String JSON_FIELD_A;

then in the .cpp file
const String MyClass::JSON_FIELD_A = "field_a";

In this way I can use that in several point inside my class (eg. to create and parse JSON) without needs to write the field name each time which may cause inconsistency after a refactoring.
I'm not sure about this way anyway... is there a more efficient way to achieve that? Using #define may be a solution?

This looks reasonable

You should look at the F() macro, and the __FlashStringHelper stub class. As well as the _P variants of the standard string library functions.

The "traditional" way is to use PROGMEM and use const char * strings.
I don't use the "traditional" way. Instead I use some "helper" classes and macros that WString.h provides.
This does mean, though, due to limitations in C++, that you have to create your string constants in two stages.
First is to define your variables:
const __FlashStringHelper *stringOne;
const __FlashStringHelper *stringTwo;

Then you need to assign the actual strings to those variables within a function. This could be in setup(), but I prefer to define an initializeStrings() function that setup() calls:
void initializeStrings() {
    stringOne = F("This is the first string")
    stringTwo = F("This is the second string");
}

void setup() {
    initializeStrings();
}

You can then pass these objects (they're not really objects, it's all just some magic casting done by the compiler) as parameters to other functions using const __FlashStringHelper * as the type.  They can also be passed directly to any of the .print() and .println() functions provided by the Print class (which all Stream objects ultimately inherit).
If you want to use the standard C string library functions _P variants for manipulating the strings (concatenating them to other strings, for instance), you can simply cast them to PGM_P:
char temp[50];
strcpy_P(temp, (PGM_P)stringOne);
strcat_P(temp, (PGM_P)stringTwo);

Another alternative to all that is to use precompiler macros.
#define STRING_ONE F("This is the first string");
#define STRING_TWO F("This is the second string");

Again, you can cast those to PGM_P to use the _P variants of the standard C string library functions, and pass them directly to print functions, since they are replaced verbatim as F("This is the first string"), and F() does a reinterpret-cast to const __FlashStringHelper *.

it is all `const char* and we must track which one is in flash and which in RAM and use the right functions. __FlashStringHelper is a trick to match the flash variants. but a trick not recognized by _P functions. so we need to cast it back to const char*. but I doubt a beginner can understand this

@Juraj Ah... the complexities of Harvard architecture. It's such a joy. One of the many reasons I never use AVR chips :)

const String does make nothing constant. You create an object, which can't be reassigned, but all methods work. Because it handles the characters inside and the const declaration doesn't change it. You can delete the content, change the content, append the content of the String object.
You should use const char* or const char[]. It is an c-string and the compiler checks if it is handled as a constant at gives at least a warning if not.
To save RAM the const char[] should be declared as PROGMEM. At runtime then this string isn't copied into RAM. You can use it with functions with _P postfix or copy it temporally to RAM.
Example from my project:
global char array with PROGMEM
const char data[] PROGMEM = "{\"suspension_time_seconds\":10800}";
use in a function
client.print(F("Content-Length: "));
client.println(strlen_P(data));
char buff[64];
strcpy_P(buff, data);
client.print(buff);

You don't need to copy a PROGMEM string into RAM just to "print" it. Just cast it to const __FlashStringHelper *: client.print((const __FlashStringHelper *)data);

I know. Wrong example with print. It should be some function that has not a variant for progmem.


text:
Creating a Web Interface for ESP32
I am working on a project that involves moving various servos and lights and I need a good UI to work with the device. I've previously used Blynk, which worked very well but I didn't like some of the limits it has. My current code works with Blynk and I'd like to change it to a web server so it can work on any device without an app or internet connection.
Right now my esp configures itself as an access point and I can navigate to its IP address to get to my "hello world file" but after that I'm stuck. What really stumps me is getting the input from the interface that I make in HTML, I could fairly easily make an arrangement of buttons, sliders, and fields, that fits my need but how do I get the value of these as a variable in my arduino code?
I've seen some examples of code that are very simple essentially a couple buttons redirect to different web pages on the server and it takes these commands to assign a variable, but that seems kind of poor form, is there a better way, or how do I make that work with a complex interface with many buttons and switches.
I've heard of Jquery and Ajax but not familiar on how to make this work with Arduino code.

have you tried googling "ESP32 web server library"? What you need to do is implement a web server that gives you access to those controls.

I would highly recommend splitting it into two parts: back end (C++) and front end (JS). You'll probably want to connect to a router, so your clients, like a phone and laptop need not be on that AP hotspot w/o internet.
You first build an API with arduino using GET params to control, example pin values int level = server.arg("level").toInt(); analogWrite(2, level);, or whatever you need to do. Put that in a function called handlePin, and subscribe it in setup(): server.on("/pin", handlePin);. Then just add CORS to the server response: server.sendHeader("Access-Control-Allow-Origin","*"); and you can now hit it from any computer on the network. To test, just enter it's URL and some params into a browser URL bar; http://192.168.2.123/pin?level=512 to dim halfway.
Once you have the URLs working, the interface part is built completely separately using whatever tools you want. All you need to do is have your UI hit the API using simple ajax calls. As a quick and dirty example: Level:<input type=range id=val max=1024> <br> <button onclick="fetch('http://192.168.2.123/pin?level='+val.value)">update</button>
That's hows the pros do it, you just swap C++ for PHP or C# or whatever, and use any UI framework you want. Once you have the source of your client app ready, you can upload it to the SPIFFS of the ESP, but I find it easier to host and update system-wide on a "real" server.
If you don't want to write the UI code yourself, you can use node-red to make a quick and dirty "control panel", just like HTML but with drag and drop functionality (more or less). You still use the same API on the ESP, and you can use more than one system at a time; all the ESPs care about is hitting the right URL.

I could fairly easily make an arrangement of buttons, sliders, and fields, that fits my need but how do I get the value of these as a variable in my arduino code?

The same way a web server does! What you need to do is implement a web server on the ESP32. You will serve a page with the controls, and then that page must make a request back to the server which will then processes it and do whatever you program it to do.
There are two ways to do this:

Use a get/post form; send all the data at once
Something like ajax; each control sends data asynchronously


text:
YL-38 output to NodeMCU v1.0 analog input
Using a YL-38 and NodeMCU v1.0 I am trying to achieve what the first link is doing, take a soil moisture reading. I've done this on an arduino, but the conversion from an arduino nano to a nodemcu is proving difficult.
To my understanding, the nodemcu A0 pin operates from 0v-3.3v but the YL-38 analog output operates from 0-4.1v. So first off, is my understanding correct?
I struggle with hardware, so looking around I found these resources:
How to set up a simple level shifter: this setup seemed pretty much like what i wanted, but the 5v input was off
This thread was verbatim what I wanted but I am terrible with circuit math, so I couldn't solve or understand the provided formulas.
Attempt 0: Initially had sensor analog out connected to a0 on nodemcu. Saturated or dry the mcu read 1023. Thought this must be because the signal out is above the A0 mapping range.
Attempt 1: I figured I'd try out the level shifter. Wired it all up as indicated. Now my readings were 760 saturated and 765 dry.
runHygrometer(index);
delay(2000); //allow hygrometer to wake up
reading = (DEBUG) ? analogRead(HYGROMETER_READ_PIN) : 1023 - analogRead(HYGROMETER_READ_PIN);

As shown, my code does no scaling, It's a direct read (DEBUG is true here). So what gives? When using an arduino the range of readings was typically from 20 dry to 180 saturated (DEBUG false, so raw 1003 dry and 843 saturated)

To my understanding, the NodeMCU A0 pin operates from 0v-3.3v

Incorrect. The ESP8266's ADC can only measure between 0V and 1V.
You need to reduce your output voltage down to that range. How you do that very much depends on the output impedance of the YL-38.
The LM393 that the YL-38 is based around looks to have a maximum output current of 16mA. That should be enough to happily drive a simple voltage divider.  A 4.7kΩ and 1kΩ divider would give you 0 to 0.877v out from a 0-5V input.

simulate this circuit – Schematic created using CircuitLab
An alternative would be to attach an external ADC running at 5V to the NodeMCU. This would give you multiple channels of analogue input with a 0-5V range. I use the MCP3208 running over SPI (I actually bit-bang it on the ESP8266 rather than using SPI, since I haven't yet got SPI to work properly with it).  Ideally, you want a proper logic level translator for the SCK and MOSI signals to boost them to 5V. It all gets a little complex, though.

It has come to light that the NodeMCU includes a voltage divider already. For some reason they chose to use massive resistors, which give far too high an impedance for any reasonable ADC input to accurately work with.  I would suggest, if you can, removing those resistors from the board and replacing them with 4.7k and 1k resistors to form your own voltage divider. Otherwise you're going to have to use a pair of op-amps in inverting mode, one with a fractional gain, and one with unity gain (the second is to "undo" the inverting of the first one) to reduce the signal to 0-3.3V.
TBH I'd be inclined to use an external ADC anyway for this.

I thought I read that A0 has a voltage divider and feeds that signal into the ESP8266 ADC? I'm referring to the 3rd to last page on NodeMCU doc listed above.
https://randomnerdtutorials.com/esp8266-adc-reading-analog-values-with-nodemcu/
"Currently, TOUT (Pin6) has a 10-bit precision and its input voltage range is 0 to 3.3V when TOUT is connected to an external circuit."

Ugh. So it does. That's nasty. You want to remove those resistors and replace them with 4.7K and 1K. The resistors used are at least 10x too big for any normal ADC input. Far too high an impedance. You can't use another voltage divider along side it, it just won't work. Either that or you'd have to use an op-amp with a sub-unity gain (actually you'd need a pair of inverting op-amps, one with a fractional gain and one with unity gain) to buffer your signal with a low impedance output. Or use an external ADC...

So i should look into using an external ADC to convert 5v to 3.3v signals? Would that be the simplest solution?

It's the route I'd probably take, yes. In fact, right in front of me I have a D1 Mini Pro with an MCP3208 attached to it to do some current and voltage measurements...

I'm really short on IO pins, so im not sure if the MCP3002 will work for me. But can i skip ADC EX and its voltage divider and use your 4.7k/1k external ADC straight to the ESP8266's tout pin (which i think is labled just ADC in the doc)?

@DougClark Sure thing. You may want to remove the existing divider though as the lower resistor will skew your readings slightly.

Let us continue this discussion in chat.


text:
I can't manage to upload multiple sketches
I'm doing a gardening project. It involves multiple sensors and even having the sketches for them, I don't know how to make them run together and get a reading on them at the same time. I'm really new with this. It's my first Arduino ever.
I seem to manage getting a read on one of the sensors, but whenever I try to upload a new sketch, it fails to load.
Here are a couple of the codes I want to run together. One is a temperature/humidity sensor and the other one a soil humidity sensor.
Thanks in advance!!!
#include "DHT.h"          // DHT & AM2302 library

// Data pin connected to AM2302
#define DHTPIN 2

#define DHTTYPE DHT22       // DHT 22  (AM2302)

DHT dht(DHTPIN, DHTTYPE);   // LED pins

//////////////////////////////////////////////////////
//
// SETUP
//
void setup() {
  // Setup serial monitor
  Serial.begin(9600);
  dht.begin();
}

void loop() {

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow     sensor)
  float h = dht.readHumidity();
  float t = dht.readTemperature();

  // check if returns are valid, if they are NaN (not a number) then     something went wrong!
  if (isnan(t) || isnan(h)) {
    Serial.println(F("Failed to read from DHT"));
  }
  else {
Serial.print(F("Humedad: "));
Serial.print(h);
Serial.print(F(" %\t"));
Serial.print(F("Temperatura: "));
Serial.print(t);
Serial.println(F(" C"));
  }

  // Wait 3 seconds
  delay(3000);
}

The other code:
   //////////////////////////////////////////////
  //        ARDUINO SOIL MOISTURE DEMO        //
 //                                          //
//           http://www.educ8s.tv           //
/////////////////////////////////////////////

int sensorPin = A0;
int sensorValue = 0;
int percent = 0;

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

void loop() {

  sensorValue = analogRead(sensorPin);
  percent = convertToPercent(sensorValue);
  printValuesToSerial();
  delay(1000);
}

int convertToPercent(int value)
{
  int percentValue = 0;
  percentValue = map(value, 1023, 465, 0, 100);
  return percentValue;
}

void printValuesToSerial()
{
  Serial.print("\n\nAnalog Value: ");
  Serial.print(sensorValue);
  Serial.print("\nPercent: ");
  Serial.print(percent);
  Serial.print("%");
}

Only one sketch at a time. You will have to merge them (somehow)

@Greenonline, OP did it some hours ago. read the answer and comments

@Juraj -  good point, but then, in that case, the original question has been changed substantially

I can't manage to upload multiple sketches

The arduino can only run one sketch at a time. You can do multiple things in a single sketch, but you can only have one sketch.

... but whenever I try to upload a new sketch, it fails to load.

What exactly fails? You should be able to change sketches, the new sketch should replace the old sketch; If this isn't working you have another problem all together.

Here are a couple of the codes I want to run together ...

You will have to write a new sketch that combines the behavior of the two sketches.
something like:
...
setup()
{
    // common setup code goes here
}
...
loop()
{
    int sensor_reading_1 = analogRead(sensor_pin);
    float sensor_reading_2_h = dht.readHumidity();
    float sensor_reading_2_t = dht.readTemperature();

    ... // do stuff with the readings
}

The error is because I used 2 Voids in 2 separate tabs, apparently.

@guillo umm ... what? that doesn't make any sense at all!

Here's the error that appeared:
"Redefinition of void setup"
Cant manage to paste the entire error code here

A couple of hours in the making I managed to merge them together. Thanks for your replys tho!

@guillo just to be clear, it's not "I used 2 Voids", but "I declared 2 setups". You can have infinite void functions, since void is the return type, but every function should have a unique name


text:
ESP8266 does not reconnect to WiFi on reboot
The ESP8266 is supposed to remember the WiFi credentials and reconnect to the network (if it is available) after each reboot.  That was the topic of this question: Does the ESP8266 somehow remember wifi access data?
I was observing that behavior and something has changed, I think when I updated via Board Manager in the Arduino IDE.  Now the credentials are lost each time that the device reboots. I've tried going back to earlier versions, but I have not been able to roll back to a version of the board definition that restores the old behavior.
Here's a sample sketch that I boiled down for testing:
#include <ESP8266WiFi.h>

char ssid[] = "ssid";
char pss[]  = "pass";

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

  Serial.println("Started");

  pinMode(0, OUTPUT);
  pinMode(2, OUTPUT);

  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("Not connected");
    WiFi.begin(ssid, pss);
    digitalWrite(0, LOW);
    digitalWrite(2, HIGH);
  } else {
    Serial.println("Connected");
    digitalWrite(0, HIGH);
    digitalWrite(2, LOW);
  }
}

void loop() {
  Serial.println("Loop");
  delay(500);
}

The first time through, of course, it hits the first case and prints "Not connected."  On reboot, however, I was expecting it to hit the second case and print "Connected".
I'm programming via the Arduino IDE.  The board is the Adafruit Feather HUZZAH ESP8266.  I've tried lwIP v1.4 and lwIP v2 in version 2.4.1 of the board.  I started rolling back versions from there got the same run-time results.
So, questions:

Is this a known bug of the ESP8266 modules in recent versions?
Is there some aspect of the WiFi configuration that's preserved on the board when I upload a new sketch? If so, how do I roll back?

remove the if statement from the setup() block .... put serial.println(WiFi.status()) into the loop() block .... reduce the delay to 100mS ..... that should show you if it connects and how long it takes to connect

The esp8266 SDK libraries starts the STA connection, but it is handled by other thread then the Arduino sketch. You can wait for this connection in setup with waitForConnectResult. It returns status().
  if (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("Not connected");
    WiFi.begin(ssid, pss);
    digitalWrite(0, LOW);
    digitalWrite(2, HIGH);
  } else {
    Serial.println("Connected");
    digitalWrite(0, HIGH);
    digitalWrite(2, LOW);
  }

to connect with remembered STA mode, ssid and password, but with static IP address
  WiFi.setAutoConnect(false);
  IPAddress ip(192, 168, 1, 8);
  IPAddress gw(192, 168, 1, 1);
  IPAddress sn(255, 255, 255, 0);
  WiFi.config(ip, gw, sn, gw);
  WiFi.begin(); // uses remembered ssid and password
  WiFi.waitForConnectResult();

This fixed the issue in the sample sketch that I created for the question.  For anyone coming along later, to make it work in the real sketch, I had to use this and also coordinate it with other aspects of the WiFi set-up, especially the selection of the mode.  My original was changing the mode from AP to AP+STA over the course of the sketch, and I had to eliminate that part so that it is in AP+STA from the start.  Strange that this same sketch worked before and then suddenly stopped, but I'm happy to having working again now.

mode and AP settings are remembered too and initiated parallel to sketch

First, let's answer the OP's questions directly:

Is this a known bug?
Ans: There are and will continue to be '[issues][1],' but as
@Juraj's    answer points out it was not an issue, but a sketch that
wasn't    waiting for the quickest method to get wifi + IP ready on
an esp8266,    the SDK connect.

Is there ... WiFi configuration that's preserved on the board when I upload a new sketch? How to roll back?
Ans: There is no 'rolling back,' only erase & write new data to flash to recover. At the time of sketch upload, 'wifi settings' can only be erased. The user would choose in the Arduino IDE menu > Tools > Erase Flash: Sketch + Wifi Settings. Those 'wifi settings' are typically written to flash by calling

WiFi.begin(ssid,passphrase);  // or,
WiFi.begin(ssid,passphrase,channel,bssid,connect);  // about 2x quicker

The final arg can be false; we don't even need to connect to wifi to save the settings, eg.
begin("ssid", "passphrase", 1, {0xA4,0xB1,0xE9,0xBC,0x6A,0x28}, false);
ESP.restart();

Then wait for the SDK firmware to connect.
And now let's conclude with the 'newer' information, due to changes in the Arduino esp8266 core 3.0, circa mid-2020.
Beginning in core 3.0, the SDK connect feature was disabled by default. Since then, sketches wanting to take advantage of the quick SDK connect (about 220 ms, or twice as fast as any WiFi.begin), the following line must be included early in the setup() function
enableWiFiAtBootTime();                // prevents shutdown of sdk connect


text:
Entire arrays are not read by Processing sent by Arduino unless cord is unplugged and plugged back in?
I am using an Arduino to read sensors and then send the data to the serial port for Processing to read. It works totally fine when I first download the code and run the Processing program. But if I stop the Processing code and then start it again I will get the error ArrayIndexOutOfBounds. I print the array that Processing reads and it is only 3 indexes long, even though the Arduino code should be sending an array that's 7 long. This error happens because I am calling an index that doesn't exist, but it should exist, Processing just isn't receiving the entire array. If I unplug the USB cord from the Arduino and plug it back in this error won't happen and Processing will receive the entire array. I don't understand why this is happening. I have tried using the button on the Arduino to reset it each time before running the Processing code but this doesn't work, I actually need to unplug the cord and plug it back in.
If you have any input that would be great! Thanks in advance!
EDIT:
I am posting the code because it was requested. There's a lot of unnecessary stuff on reading the sensors and creating graphics for in Processing. The gist is that the user interacts with a Processing program and clicks when the want the data sent by Arduino to be saved. I had been talking to someone else about the problems Ive been having and they think it may have to do with the serial buffer, and that I need to clear it or wait for it to be cleared. I have looked into this and am having trouble figuring out the proper way to do it. I have tried resetting the Arduino code using SoftRestart library, but that hasn't worked.
Here's the Arduino Code:
//need to include these libraries to be able to read from serial and read   the sensors
#include <SoftwareSerial.h>
#include <Wire.h>
#include "Adafruit_MCP9808.h"
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include <AMS5915.h>
#include <AMS5812.h>
#include <Adafruit_ADS1015.h>

//Create sensor objects.
Adafruit_MCP9808 tempsensor18 = Adafruit_MCP9808(); //sensor with 0x18 address is Dry Bulb Temp
Adafruit_MCP9808 tempsensor19 = Adafruit_MCP9808(); //sensor with 0x19 address is Temp in chamber
Adafruit_BME280 bme; //pressure and humidity sensor
AMS5915 amsD; //sensor being used for reading differential pressure across the nozzle
AMS5812 amsS; //sensor being used to measure static pressure in the chamber
Adafruit_ADS1115 ads; //16-bit ADC sensor (actually 15-bit when used as a single-ended ADC)

//Initializing variables
float tableVals[]={0,0,0,0,0,0,0,0}; //an array that will hold sensor values. If more sensors or readings are added the size of the array needs to increase
float relHum=0;
float dryBulb=0;
float wetBulb=0;
float pressure=0;
float chamberTemp=0;
float pressureDiff;
float pressureStatic;
float rpm;
float correctedADC=0;
float correctedRPM;
float correctedADCx2=0;
float correctedRPMx2=0;
int counts=0;
const float AMS5915_0010_D_B_P_MIN = -10.0;     // minimum pressure, millibar (for sensor reading differential pressure)
const float AMS5915_0010_D_B_P_MAX = 10.0;      // maximum pressure, millibar (for sensor reading differential pressure)
const float AMS5812_0003_D_B_P_MIN = -0.3;      // minimum pressure, PSI (for sensor reading static pressure)
const float AMS5812_0003_D_B_P_MAX = 0.3;       // maximum pressure, PSI (for sensor reading static pressure)
const float AMS5812_0003_D_B_T_MIN = -25.0;     // minimum temperature, C (for sensor reading static pressure)
const float AMS5812_0003_D_B_T_MAX = 85.0;      // maximum temperature, C (for sensor reading static pressure)

//Setup function, will run one time. Initializes sensors
void setup() {
  Serial.begin(9600); //set baud rate
  amsD.getAddr_AMS5915(AMS5915_DEFAULT_ADDRESS);   // 0x28
  amsS.getAddr_AMS5812(AMS5812_DEFAULT_ADDRESS);   // 0x78
  ads.setGain(GAIN_ONE); //1x gain +/- 4.096V  1 bit = 0.125mV
  ads.begin(); //starting sensors
  amsD.begin();
  amsD.begin();
  if(!tempsensor18.begin(0x18) || !tempsensor19.begin(0x19)|| !bme.begin())    {  //wait until these sensors are ready
    while(1);
  }
}

//loop function keeps repeating
 void loop() {
  if (counts >100){  //will only enter conditional if counts variable is over 100
    readSensors(); //go to readSensors function below

    tableVals[0]= pressure; //set pressure to the first index in array
    tableVals[1]=relHum;  //rel hum to the second index in array
    tableVals[2]=wetBulb; //wet bulb to the third index in array
    tableVals[3]=dryBulb; //dry bulb to the fourth index in array
    tableVals[4]=chamberTemp; //chamber temperature to the fifth index in the array
    tableVals[5]=pressureDiff; //differential pressure to the sixth index in the array
    tableVals[6]=pressureStatic; //static pressure to the seventh index in the array
    tableVals[7]=rpm; //RPM is the eighth index in the array
    Serial.flush();
    Serial.print(tableVals[0]); //sending all the values to Processing, need commas so Processing can split into different values (don't totally know why I put everything in an array first, that's just how I saw it done in an example)
    Serial.print(",");
    Serial.print(tableVals[1]);
    Serial.print(",");
    Serial.print(tableVals[2]);
    Serial.print(",");
    Serial.print(tableVals[3]);
    Serial.print(",");
    Serial.print(tableVals[4]);
    Serial.print(",");
    Serial.print(tableVals[5],4);
    Serial.print(",");
    Serial.print(tableVals[6],4);
    Serial.print(",");
    Serial.print(tableVals[7]);
    Serial.println(","); //need this last comma for some reason or it gets messed up
    counts=0; //reset counts variable to 0
  }
  counts++; //increment counts
}

//This function is called in the loop() function. It reads all of the sensors
void readSensors(){
  dryBulb = tempsensor18.readTempC(); //read from temp sensor with 0x18 address
  relHum = bme.readHumidity();  //read humidity from bme sensor
  pressure = bme.readPressure()/100.0F; //read pressure, in hpa
  pressure = pressure * 0.029529983071445; //convert pressure to inches of mercury
  wetBulb = dryBulb*atan(0.151977*pow(relHum + 8.313659, 0.5)) + atan(dryBulb +relHum) - atan(relHum - 1.676331) + 0.00391838*pow(relHum,1.5)*atan(0.023101*relHum) - 4.686035; //equation finds approximate wet bulb temp from humidity and dry bulb temp
  chamberTemp = tempsensor19.readTempC(); //read from temp sensor with 0x19 address

  //this chunk of code gets the differential pressure reading and converts it to inches of water
  byte errorDiff;
  int8_t addressD;

  addressD = amsD.ams_i2cAddress;
  Wire.beginTransmission(addressD);
  errorDiff = Wire.endTransmission();
  if (errorDiff == 0){
    amsD.Measure_PressureAndTemperature(AMS5915_0010_D_B_P_MIN, AMS5915_0010_D_B_P_MAX);
    pressureDiff=amsD.getPressure();
    pressureDiff = pressureDiff * 0.40146307866177;
  }

  //this chunk of code gets the static pressure reading and converts to inches of water
  byte errorStatic;
  int8_t addressS;

  addressS = amsS.ams_i2cAddress;
  Wire.beginTransmission(addressS);
  errorStatic = Wire.endTransmission();
  if(errorStatic == 0){
    amsS.Measure_PressureAndTemperature(AMS5812_0003_D_B_P_MIN, AMS5812_0003_D_B_P_MAX, AMS5812_0003_D_B_T_MIN, AMS5812_0003_D_B_T_MAX);
    pressureStatic = amsS.getPressure();
    pressureStatic = pressureStatic*27.679904842545;
  }

  //the next chunk of code takes 300 readings from the ADC, averages them together. Applies two correction equations to the ADC and then converts it to the RPM that is sent to Processing
  float ADCcount=0;
  float ADCtotal=0;
  float finalADC=0;

  int16_t adc0;
  while(ADCcount<100){ //taking 100 ADC readings and averaging them
    adc0 = ads.readADC_SingleEnded(0);
    ADCcount=ADCcount+1;
    ADCtotal=ADCtotal+adc0;
  }

  finalADC=ADCtotal/ADCcount;
  rpm = (40740.0/32767.0)*finalADC;
}

Processing Code:
//initializing variables
import processing.serial.*; //need this library to read serial data
Serial myPort;
int signal=0; //this will signal what part of the draw function to read
Table table;
int count =-1;
int lf = 10; //10 is the ASCII number that represents an enter key
String d_string;
String m_string;
String y_string;
float countVals[];
float pressureVals[];
String voltage=""; //these variables need to be blank strings since these are the variables that come from user input
String current=""; //they will be changed to floats before being saved in the table
String fileName="";
String COM ="";
float Pdiff;
float Pstatic;

//Set up
void setup(){
  size(300,410); //creating the start graphics
  background(255);
  String s = "Click on the rectangle to start.";
  textSize(20);
  textAlign(CENTER);
  fill(25);
  text(s,10,10, 290, 150);
  fill(255, 0, 0);
  rectMode(CORNERS);
  rect(115,85,195,160); //drawing rectangle 'button'

  table = new Table();  //create new table
  table.addColumn("Date");  //make a Date column
  table.addColumn("Reading Number"); //make a Reading Number column
  table.addColumn("Voltage V");  //Voltage column
  table.addColumn("Current A");  //Current column
  table.addColumn("Pressure inHg"); //Pressure column
  table.addColumn("Humidity %");  //Relative Humidity column
  table.addColumn("Wet Bulb Temp. *C");  //Wet Bulb Temp. column
  table.addColumn("Dry Bulb Temp. *C");  //Dry Bulb temp. column
  table.addColumn("Chamber Temp. *C"); //Chamber Temp column
  table.addColumn("Static Pressure inH20");  //Static pressure column
  table.addColumn("Differential Pressure inH2O"); //Differential Pressure column
  table.addColumn("RPM");  //RPM column

  int day = day();  //Find the day
  int month = month(); //find the month
  int year = year();  //find the year
  d_string = str(day);  //convert these integers to strings
  m_string = str(month);
  y_string = str(year);
}

//Draw function is continuously looping
   void draw(){
      if(signal==1){ //if signal is 1 (set in keyPressed) ask the user to enter the COM
        background(255);
        String f = "Enter what number in the list of COM Ports the Arduino is plugged into (This is not necessarily the COM number.) \nPress ENTER to continue.";
        textAlign(CENTER); //center the text on the screen
        fill(25); //setting fill color
        stroke(0);  //setting stroke color
        textSize(14); //setting text size
        text(f,10,10,290,200); //displaying the instructions in the graphics box
        textSize(20); //resetting text size
        text(COM,10,125,290,200); //displaying the COM the user is typing
      }
      else if (signal==2){ //if signal is 2 (set in keyPressed) ask the user to enter the name of the CSV file where the data will be saved
        background(255);
        String f = "Enter the name of the CSV file where the data will be saved. \nThis will be located in the folder called 'data' that is in the same folder as this application. \nPress ENTER to continue.";
        textAlign(CENTER);
        fill(25);
        stroke(0);
        textSize(12);
        text(f,10,10,290,200); //displaying instructions to the user
        textSize(20);
        text(fileName,10,125,290,200); //displaying the user file name the user is typing
      }
      else if(signal==3){ //if signal is 3 (set in keyPressed) ask the user to input the voltage
        background(255);
        String f = "Enter the Voltage in Volts. Press ENTER to continue.";
        textAlign(CENTER);
        fill(25);
        stroke(0);
        textSize(20);
        text(f,10,10,290,200); //displaying instructions to the user
        text(voltage,10,125,290,200); //displaying the voltage the user is typing
      }
      else if(signal ==4){ //if signal variable is 5 (set in conditional above) ask the user to input the current
        background(255);
        String f = "Enter the Current in Amps. Press ENTER to continue.";
        textAlign(CENTER);
        fill(25);
        stroke(0);
        textSize(20);
        text(f,10,10,290,200); //displaying instructions
        text(current, 10,125,290,200); //displaying the current the user is typing
      }
       else if (signal ==5){ //if signal variable is 4 (set in mousePressed) then read the following chunk of code.
        String val=null;
        while (val==null){
          val = myPort.readStringUntil('\n'); //read serial data sent by Arduino
        }
            val = trim(val); //trim off any white space
            countVals = float(split(val, ',')); //split serial data into individual readings
            delay(500);
            signal =6; //set signal to 6 so next chunk of code will be read
      }
       else if (signal ==6){ //if signal is 6 (set in the above conditional) read the following chunk of code
        TableRow newRow = table.addRow(); //add a row to the spreadsheet
    newRow.setString("Date", m_string +"."+ d_string +"."+ y_string); //write data in the correct columns in the table
    newRow.setInt("Reading Number", count);
    newRow.setFloat("Pressure inHg", countVals[0]);
    newRow.setFloat("Humidity %", countVals[1]);
    newRow.setFloat("Wet Bulb Temp. *C", countVals[2]);
    newRow.setFloat("Dry Bulb Temp. *C", countVals[3]);
    newRow.setFloat("Chamber Temp. *C", countVals[4]);
    newRow.setFloat("Differential Pressure inH2O", countVals[5]);
    newRow.setFloat("Static Pressure inH20", countVals[6]);
    newRow.setFloat("Voltage V", float(voltage)); //values that were strings are converted to floats
    newRow.setFloat("Current A", float(current));
    newRow.setFloat("RPM", round(countVals[7]));
    saveTable(table, "data/"+fileName+".csv"); //saving the data in a folder called 'data' in a file with the user given name
    signal = 7; //signal variable back to 7 to read the next conditional
  }
  if(signal ==7){ //if signal is 7 (set in conditional above or in keyPressed), read serial port data and display graphics Draw function will continue to loop through this conditional until box is clicked so pressures are always updated.
    String pressures=null;
    while(pressures==null){
      pressures = myPort.readStringUntil('\n'); //read serial data sent by Arduino
    }
        pressures = trim(pressures); //trim off any white space
        pressureVals = float(split(pressures, ',')); //split serial data into individual readings
        println(pressureVals);
        background(255);  //reset graphics
        String s = "Click on rectangle to take a data point. Exit out of this box when done.";
        stroke(0);
        textSize(15);
        fill(25);
        textAlign(CENTER);
        text(s,10,10,290,100); //displaying instructions to user
        fill(50, 255, 200);
        rect(115,85,195,160);
        fill(0);
        textSize(12);
        textAlign(LEFT); //next line will display the previous data point if it is not the first data reading (counts needs to be 1 or greater)
        if (count>0) text("Previous Data Point: \n\t" +"Barometric Pressure inHg: " + str(countVals[0]) +"\n\tHumidity %: " +str(countVals[1]) + "\n\tWet Bulb Temp *C: " + str(countVals[2]) + "\n\tDry Bulb Temp *C: " +str(countVals[3]) +"\n\tChamber Temp *C: " + str(countVals[4])+"\n\tDifferential Pressure inH20: " + str(countVals[5]) +"\n\tStatic Pressure inH20: "+ str(countVals[6]) + "\n\tRevolutions Per Min: " + str(round(countVals[7])),10,190, 300,400);
        textAlign(10, 400);
        text("Static: " +str(pressureVals[6]) + " in.H20", 10,400); //display the static pressure on the bottom of graphics window
        textAlign(150, 400);
        text("Diff: "+ str(pressureVals[5]) + " in.H20", 150, 400); //display the differential pressure on the bottom of graphics window
  }
}

//mousePressed function will run when mouse is clicked in box
void mousePressed(){
  if(mouseX <= 195 && mouseX >= 115 && mouseY <=160 && mouseY >=85){ //if the mouse is clicked within the boundaries of the rectangle
     if(count>=0){ //if counts is greater or equal to 0 (counts starts at -1, this was b/c there were some glitches with the first click being registered)
       signal=5;
       String d= "DATA TAKEN"; //display "DATA TAKEN" to signal that a data point was taken
       textSize(15);
       fill(255,0,50);
       textAlign(LEFT);
       text(d, 107, 180);
    }
    else{   //will run if counts is not greater than or equal to 0 (so this will just be on the first click before data is taken)
      signal=1;
    }
    count++; //increment count
    mousePressed = false;  //set mousePressed to false to make sure this function doesn't run again.
  }
}

//keyPressed will run when a key on the keyboard is pressed
void keyPressed() {
  if(signal==1){ //if signal variable is 1...
    if(key==BACKSPACE){ //if the key pressed is BACKSPACE
      if(COM.length()>0){ //if length of what is being typed is greater than 0
        COM = COM.substring(0,COM.length()-1);  //then get rid of the last character
      }
    }
    else if (textWidth(COM+key) < width && key != ENTER){ //if what is being typed is not greater than the width of the graphics window and the key pressed is not ENTER
      COM = COM +key; //add the key pressed to the end of what is being typed
    }
    if(key ==ENTER){ //if ENTER is pressed
      signal=2; //change signal variable
      String portName = Serial.list()[int(COM)]; //COM is not necessarily the COM number the Arduino is plugged into. It's the number in the list of COMS that the COM is listed. I used trial and error to figure this out
      myPort = new Serial(this, portName, 9600);  //setting up baud rate
      myPort.bufferUntil(lf); //I don't know if this is actually necessary
    }
  }
  else if(signal==2){ //if signal variable is 2...
    if(key ==BACKSPACE){ //these first two conditionals for this signal number are the same for all the signal number conditionals.
      if(fileName.length()>0){
        fileName = fileName.substring(0,fileName.length()-1);
      }
    }
    else if (textWidth(fileName+key) < width && key !=ENTER) {
      fileName = fileName +key;
    }
    if (key == ENTER) { //If key pressed is ENTER
      signal=3;  //change signal
    }
  }
  else if(signal==3){ //If signal is 3...
    if(key ==BACKSPACE){
      if(voltage.length()>0){
        voltage = voltage.substring(0,voltage.length()-1);
      }
    }
    else if (textWidth(voltage+key) < width && key!=ENTER) {
      voltage = voltage +key;
    }
    if (key == ENTER) {
        signal=4;
    }
  }
  else if(signal ==4){ //if signal is 4...
    if(key == BACKSPACE){
      if(current.length()>0){
        current = current.substring(0,current.length()-1);
      }
    }
    else if (textWidth(current+key) <width && key != ENTER) {
      current = current + key;
    }
    if (key ==ENTER){
          signal=7; //change signal to 7 and display graphics to take a data point
      key = BACKSPACE;
      background(255);
      String s = "Click on rectangle to take a data point. Exit out of this box when done.";
      stroke(0);
      textSize(15);
      fill(25);
      text(s,10,10,290,100);
      fill(50, 255, 200);
      rect(115,85,195,160);
    }
  }
}

Sorry, this is probably very hard to follow. I do not have that much coding experience so I'm sure my logic isn't very good.

I would suggest that you are seeing reset-stutter from the serial. Basically the sketch is running and filling the serial buffer with data. Then you connect and the board resets, but some data is still in the USB chip's buffer. The sketch then starts running again, and new data is sent.
In effect I am guessing you may be seeing something like:
3.87,4.45,55.13,
19.44,43.12,14.56,1.01,23.87,4.45,55.13,
19.44,43.12,14.56,1.01,23.87,4.45,55.13,
19.44,43.12,14.56,1.01,23.87,4.45,55.13,
19.44,43.12,14.56,1.01,23.87,4.45,55.13,

where the first line is left over from the previous execution before the reset.  You don't get that with a complete unplug and re-plug because there is no "previous" data in the USB buffer to send.
The simplest solution is just to handle it gracefully.  Take a look at the .length of your float array and see if it's correct or not. Only if it has enough entries in it do you actually want to deal with the data - otherwise, you just throw it away and wait for the next line to arrive.


text:
How to detect water presence with only 2 wires
I don't know if this question belong here or on electronics SE.
A manufacturer just sent me a personalize device which include an ESP-32 and a Water Sensor.
My problem is that I don't know how to retrieve the water sensor data (if there is water or not).
When I used my Arduino Nano and a Funduino Water Sensor, it was easy to retrieve the value because this sensor got 3 connectors (VCC, GND, Data), I just had to do a basic analogRead(DATA_PIN).
But now, as you can see on the diagram bellow, the water sensor is just composed of 2 wires. I presume that it will detect water when these two wires are going to be connected by water.
So, How to detect the presence of water in Arduino using only these 2 wires ?
What I tried :

Analog Read on the pin GPIO33
Digital Read on the pin GPIO33
Try to use TOUCH_PAD with this pin using touchAttachInterrupt(T8, callback, Threshold); but callback was never called
Contact the manufacturer (He said that it works perfectly, he used touch_pad for testing but never used Arduino IDE, only ESP-IDF that I really don't know)

simulate this circuit – Schematic created using CircuitLab
EDIT:
This image represent the back of the device with the sensor, inner wire is directly connected to GND and outer wire is connected to GPIO_33. This is all, there is not hidden connectors or something else.

You'll have to show us what this mystery sensor is.

@Majenko I edited the question with a photo of the device

So it is just literally 2 bare wires then? Nothing else?

Yep that's it, one connected to GPIO_33 and the other connected to GROUND

Since all you have is 2 bare wires, the water simply forms a resistor between them.
You can use it as part of a resistive divider, with a fixed resistor between your analog input and +3.3V.  The resistance between the wires will change from infinite (dry) to something much lower (wet) and the reading you get from the ADC will depict that.
You will need to experiment with different resistances in order to get reasonable values, but start with 10kΩ, or 100kΩ.  If you use a very high resistance (in the order of 1MΩ or more) you may even be able to use it like a simple switch and connect it to a digital input.
Be warned, though, that this method will cause a small amount of electrolysis, causing one electrode to be eroded away and the other to gain extra material.  For this reason it can be good to connect the resistor to a GPIO pin instead of directly to +3.3V and switch the GPIO pin HIGH when you want to do a reading (to provide power) and LOW (or INPUT) when at other times (to remove power).  This will greatly increase the lifetime of your water sensor.

Hum, the device is already functional, and I don't have to add electronic parts
(according to the manufacturer). I just need a way to obtain the value I guess

I am not familiar with the ESP32, but you may be able to do it by turning on an internal pullup resistor on the GPIO pin.


text:
What's the problem? My motor works properly only when we press the left key and not others
int mf11=13;//motor1 1st terminal
int mf12=12;//motor1 2nd terminal
int mf21=9;//motor2 1st terminal
int mf22=8;//motor2 2nd  terminal
int fr=2;//front key
int bk=3;//back key
int rt=4;//right key
int lt=5;//left key

void setup() {
    pinMode(mf11,OUTPUT);
    pinMode(mf12,OUTPUT);
    pinMode(mf21,OUTPUT);
    pinMode(mf22,OUTPUT);
    pinMode(fr,INPUT);
    pinMode(bk,INPUT);
    pinMode(rt,INPUT);
    pinMode(lt,INPUT);
}

void loop() {
    int s = digitalRead (fr);
    int h = digitalRead (bk);
    int i = digitalRead (rt);
    int v = digitalRead (lt);
    if(s==HIGH) {
         digitalWrite(mf11,HIGH);
         digitalWrite(mf12,LOW);
         digitalWrite(mf21,HIGH);
         digitalWrite(mf22,LOW);
    }
    if (h==HIGH) {
        digitalWrite(mf11,LOW);
        digitalWrite(mf12,HIGH);
        digitalWrite(mf21,LOW);
        digitalWrite(mf22,HIGH);
    }
    if (i==HIGH) {
         digitalWrite(mf11,LOW);
         digitalWrite(mf12,HIGH);
         digitalWrite(mf21,HIGH);
         digitalWrite(mf22,LOW);
    }
   if (v==HIGH) {
        digitalWrite(mf11,HIGH);
        digitalWrite(mf12,LOW);
        digitalWrite(mf21,LOW);
        digitalWrite(mf22,HIGH);
   } else {
       digitalWrite(mf11,LOW);
       digitalWrite(mf12,LOW);
       digitalWrite(mf21,LOW);
       digitalWrite(mf22,LOW);
  }
}

Would need schematics to be able to tell whats going on....   Also I am guessing you really want to use else if statements rather then separate if statements as the else only applies to the if(v==HIGH) statement  (this may be part/all of your issue, as that is the condition you say works)

The reason your code only works for left, is because when v is LOW your else block gets executed and sets all pins to low! You need to use else if.
if(condition1)
{
  ...
}
else if (condition2)
{
  ...
}
else
{
  ...
}


text:
Where in datasheet is the warning about unreliability of reading PINxn?
I use atmega32u4 (but believe it applies to all models). Here is the datasheet.
Consider the following C program (I use AVR-GCC 5.4.0):
#include <avr/io.h>
int main(void)
{
  PORTB |= 1 << PB5; /* pullup */
  DDRB |= 1 << PB0; /* LED */
  if (!(PINB & 1 << PB5))
    PORTB |= 1 << PB0; /* turn on LED */
  while (1) ;
}

There are two situations:

connect a 10cm wire to PB5 pin (the other end of the wire is in the air): the result is that sometimes after poweron the led is on, sometimes the led is not on.
do not connect anything to PB5 pin: the result is that after poweron led is never on.

I have a standard setup. Nothing tricky. If it does not work reliably, this gotcha MUST be documented in datasheet. This setup is supposed to deal with a stupid button. But sometimes it detects a keypress while there is no keypress.
The question is: where in datasheet there is a warning about this gotcha?
And did somebody come across such case, or I'm the first in the world?
EDIT See also this question.

the internal pullup is pretty weak ... there may be too much radio interference in your area .... try using an external 1k resistor for pullup .... increase the value until failure occurs again, then use the largest value resistor that provides correct functionality

@jsotola ok, but I need to know where it is mentioned in datasheet (remember: it is a standard button, and I doubt that a 10 cm wire can have any influence even if "there may be too much radio interference in my area")

It's not in the datasheet because it's a basic characteristic of all CMOS circuits, and should have been covered in Digital Electronics 101.

@jsotola OK, put it in the answer please. Now (as a newbie) I know that internal pullup is not useful for anything. Good to know this.

I know that internal pullup is not useful for anything ... that is not true ... it works great for switches .... also you abused the intended usage of the chip .... you should not have an antenna connected to the input pin

did somebody come across such case, or I'm the first in the world?

You are not the first. I recently got bitten by the very same issue.
However, unless you are close to an unusually strong radio source, I do
not think it has anything to do with electromagnetic interference. In my
experience, the internal pullup is perfectly reliable for reading
switches and push buttons, even on a breadboard with jumper wires acting
as antennas. If you use pinMode() and digitalRead() instead of
direct port access, you too will find the internal pullup is perfectly
fine.
Before I give you the answer (suspense...), let's look closely at what
your code does. The disassembly looks like this:
main:
    sbi  PORTB, PB5 ; turn on pullup on PB5
    sbi  DDRB,  PB0 ; set LED pin as output
    sbis PINB,  PB5 ; read PB5, if it is LOW then:
    sbi  PORTB, PB0 ;   turn on LED
0:  rjmp 0b         ; hang in an infinite loop

In the situation when the LED turns on, every instruction there executes
in two CPU cycles, save for sbis, which takes a single cycle in this
case. Now, let's look at the timings, and specifically at the states of
the pullup and the input circuitry during each of the first seven CPU
cycles:
cycle   instruction   pullup latch PINB5
----------------------------------------
   1   sbi PORTB, PB5   off    X     X
   2      cont.         off    X     X
   3   sbi DDRB,  PB0   on     X     X
   4      cont.         on    LOW    X
   5   sbis PINB, PB5   on     X    LOW
   6   sbi PORTB, PB0   on     X     X
   7      cont.         on     X     X

In the table above, “X” means “don't care”. Each instruction takes
effect at the beginning of the next CPU cycle, when the clock's rising
edge commits the result of the instruction to the affected flip-flops.
That's why the pullup turns on only at the beginning of cycle 3.
Now, since the pin did read LOW, that means the PB5 flip-flop was LOW
while the CPU was reading it, during cycle 5. This in turn means
that the synchronizing latch before that flip-flop was LOW during
cycle 4.
Your expectation was for the pin to read HIGH. So let's see: how fast
should the pin voltage have risen in order for the pin to indeed read
HIGH? Since the input latch is transparent during the first half of each
cycle, this means that the voltage should raise past the Schmitt
trigger's threshold during cycle 3 and the first half cycle 4.
So the rise time should be less than 1.5 cycles. Or rather
1.5 cycles minus the combined propagation delay of the PORTB5
flip-flop and the logic that controls the pullup from that flip-flop's
output. Probably around 90 ns. That's short!
By now you have probably guessed: the culprit is not electromagnetic
interference, it's stray capacitance. A simple calculation will show you
that about three picofarads is enough to produce the effect you are
seeing. This is the kind of stray capacitance you will find everywhere,
even between the PCB traces of your Arduino board. Note that
electromagnetic noise can add some unpredictability to what you see, as
the pin is susceptible to it when it's completely floating, i.e.
before you turn on the pullup, which makes the initial voltage (at the
beginning of cycle 3) unpredictable. But once the pullup is on and
the pin has settled, you won't care about noise anymore, unless it's
unusually strong.
The solution to your problem is simply to wait for the pullup to charge
the stray capacitance. A microsecond delay should be enough to fix the
issue. Alternatively, use the Arduino functions instead of direct port
access: they are so slow that you will not need any extra delay.

where in datasheet there is a warning about this gotcha?

In section 18.2.4 – Reading the Pin Value: “[The synchronizing latch] is
needed to avoid metastability if the physical pin changes value near the
edge of the internal clock, but it also introduces a delay.”
(emphasis mine).
Edit: In a previous version of this answer, I incorrectly stated
that sbi is a single cycle instruction, which required the voltage to
rise in half a cycle instead of 1.5 cycles. The corrected timing is
still short enough for stray capacitance to be a valid explanation of
the observed behavior.

In summary:

The stray capacitance attached to the pin, together with the pullup
resistor, for an RC circuit.
As the pin is initially floating, it's initial voltage is
unpredictable.
When the pullup is turned on, the voltage starts to rise from whatever
initial value it had to 5 V.
After some time, which can be typically of the order of the RC time
constant, the input Schmitt trigger turns HIGH.
After some extra delay introduced by the synchronizer, the PINxn
flip-flop turns HIGH.
If the CPU reads the PINx register before that happens, it gets a LOW
reading.

Could you explain in a couple of words what this "latch" and "synchronizer" stuff is all about? Or recommend a resource which explains it in a more understandable way than the datasheet?

@IgorLiferenko: This is common electronics knowledge. The latch is a D latch, similar to a D flip-flop, but sensitive to clock levels instead of clock edges. The synchronizer synchronizes the input signal with the internal clock in order to prevent metastability, i.e. the “undecided” states in between LOW and HIGH. It's a non-trivial topic. You can try a Web search or this in depth tutorial (warning: not a light reading).

To sum it up: the delay from metastability synchronization input circuit sometimes is enough for the
stray capacitance to settle, and sometimes not. And the stray capacitance has more chance (with other conditions being equal) to affect the input pin when reading of pin is delayed by 1/2 cycle than
when by 1.5 cycles. Is it correct?

@IgorLiferenko: I couldn't understand your summary, so I added my own.

A test with an Arduino Uno.
I used the usb connector to power-on the arduino uno. The led is at PB5, so I have exchanged PB0 and PB5. My test is therefor not the same.
#define LED_PB  PB5   // pin 13, onboard led
#define INP_PB  PB0   // pin 8, antenna

void setup(void)
{
  noInterrupts();
  PORTB |= 1 << INP_PB; /* pullup */
  DDRB |= 1 << LED_PB; /* LED */
  if (!(PINB & 1 << INP_PB))
    PORTB |= 1 << LED_PB; /* turn on LED */
  while (1) ;
}

void loop()
{
}

Using it next to my computer and phone, sometimes the led stays on. I can even find a spot behind my computer monitor (with CCFL backlight) where the led always turns on.
Then I went outside, away from metals, wifi, and so on. The air humidity outside is 70% at the moment, which is high. I put it on a wooden table, so there is no charge by plastic. I used a battery to power the arduino uno. Then the led never turns on.
In such a clean environment, the internal pullup resistor was probably strong enough to pull the pin high during that very short time.
@IgorLiferenko, @sa_leinad gave the right answer. What you noticed is normal. It is totally normal. That behaviour can be expected. It will be worse when your circuit is not well designed.
A oscilloscope will not help. As soon as you connect a oscilloscope, you have changed something. It will also be very hard to detect that very short time (less than a microsecond).
In my opinion the influence by radio waves is only half of the problem. I think the electrical charge of the air, and the capacitive coupling of the wire with the air might have a larger effect.

You have made an antenna with the 10cm wire and are receiving radio waves which is translating to voltages on your input pin. This is why you don't have the same trouble when the wire is not connected.
According to www.csgnetwork.com/freqwavelengthcalc.html your 10cm wire is picking up frequencies of 750 MHz based on a quarter wavelength calculation.
The datasheet states that the internal pull up resistance is roughly between 20K - 50K ohms. As mentioned in the comments, this is quite weak.
There are two things that you can do that I can see:

Add a stronger pull up resistor (a value between 1K and 5K ohms should do)
Add a decoupling/bypass capacitor.

The reason that this is not in the datasheet is because this is a general electronics/physics knowledge, not a characteristic of the micro-controller itself.

Is there any explanation to the fact that this effect manifests itself only right after enabling pullup, never after a delay (I used 10ms to check)?

@IgorLiferenko, how many explanations do you want? The radiowaves are reflected by metals and can be unpredictable. Perhaps the air is dry and is charged. The internal multiplexer might have influence. How scientific was your test? Did you try it with an other computer and other arduino board in another location? Have you made your own circuit with a atmega32u4, did you forget to decouple the vcc or are the crystal and 22pf capacitors not close to the atmega? Maybe the voltage is too low or there is a grounding error. I can think of about 20 explanations, and others perhaps another 80.

@Jot If you are interested, try the simple setup as I described in OP - I'm sure you will get the same results. I just thought somebody came across such problem before... Now I'm sure that the only way for me to find out what is going on, is to get an oscilloscope...

@IgorLiferenko I did, see my answer.

This actually is documented in the datasheet and illustrated by the logic diagram of the typical GPIO, to see what is really going on behind your compiled code you need to look at the generated assembly code and which registers are being accessed:

When you change one bit of an IO port, you are either modifying the 8 bit register on which that bit is mapped using the WRx signal or just the 1 bit register for the pin alone using the WPx signal.  When you use the WPx signal to set or clear the bit, you don't need to know the states of the other pins so the discussion ends here.  However, when you use the WRx signal to MODIFY a single bit, you need to know the states of the other 7 bits which means that your need to read the 8 bit port.  You can either read the port LATCH using the RRx signal or you can read the actual physical pins using the RPx signal.  Now when using the RRx signal, no amount of loading or noise on the pins themselves will affect what is read from the output of the port latch but when using the RPx signal, if a previous write to the port is followed by a read of the port, any parasitics or noise on the OUTPUT pins may cause a pin that you think that you just set to a one suddenly becomes a zero.
The reason this happens is because of how opcodes are pipelined.  Writes to ports happen at the end of the last instruction clock but reads happen at the beginning so that there is essentially zero time between when you set that bit to a 1 and when you change some other bit (Read-modify-write fashion) so that bit is still a zero when it is read and then immediately written as a zero.
As illustrated below, this can be rectified by inserting a delay between write and read-modify-write opcodes to let the pin states stabilize.  The delay must take into account the capacitive loading and noise environment

The WRx vs WPx distinction has nothing to do with whether you are writing a single bit or the whole register: WRx is the signal for writing the PORTxn flip-flop, whereas WPx is for writing PINxn (which is actually used to toggle PORTxn). And note that the OP did include a two-cycle delay between writing and reading.

You have apparently missed the entire point:  When read-modify-write reads from the pins and then writes the latch, noise or delay on outputs can be re-written to the output and possibly changing the output's state unintentionally.  Adding one cycle, tow cycles or a thousand cycles of delay may not be sufficient and understanding the mechanism of this uncertainty is the only way to build robust platforms that operate predictably under ALL circumstances.

You also missed my point. I told you about a factual error in your answer. The appropriate response in this case is to edit the answer and fix the error. Your point that I still don't get is the one about “When read-modify-write reads from the pins and then writes the latch [...]”. Do you actually mean “reads from PINx and writes to PORTx”? If so, it's irrelevant. Nobody does that. Certainly not the OP.


text:
Running two NEMA 17 motors, one by one, using the Arduino Uno
I am new to Arduino. I am trying to run two stepper motors NEMA 17 through respective A4988 driver and controlling via Arduino Uno.
The thought is that first stepper motor will carry out a first horizontal scan and then as it reaches to its initial position, second stepper motor will move a single step in vertical direction. This is a kind of raster scan that I want to perform with both motors.
When I am running the code, only horizontal scan motor is running and vertical scan motor is not moving. I have checked my circuit, motors and drivers and everything is working fine. I think there is some mistake in my code. It is a basic level code and I would really appreciate the help for helping me out.
int x, y; //stepper motor 'x' and stepper motor 'y'
#define BAUD (9600)

void setup()
{
  Serial.begin(BAUD);
  pinMode(6,OUTPUT); // Enable for x
  pinMode(5,OUTPUT); // Step for x
  pinMode(4,OUTPUT); // Dir for x
  digitalWrite(6,LOW); // Set Enable low for x

  pinMode(9,OUTPUT); // Enable for y
  pinMode(8,OUTPUT); // Step for y
  pinMode(7,OUTPUT); // Dir for y
  digitalWrite(9,LOW); // Set Enable low for y
}

void loop()
{

  digitalWrite(9,LOW); // Set Enable low for y

  for(y = 0; y < 20; y++)
  {
     digitalWrite(6,LOW); // Set Enable low for x
     digitalWrite(4,HIGH); // Set Dir high for x - Clockwise

     Serial.println("CLOCKWISE HORIZONTAL SCANNING IN PROGRESS");

     for(x = 0; x < 50; x++) // Loop 50 times
     {
      digitalWrite(5,HIGH); // Output high for x
      delay(10); // Wait
      digitalWrite(5,LOW); // Output low for x
      delay(100); // Wait
     }

    digitalWrite(6,LOW); // Set Enable low for x
    digitalWrite(4,LOW); // Set Dir low for x - Anticlockwise

    Serial.println("ANTICLOCKWISE HORIZONTAL SCANNING IN PROGRESS");

    for(x = 0; x < 50; x++) // Loop 50 times
    {
      digitalWrite(5,HIGH); // Output high
      delay(10); // Wait
      digitalWrite(5,LOW); // Output low
      delay(100); // Wait
    }

    Serial.println("ONE STEP CLIMB ON VERTCAL AXIS");

    digitalWrite(7,HIGH); // Set Dir high for y

    digitalWrite(8,HIGH); // Output high for y
    delay(100); // Wait
    digitalWrite(8,LOW); // Output low for y
    delay(100); // Wait
  }

  digitalWrite(9,LOW); // Set Enable low for y
  digitalWrite(7,LOW); // Set Dir low for y

  Serial.println("RESETTING ON VERTCAL AXIS");

  for(y = 0; y < 20; y++) // Loop 20 times
    {
      digitalWrite(8,HIGH); // Output high for y
      delay(10); // Wait
      digitalWrite(8,LOW); // Output low for y
      delay(100); // Wait
    }

}

Do i need to look after the delay being provided??

Stupid question, but are you expecting the motors to move at the same time?

First of all I find it strnage that you put the baud rate as a macro and the pins as constants. I strongly suggest to declare the pin names as constants (e.g. const byte X_EN = 6;), so that you can easily redefine them and avoid forgetting one. Then are you sure the second motor is not moving? Maybe the stepper is a 200 step/turn, and in one turn you move 1mm, so the full 20 steps are 0.1mm and you can't see it... Can you try swapping X and Y motors?

@ code gorilla - No both motors will not run at the same time. X motor  - 50 steps to right, then 50 steps to left. Then Y motor will movie one step up. Again X motor moves 50 steps to right and then 50 steps to left. Then again Y motor will move one step up. This loop continues for 20 steps of Y motor. At the end of 20th, Y motor moves 20 steps down. the loop continues.

@ frarugi - Yes, second motor is not at all working. I have also tried to swap both motors. But no result. One thing i want to share that i am using A4988 and HR4988 drivers. Is that any problem?? Because when they are used together, A4988 connected motor is not working and HR4988 connected motor is working. When i swapped the drivers, neither of the two motors is woking.

A minor issue that probably won't affect your result is that
Serial.println("ONE STEP CLIMB ON VERTCAL AXIS");
--> digitalWrite(9,LOW);  // This line 'needs' adding
digitalWrite(7,HIGH); // Set Dir high for y

I can't see anything in the code that will prevent the motors running, OK it will take ~13 seconds to start moving, but it should move.
So - without any hardware attached to the motor spindles - is it possible to switch the motors over to check for a wiring breakage issue?  With one motor working and one not it implies to me that either the motor is broken, the wiring is broken or the driver circuit is broken.  If the fault moves then its a motor/wiring fault if it stays the same then its a driver fault.

it's at the beginning, and it never gets modified...

@frarugi87 - Yes and so is the one for the X axis, but that's also set in the loop.  Its just my natural software engineer's distrust of hardware that says it could be that, because you never truly know what the pixies are doing on that blue board.:)


text:
Caluclate lux value from LDR
I am using an LDR (Iduino SE012) to measure light. It returns a 10-bit value of the incoming voltage and I don't know how to convert this into lux, lumen candela or any other light-intensity unit. I was googling for datasheets but nothing useful came up. So is there any way how I can extrapolate a light intensity from the voltage?
I mean one idea that I would have is to measure some things where I know the lux output, but since I don't have such things or a luxmeter I'm pretty stuck. It also returns 1024 pretty quick if you hold it into the sun (Altough the sun is very strong today and it has 36°C). Is there maybe a "minimal value" at wich it returns the full voltage? From that point I could calculate it for all the other values.
Here are some datasheets I found:

https://www.manualshelf.com/manual/iduino/se012/datasheet-english.html
https://wakamatsu.co.jp/waka/SE012.pdf

I'm in no way known on this subject, but if you have reference lights you could gauge/plot them to find the corresponding values for your sensor?

The cheapest lux sensor is the bh1750. If you buy a bh1750 you can make a table for the ldr to get the lux value. Maybe you can also add a ds18b20 temperature sensor to compensate the ldr value for the temperature. Then you can use the ldr...  wait, did the bh1750 do all of that already? A light sensor may not be used with direct sunlight. Neither the ldr or the bh1750.

You can't.
The LDR has a spectral sensitivity which is very different from the
human eye's. The definition of the lux, or any photometric unit for
that matter, pretty much requires that your sensor is filtered in such
a way as to have the human eye's spectral sensitivity.

Well maybe there's some interference of ultaviolet, radio waves and such things but these should be minor. And if you use it to measure sunlight the amount of visible light and UV-light should be relative to each other. So if I accept interference from other spectres would it then be possible?

@The_javascript_King: Most of the spectral response misfit will come from near IR, rather than UV or radio. And it's nowhere near “minor”. If the light you measure has always the same relative spectrum (same relative intensities at various wavelengths), then yes, you could calibrate this in lux. However, the vis/IR ratio of sunlight depends on the height of the sun over the horizon, so you cannot assume a constant ratio.


text:
Can't upload code to an Arduino LilyPad using FTDI
I've tried to upload my code to an Arduino LilyPad (328) using an FTDI basic breakout, but i get this:
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x29

I tried to install the latest FTDI drivers from the FTDI website, tried another PC, tried to install the CDM-2.08.28 driver (latest I think) and nothing.
If I change the PC port the USB Serial Port doesn't change (is always COM3).

Does the Loopback test work? Connect Lilypad's Reset to Gnd, connect D0 to D1, open the serial monitor, see if typed text is echoed back.  If, you have FTDI problems that you need to resolve.

Hi, i can't do the loopback test because i have no jumper cables at the moment, i've done the loopback test on the FTDI breakout using PuTTy, and when i press any keyboard key the Rx LED on the FTDI blinks, anymore tests?

solved ! was able to upload code choosing arduino uno instead of the lilypad (baud reasons if im correct)


text:
Getting 0 cm from ultrasonic sensor when nothing is in front
My Ultra sonic sensor (HC-SR04) is returning these types of values when it has nothing in front:
Ping: 144cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 105cm
Ping: 105cm
Ping: 94cm
Ping: 0cm
Ping: 378cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 106cm
Ping: 106cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 106cm
Ping: 250cm
Ping: 0cm
Ping: 108cm
Ping: 0cm
Ping: 108cm
Ping: 0cm

I am not able to understand why I am getting 0 cm. This value is critical in the program that I am using. Here is a test code which gives me these output:
#include <NewPing.h>

#define TRIGGER_PIN  A5
#define ECHO_PIN     A4
#define MAX_DISTANCE 200

NewPing sonar(TRIGGER_PIN, ECHO_PIN);

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

void loop() {
  delay(1000);
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm());
  Serial.println("cm");
}

Because  of these 0s my robot is making turns which are not expected.
Any idea why this might happen ?

The documentation for the NewPing library states:

Constructor
NewPing sonar(trigger_pin, echo_pin [, max_cm_distance]);

and

max_cm_distance is optional [default = 500cm].

Then:

sonar.ping_cm(); - Send a ping, returns the distance in centimeters or
  0 (zero) if no ping echo within set distance limit

So it would seem that if there is nothing in front of your sensor closer than 500cm, this library returns 0cm. Probably not the best design, but at least it is disclosed.
Thus, you need to write your code such that a 0cm measurement is treated as no obstruction visible; more like an infinite cm measurement.

The library defines NO_ECHO as 0 so you check sonar.ping_cm() == NO_ECHO for clarity.