message:
Traffic light light system with sensors

I'm trying to make a traffic light system with a ultrasonic range sensor as well as a light dependant resistor. I'm trying to make it so that the default setting is 2 seconds red light 1 second yellow 2 seconds green then 1 second yellow, this will then repeat until something else happens - I've got this working fine.

Then I want 2 different states.

One where if something comes with 10cm of the sensor then the buzzer will beep and the yellow light must blink on and off 10x with intervals of 0.1ms. When the object moves away it must then return to the default setting.

Secondly I want it when the LDR detects that the light has dropped below a level the red light will turn on and stay on until a object approaches the sensor. When an object is near the sensor it must then turn the red light off and turn the Green light on.

Here is all the code i have so far and i cant figure out why its not working.
Any help would be appreciated
Thanks

        #define ECHOPIN 3
        #define TRIGPIN 2
        float distance;
        long distancecm;

        int RED = 13;
        int YELLOW = 12;
        int GREEN = 11;

        int piezoPin = 8;

        int sensorpin = A0;
        int sensorvalue = 0;

        void setup() {
          pinMode(RED, OUTPUT);
          pinMode(YELLOW, OUTPUT);
          pinMode(GREEN, OUTPUT);
          Serial.begin(9600);
          pinMode(ECHOPIN, INPUT);
          pinMode(TRIGPIN, OUTPUT);
          }

        void distancesensor()
          {
          digitalWrite(TRIGPIN, LOW);
          delayMicroseconds(2);
          digitalWrite(TRIGPIN,HIGH);
          delayMicroseconds(10);
          digitalWrite(TRIGPIN,LOW);
          distance = pulseIn(ECHOPIN, HIGH);
          distancecm = distance/29.1/2;
          if (distancecm <=10);
            for (int j=1; j<=5; j=j+1)
            {
             tone(piezoPin, 1, 500);
             digitalWrite(YELLOW, HIGH);
             delay(100);
             break;
             }
        }

        void lightsensor()
          {
          sensorvalue = analogRead(sensorpin);
          if (sensorvalue > 500)
            digitalWrite(RED,HIGH);
            digitalWrite(TRIGPIN, LOW);
            delayMicroseconds(2);
            digitalWrite(TRIGPIN,HIGH);
            delayMicroseconds(10);
            digitalWrite(TRIGPIN,LOW);
            distance = pulseIn(ECHOPIN, HIGH);
            distance = distance/58;
            while (distance >10)
              digitalWrite(RED,LOW);
              digitalWrite(GREEN,HIGH);
              digitalWrite(TRIGPIN, LOW);
              delayMicroseconds(2);
              digitalWrite(TRIGPIN,HIGH);
              delayMicroseconds(10);
              digitalWrite(TRIGPIN,LOW);
              distance = pulseIn(ECHOPIN, HIGH);
              distance = distance/58;

           }

        void loop() {
          distancesensor;
          lightsensor;
          digitalWrite(RED, HIGH);          //RED ON
          delay(2000);                      //WAIT 2 SECONDS
          digitalWrite(RED, LOW);           //RED OFF
          delay(200);
          distancesensor;
          lightsensor;
          digitalWrite(YELLOW, HIGH);       //YELLOW ON
          delay(1000);                      //WAIT 1 SECOND
          digitalWrite(YELLOW, LOW);        //YELLOW OFF
          delay(200);
          distancesensor;
          lightsensor;
          digitalWrite(GREEN, HIGH);        //GREEN ON
          delay(2000);                      //WAIT 2 SECONDS
          digitalWrite(GREEN, LOW);         //GREEN OFF
          delay(200);
          distancesensor;
          lightsensor;
          digitalWrite(YELLOW, HIGH);       //YELLOW ON
          delay(1000);                      //WAIT 1 SECOND
          digitalWrite(YELLOW, LOW);        //YELLOW OFF
          delay(200);
          distancesensor;
          lightsensor;
          //REPEAT
          }

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/xIP0Y.jpg

body:
The photo of your circuit doesn't really show, how all the components are wired. For this you should either draw a schematic (which you can do with the schematic tool directly in the question editor) or provide a good visible wiring diagram like from Fritzing (though a proper schematic would be better).

For now I cannot see any wrong wiring, though you definitely should recheck it and add a proper diagram to your question.

For your code I will shortly sketch the functionality of non-blocking code and a state machine:

 1. **Non-blocking code:** Task, that require a long amount of time (this means long for a microcontoller; seconds are long in this context), you should not use code, which blocks the whole program execution, until the task is completed. Instead you should only shortly check, if there is an action to be taken. If not, quickly proceed with other code. This enables you to do, which seems to be multitasking. For timed sequences you can use the `millis()` function. It returns the number of milliseconds since the program has started and overflows after 50 days. The following code saves the timestamp, when the LED was toggled the last time and checks, if enough milliseconds have passed since the last time. This way you can do something else in the meantime (like checking the state of your sensors). Also refer to the `BlinkWithoutDelay` example of the Arduino IDE.

<!-- language: c -->

    unsigned long timestamp = 0;
    unsigned long interval = 500;
    ...
    void loop(){
      if(millis() - timestamp > interval){
        digitalWrite(led_pin, !digitalRead(led_pin));
        timestamp = millis();
      }
    }

 2. **State machine:** A state machine is code, that holds it's current state in a variable, thats mostly numeric. This variable is read at every loop cycle and used to determine, which piece of code is to be executed. In your case you would have states for "red light on", "yellow light on", "green light on", "distance lower than 10cm" and "LDR reports low light condition". Each on this gets it's own number. For convenience you should use an enum. Now on every loop cycle we use a switch case to go to the right code depending on the state. For your case you would set the state code with non-blocking behavior as described above. Then you only need transitions between the states, by setting the state variable.

<!-- language: c -->

    enum STATE {STATE1, STATE2, STATE3};
    STATE state = STATE1;
    ...
    void loop(){
      switch(state){
        case STATE1:
          digitalWrite(led1_pin, HIGH);
          if(millis() - timestamp > interval){
            digitalWrite(led1_pin, LOW);
            state = STATE2;
          }
          break;
        case STATE2:
          // doing whatever this state needs to do and then do transition with setting state variable
          break;
        case STATE3:
          // doing whatever this state needs to do and then do transition with setting state variable
      }
    }

For designing the states and transitions it sometimes makes sense to sketch them on paper. A bubble with a names is a state and then you connect these states with arrows.

Since you want to check the sensors in every state, you should do this outside of the `switch` statement. The measurement functions then do nothing else but the measurement and setting the `state` variable accordingly (so no `digitalWrite()` or `delay()` in there).


sender: user

message:
I2C EEPROM "hangs" on endTransmission()

I am working on the [24LC256][1] EEPROM, [wired as such][2], except 3.3v to the EEPROM, with 'scope clamped on SDA and SCL. I'm using an [address scanner script][3] with a few tweaks, 57600 baud, 10kOhm pullups, 100000 I2C clock, and some serial prints for snooping:

    for(address = 1; address < 127; address++ ) {
        Serial.printf("\nx", address);
        Wire.beginTransmission(address);
        Serial.printf(",");
        error = Wire.endTransmission();
        Serial.printf(".");
        Serial.flush();
        if (error == 0) {
          Serial.printf("I2C device found at address 0xx", address);
          Serial.println("  !");
          nDevices++;
        }
        ...

When the loop hits the address corresponding to the jumpers (pins 1, 2, 3 correspond to address 0b01010abc, aka 0x5?, where ? = binary encoding of those pins), it just sorta hangs:

    4c,.
    4d,.
    4e,.
    4f,.
    50,

(here I have 1, 2, 3 all low, so the chip responds to addr 0x50). Since it's hitting `,` but not `.`, I know it's hanging at `Wire.endTransmission()`. It always hangs at endTransmission at the address encoded by the jumpers.  SCL is low and SDA is high.

Scope trace looks fine counting through the addresses.

[Trace][4] of address not found.

[Trace][5] of hanging at address.

[gif][6] of cycling through last few addresses.

I'm on an Adafruit Feather nrf52 BLE, if that matters.

  [1]: http://ww1.microchip.com/downloads/en/DeviceDoc/21203M.pdf
  [2]: https://cdn.sparkfun.com/assets/learn_tutorials/6/9/3/eeprom_wiring.png
  [3]: https://playground.arduino.cc/Main/I2cScanner
  [4]: https://i.stack.imgur.com/xb0HZ.jpg
  [5]: https://i.stack.imgur.com/Q5Rdg.jpg
  [6]: https://gfycat.com/SeriousBeautifulIndianspinyloach

sender: assistant

body:
Because of the way that the I2C library works, the only place it **can** hang is on the endTransmission. The other calls just buffer stuff up in memory.

There is probably some electrical issue. For example, the pull-up resistors might be better as 4.7k.

There is [another library](http://dsscircuits.com/articles/arduino-i2c-master-library) which handles transmission a bit differently which might resolve the hanging.

However if it is hanging there are probably other issues (cable lengths, pull-up resistors, noise) that are the underlying issue.

The standard library waits in a tight loop for certain interrupts to arrive, and if they don't arrive it hangs indefinitely.

---

> except 3.3v to the EEPROM

You may well need a level-shifter. It's all very well only sending out 3.3V to the EEPROM, but the rest of the circuit is dealing in 5V not 3.3V. You can get suitable level shifters quite cheaply.

Why are you using 3.3V anyway? That chip can handle 5V. I have [a post about that exact chip](http://www.gammon.com.au/forum/?id=10896&reply=2#reply2) which works fine there.


message:
How do I correctly choose components for my current project?

Previously I asked a question that was a bit to broad so I'm narrowing the focus to a single component board of my design.

I have a set of 3 luckylight R/G bar graphs
(datasheet here: https://cdn-shop.adafruit.com/datasheets/KWL-R1230XDUGB.pdf)
A 5.1 V 2A power source
(recycled ac/dc converter voltage tested datasheet here: http://pdf1.alldatasheet.com/datasheet-pdf/view/322359/BOTHHAND/M1-10S05.html)
a series of 5 SN74HC595 (for controlling the LED multiplexing)
and an Arduino Nano.

The purpose of the bar graphs is to show the player how much of his available system energy he/she is using.

The first three bars of the graph are set to Red, the next 5 are yellow, and the final 4 are green.

As various components are switched on, or other activities drain the power of the engine core, a program level command will switch the multiplexing array to have them shut off.

The problem I'm having is getting enough power to each of the LEDs of the bar graph without overloading the IC pins on the Arduino or shift registers and making the colors appear correctly.

I know I could use Darlington arrays, or a bunch of transistors to keep the power going to the LEDs on a line independent of the ICs, but i'm not sure the right way to go about this. I have a few ULN2803 Darlingtons and a lot of 2n2222a transistors.

(Also my current Arduino code only has, at max, 8 LEDs from each register on at the same time, with a forward voltage of 2.4 volts and 20mA per LED. There are three cycles to my code because the bar graphs have three shared cathode pins that run three 2x4 matrices.)

Additionally I don't know precisely how to calculate the resistor values I would need for this arrangement to maintain the same voltage being applied to the 24 simultaneously running LEDs and get their brightness to be equivalent. Currently i'm noticing LEDs that are farther down the 595 logic chain are receiving less power and appearing weaker. (yes i have been running them off the power coming from the Arduino thus far)

Hopefully this is a narrow enough question.

body:
According to [this datasheet](http://www.ti.com/lit/ds/symlink/sn74hc595.pdf) the 595 can drive up to 6 mA per output pin with a maximum of 20 mA for the input to the chip (so, 2.5 mA if you are driving all outputs).

Since your LEDs are quoting a forward current of 25 mA it seems that you will fall somewhat short of providing the 25 mA per LED.

There are higher power shift registers, eg. the [TPIC6B595](http://www.ti.com/lit/ds/symlink/tpic6b595.pdf).

You might want to consider a multiplexing LED driver such as the [MAX7219](https://datasheets.maximintegrated.com/en/ds/MAX7219-MAX7221.pdf). I have [a post](http://www.gammon.com.au/forum/?id=11516) about using that chip.

Your LEDs sound similar to the things that the MAX7219 is designed to drive. It also has inbuilt current-limiting with the current selected by a single resistor.

It isn't clear from your question whether you have the common anode or common cathode device, but you need a common cathode for the MAX7219.

---

The MAX7219 is not that expensive if you buy it from eBay. For example search for "MAX7219 kit". I found hits for 4 x MAX7219 for $US 9.75 including boards, capacitors and LEDs. Just discard the LEDs (8 x 8 dot matrix) and run the wires to your bargraph.

---

> As they are designed to run 7 segment displays how would I connect it to transfer from my current 16 bit binary shift setup ...

They can run in a couple of modes (see the Decode Mode register) and one is to send arbitrary bits. Since you can program in any combination of bits (in my link above there is an array which does a CP437 font) you can therefore make up any combination of bars on and off. I would get one as an experiment (buy one of those kits from eBay) and try the idea out. It will be a lot less mucking around than 595 chips, transistors, current-limiting resistors, and so on.

There are various kits around, some are pre-soldered (which you won't want), some come with SMD chips and some with through-hole chips. Choose SMD or through-hole depending on your confidence with soldering SMD parts.

---

>  I know on my shift registers pins 1-8 go to the LED anodes and Pins 9-11 go to transistors that run the cathodes. Can you help me understand the pin connections to get the MAX to run this?

Looking at your bar graph specs:

[![Bar graph wiring][2]][2]

You have 3 rather than 8 cathodes (pins 14, 9 and 8 are duplicates of 1, 6 and 7). So, you would run the cathode wiring (1, 6, 7) to the first 3 "digit" pins (2, 11 and 6) on the MAX7219. The other 8 wires (marked anodes) would go to the 8 anodes (2, 3, 4, 5, 10, 11, 12, 13).

As you have only used 3 cathode pins you could wire up a second bargraph using another 3 cathode pins (and run the anodes in parallel). That way a single MAX7219 can drive two bargraphs, giving you a total of 24 bars, each of which can show red, green, or yellow at one time.

---

## Example wiring and code

I ordered a couple of the LED modules and worked out a schematic for them:

[![LED bargraph module schematic][3]][3]

One MAX7219 can drive two of the modules.

Example of wiring:

[![LED bargraph wiring][4]][4]

Example code:

<!-- language: lang-c++ -->

    #include <SPI.h>

     // define max7219 registers
    const byte MAX7219_REG_NOOP        = 0x0;
    const byte MAX7219_REG_DIGIT0      = 0x1;
    const byte MAX7219_REG_DIGIT1      = 0x2;
    const byte MAX7219_REG_DIGIT2      = 0x3;
    const byte MAX7219_REG_DIGIT3      = 0x4;
    const byte MAX7219_REG_DIGIT4      = 0x5;
    const byte MAX7219_REG_DIGIT5      = 0x6;
    const byte MAX7219_REG_DIGIT6      = 0x7;
    const byte MAX7219_REG_DIGIT7      = 0x8;
    const byte MAX7219_REG_DECODEMODE  = 0x9;
    const byte MAX7219_REG_INTENSITY   = 0xA;
    const byte MAX7219_REG_SCANLIMIT   = 0xB;
    const byte MAX7219_REG_SHUTDOWN    = 0xC;
    const byte MAX7219_REG_DISPLAYTEST = 0xF;

    // which groups of bars we are addressing
    const byte BARS_1_4   = MAX7219_REG_DIGIT0;
    const byte BARS_5_8   = MAX7219_REG_DIGIT1;
    const byte BARS_9_12  = MAX7219_REG_DIGIT2;
    const byte BARS_13_16 = MAX7219_REG_DIGIT3;
    const byte BARS_17_20 = MAX7219_REG_DIGIT4;
    const byte BARS_21_24 = MAX7219_REG_DIGIT5;

    // within a group, which one (from the left)
    const byte BAR1_RED = 0x80;
    const byte BAR2_RED = 0x20;
    const byte BAR3_RED = 0x08;
    const byte BAR4_RED = 0x02;

    const byte BAR1_GREEN = 0x40;
    const byte BAR2_GREEN = 0x10;
    const byte BAR3_GREEN = 0x04;
    const byte BAR4_GREEN = 0x01;

    // yellow is done by adding red and green
    const byte BAR1_YELLOW = BAR1_RED + BAR1_GREEN;
    const byte BAR2_YELLOW = BAR2_RED + BAR2_GREEN;
    const byte BAR3_YELLOW = BAR3_RED + BAR3_GREEN;
    const byte BAR4_YELLOW = BAR4_RED + BAR4_GREEN;

    void sendByte (const byte reg, const byte data)
      {
      digitalWrite (SS, LOW);
      SPI.transfer (reg);
      SPI.transfer (data);
      digitalWrite (SS, HIGH);
      }  // end of sendByte

    void setup () {

      SPI.begin ();

      sendByte (MAX7219_REG_SCANLIMIT, 5);   // show 6 digits
      sendByte (MAX7219_REG_DECODEMODE, 0);  // using an led matrix (not digits)
      sendByte (MAX7219_REG_DISPLAYTEST, 0); // no display test

      // clear display
      for (byte col = 0; col < 8; col++)
        sendByte (col + 1, 0);

      sendByte (MAX7219_REG_INTENSITY, 7);  // character intensity: range: 0 to 15
      sendByte (MAX7219_REG_SHUTDOWN, 1);   // not in shutdown mode (ie. start it up)
    }   // end of setup

    void loop ()
     {
      // send various test combinations
      sendByte(BARS_1_4, BAR1_RED | BAR2_GREEN | BAR3_RED | BAR4_GREEN);
      sendByte(BARS_5_8, BAR2_RED);
      sendByte(BARS_9_12, BAR2_YELLOW);
      sendByte(BARS_13_16, BAR1_RED | BAR2_GREEN | BAR3_RED | BAR4_GREEN);
      sendByte(BARS_17_20, BAR2_YELLOW);
      sendByte(BARS_21_24, BAR1_RED | BAR2_RED);
     }  // end of loop

This is documented in [my page about the MAX7219](http://www.gammon.com.au/forum/?id=11516&reply=8#reply8).

  [1]: https://i.stack.imgur.com/2EBu7.png
  [2]: https://i.stack.imgur.com/3D2l9.png
  [3]: https://i.stack.imgur.com/SBJk6.png
  [4]: https://i.stack.imgur.com/cRNN4.jpg


message:
Communicating between two Arduinos wirelessly only works when both are connected to the same computer

The transmitter is an Arduino Mega 2560 (China) that is connected to a computer over Serial, from which it only reads data and sends it using a SYN115 433mhz transmitter.

The receiver is an Arduino Nano (China) that drives an 8x8 * 5 led matrix and it reads data using a SYN480R 433mhz receiver.

Everything works as it should, when both devices are connected to my computer over USB.

If I unplug the receiver, the transmitter now stops responding to Serial data and I have to upload a sketch to make it work again, no resetting or power cycling works. But even after "fixing" the transmitter, if the receiver is not to connected to my computer but an external USB power supply (2A) it never receives any data.

I can then plug the receiver back into the computer and things work again.
Also, if I unplug the transmitter while the receiver is still plugged into the computer, the receiver crashes and resets itself.

Obviously there's some power issue when unplugging USB devices causing feedback, but the real issue is the wireless stops working on external power supply.

Both devices are running, it's easy to confirm since the receiver has some scrolling text, and the transmitter blinks an LED when it receives and sends data.

I read at https://arduino.stackexchange.com/questions/12845/serial-communication-not-working-between-two-arduinos-unless-connected-to-comput that both systems need to share ground if connected by wires. Could this affect the wireless signal somehow?

**UPDATE:** Connecting the receiver to a second computer works! (thanks Chris!! I know it was simple, but one can get stuck in one's own thought process ;))

So this is probably power related... Or can the Nano I have require more than just power over USB? I don't touch the serial device on the receiver side at all btw, all it does is read from PIN 2 and pushes data over HW-SPI to the LED matrix.

**UPDATE-2:** Added reciever code as suggested, though I doubt it's the problem here as it's very simple.

    #include <MD_MAX72xx.h>
    #include <RadioHead.h>
    #include <RH_ASK.h>

    #define RADIO_RX 2
    #define RADIO_TX 3 // not used in this scetch but still needed by RH_ASK
    #define RADIO_EN 4 // -||-

    RH_ASK radio( 1200, RADIO_RX, RADIO_TX, RADIO_EN, true);
    MD_MAX72XX mx( SS, 5);

    void setup() {
      radio.init();
      mx.begin();
      mx.control(MD_MAX72XX::INTENSITY, 0);
      mx.control(MD_MAX72XX::TEST, 0);
      mx.clear();
    }

    uint8_t sc_text[128] = "-- No Data --     ";
    uint8_t sc_pos;
    uint8_t sc_charWidth;
    uint8_t sc_charPos;
    uint8_t sc_buf[8];

    int scrollText() {
      mx.update(MD_MAX72XX::OFF);
      if(sc_text[sc_pos] == '\0') {
        sc_pos = 0;
        return 1;
      }
      if(sc_charPos == 0) sc_charWidth = mx.getChar(sc_text[sc_pos++], sizeof(sc_buf)/sizeof(sc_buf[0]), sc_buf);
      if( sc_charPos < sc_charWidth + 1) {
        mx.transform(MD_MAX72XX::TSL);
        if(sc_charPos < sc_charWidth) mx.setColumn(0, sc_buf[sc_charPos++]);
        else sc_charPos = 0;
      }
      mx.update(MD_MAX72XX::ON);
      delay(100);
      return 0;
    }

    char desc[64];
    int temp1, temp2;
    int wind1, wind2;

    uint8_t radio_preamble[] = { 0x7d, 0x6f, 0xe4, 0x26, 0xb5 };

    struct wttr_packet {
      uint8_t preamble[sizeof(radio_preamble)];
      int8_t temp1, temp2;
      uint8_t wind1, wind2;
      uint8_t desclen;
      char desc[32];
    };

    bool get_wttr_data() {
      struct wttr_packet packet;
      uint8_t len = sizeof(packet);
      int hasdata = radio.recv( (uint8_t*)&packet, &len);
      if(hasdata && len == sizeof(packet)) {
        if(memcmp( packet.preamble, radio_preamble, sizeof(radio_preamble))) return false
        temp1 = packet.temp1;
        temp2 = packet.temp2;
        wind1 = packet.wind1;
        wind2 = packet.wind2;
        memcpy( desc, packet.desc, packet.desclen);
        desc[packet.desclen] = '\0';
        return true;
      }
      return false;
    }

    bool hasnewdata = false;

    void loop() {
      if(get_wttr_data()) hasnewdata = true;
      if(scrollText() && hasnewdata) {
        if(temp1 == temp2 && wind1 == wind2) sprintf( sc_text, "%s     %d �     %d km/h      ", desc, temp1, 0xF7, wind1); // 0xF7 == '°'
        else if(temp1 != temp2) sprintf( sc_text, "%s     %d/%d �     %d km/h      ", desc, temp1, temp2, 0xF7, wind1); // 0xF7 == '°'
        else if(wind1 != wind2) sprintf( sc_text, "%s     %d �     %d/%d km/h      ", desc, temp1, 0xF7, wind1, wind2); // 0xF7 == '°'
        else sprintf( sc_text, "%s     %d/%d �     %d/%d km/h      ", desc, temp1, temp2, 0xF7, wind1, wind2); // 0xF7 == '°'
        hasnewdata = false;
      }
    }

**UPDATE-3:** Turns out this wasn't a power issue after all. I had forgotten about a voltage divider I put on the board for using it as a transmitter! The radio module has 3.3V TTL so this is needed for the transmitter but NOT the receiver!

Why this made it work plugged in to USB and not any other power brick I have no idea.

body:
Turns out I forgot I had put a voltage divider on the data-line from the receiver since I originally build the board for transmission.

This in turn, somehow, caused the signal from the radio receiver to fall short of the TTL signals when powered by anything other than USB.

I bypassed the divider and everything works as it should again :)


message:
string.indexOf() always returns a non-zero value

I am developing a hardware project which contains a facility to change the stored password by any user, if he/she knows the current password.The new password is stored in arduino eeprom. In the main screen, if the user enters the current password, door is unlocked from inside. . The issue faced here is that the point where current password is entered by user, it works fine, but **I want to check that '#' is not entered by user in the new password which is not performed properly.**

Because in the main screen, when user presses '#' key, change password function is called up, where user is asked to enter current password.

Here is the screenshot of the circuit prepared from fritzing.
[![enter image description here][1]][1]

The code snippet for entering new password is as under.

    lcd.clear();
    lcd.print("New Passkey:");
    lcd.setCursor(0, 1);
    while (j < 4)
    {
      char key = keypad4x4.getKey();

      if (key)
      {
        new_password[j++] = key;
        lcd.print(key);
        tone(buzzer, 1000, 50);

        if (j == 4)
        {
          lcd.print("4 reached");
          delay(1000);
          new_password[5] = '\0';
          String str = String(new_password);
          if (str.indexOf('#'))    /** this condition comes out to be true always i.e. always returns a non-zero value**/
          {
            tone(buzzer, 200, 700);
            lcd.clear();
            lcd.print("Invalid Entry");  /** It is printed everytime on lcd**/
            delay(2000);
            key = 0;
            changePass();
            break;
          }
          else  /** this block is not entered, so new password is not saved in EEPROM **/
          {
            for (int i = 0; i < 4; i++)
            {
              EEPROM.write(i, new_password[i]);
            }
            lcd.print(" Done......");
            delay(1000);
            break;
          }
        }
      }
    }

and

   `new_password[5]` is used to store new password entered by user.

Now, I am using a string variable to store this new password.

I am using  `string.indexof()` function to identify whether this new password contains a '#' character anywhere in it.But it seems that when I put this in an if block in code, it becomes true everytime.I have added comments at respective positions to highlight the problem faced by me. I have tested this code in Proteus simulator, and actual project too.

So, my issue is this one, **even if correct password is entered by user,without '#', then also, string.indexOf('#') condition becomes true(returns a non-zero value everytime) and thus even valid password is not saved in EEPROM**.
I guess I was able to explain my query accurately, please go through the code, and tell me where I am wrong, because I have gone through it many times and could not find the exact issue. Thanks in advance

  [1]: https://i.stack.imgur.com/LYwEI.jpg

body:
The problem here is that `indexOf` returns the position of the character in the string, or *-1 if it's not found*.

In C `0` is `false` and *everything else is true*. That includes `-1`.

However, your usage if String here to just check for one character is incredibly wasteful and should be avoided. Instead, use `strchr`:

    if (strchr(new_password, '#') != NULL) {
        ... contains # ...
    }


message:
i586-poky-linux-g++: no such file or directory Error compiling for board Intel® Edison

I'm facing this compilation issue.

Arduino: 1.8.4 (Linux), Board: "Intel® Edison"

`fork/exec /home/jimish/.arduino15/packages/Intel/tools/core2-32-poky-linux/1.6.2+1.0/i686/sysroots/pokysdk/usr/bin/i586-poky-linux/i586-poky-linux-g++: no such file or directory
Error compiling for board Intel® Edison.`

**Arduino IDE:**
[![Arduino IDE][1]][1]

<hr>
**Web IDE:**
[![Web IDE][2]][2]

  [1]: https://i.stack.imgur.com/zEyBo.png
  [2]: https://i.stack.imgur.com/eJbsn.png

body:
The problem here is that Intel, in their infinite wisdom* have lots of hard-coded paths to libraries in the binaries (why, heaven only knows) and then a set of scripts that munge those binaries to sort out where the libraries really are.

That script uses an option to `find` that was deprecated 13 years ago.

Way to keep up with the times, Intel...

So you need to make some fixes to get the toolchain to install properly.

I have created "fix" scripts for both the Edison and the Galileo that you can use to replace your broken toolchain.

* https://github.com/majenkotech/IntelFixes

----
*i.e., sheer incompetence


message:
Arduino RFID tag scanning problems

For a school project, I'm using an Arduino Uno and a Parallax RFID together with some other components, I used a script I got from Instructables for reading my serial input from the RFID (link: `http://www.instructables.com/id/Wiring-and-programming-the-Parallax-RFID-Serial-Ca/`)
To use this serial data, you need to include an if loop in your loop function to check if the scanned tag equals the previous one. If it doesn't, the tag gets used further in the program. This doesn't allow scanning the same tag twice in a row. But I need that for my project. I have tried to work around it, but I can't seem to get it working, I always create a loop of unlimited scans or some other inregularities. Here's my code:

    /* Libraries that need to be manually installed:
    Blynk libraries: https://github.com/blynkkk/blynk-library/releases/download/v0.5.1/Blynk_Release_v0.5.1.zip
    LiquidCrystal_I2C library: https://cdn.instructables.com/ORIG/FVH/K8OQ/J8UH0B9U/FVHK8OQJ8UH0B9U.zip
     */
    #define BLYNK_PRINT Serial
    #include <SoftwareSerial.h>
    #include <BlynkSimpleShieldEsp8266.h>
    #include <ESP8266_Lib.h>
    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    #include <Servo.h>
    //#include <ThingSpeak.h>

    //Setting up the Blynk wifi connection
    #define ESP8266_BAUD 9600
    char auth[] = "auth";

    //Setting up the virtual pins
    WidgetTerminal terminal(V1);
    BLYNK_WRITE(V1){}
    int freeSpots = 5;
    BLYNK_READ(V2)
    {
      Blynk.virtualWrite(V2, freeSpots);
    }

    //Setting up the RFID
    #define RFIDEnablePin 8
    #define RFIDSerialRate 2400
    String RFIDTAG=""; //Holds the RFID Code read from a tag
    String DisplayTAG = ""; //Holds the last displayed RFID Tag

    //Setting up the LCD
    LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

    //Setting up the serial connection
    SoftwareSerial EspSerial(2, 3);
    ESP8266 wifi(&EspSerial);

    //Setting up the servo
    Servo slagboom;

    //Tag database
    char tags[7][5] = {"6196", "6753", "5655", "69EC", "9FFC"};
    char owners[7][5] = {"per1", "per2", "per3", "per4", "per5"};
    int statuses[7] ={0};

    //unsigned long channelNumber = 461353;
    //const char * APIKey = "IHFFREPE9XUNSN94";

    void setup() {
      //Serial communication
      Serial.begin(RFIDSerialRate);
      EspSerial.begin(ESP8266_BAUD);
      //RFID pin setup
      pinMode(RFIDEnablePin,OUTPUT);
      digitalWrite(RFIDEnablePin, LOW);
      //Blynk startup
      Blynk.begin(auth, wifi, "ssid", "pass");
      //LCD startup
      lcd.begin(16,2);//16 kolommen, 2 rijen
      lcd.backlight();
      //Servo startup
      slagboom.attach(10);
      slagboom.write(35);

      //ThingSpeak.begin(client);

      //Blynk terminal printing test
      delay(1000);
      slagboom.detach();
      terminal.println(F("Terminal printing succesfull"));
      terminal.flush();

    }

    void loop() {
      if (Serial.available() > 0)
      {
        ReadSerial(RFIDTAG);
      }
      if (DisplayTAG != RFIDTAG)
      {
        DisplayTAG=RFIDTAG;
        tagCompare(RFIDTAG);
      }
    }

    //Function for comparing the tag to the database
    void tagCompare(String tagToCompare)
    {
      char lastTag[5];
      tagToCompare.toCharArray(lastTag, 5);
      int i = 0;
      while (i < 5)
        {
          if (strcmp(tags[i], lastTag) == 0)
            {
              terminal.print(owners[i]);
              if (statuses[i] == 0)
              {
                lcd.clear();
                lcd.setCursor(0,0);
                lcd.print("Welkom, ");
                lcd.setCursor(0,1);
                lcd.print(owners[i]);
                statuses[i] = 1;
                freeSpots--;
                digitalWrite(RFIDEnablePin, HIGH);
                slagboom.attach(10);
                slagboom.write(145);
                delay(1000);
                digitalWrite(RFIDEnablePin, LOW);
                slagboom.write(35);
                delay(500);
                slagboom.detach();
                terminal.println(F(" heeft de parking betreden."));
                terminal.flush();
              }
              else
              {
                lcd.clear();
                lcd.setCursor(0,0);
                lcd.print("Tot ziens ");
                lcd.setCursor(0,1);
                lcd.print(owners[i]);
                statuses[i] = 0;
                freeSpots++;
                digitalWrite(RFIDEnablePin, HIGH);
                slagboom.attach(10);
                slagboom.write(145);
                delay(1000);
                digitalWrite(RFIDEnablePin, LOW);
                slagboom.write(35);
                delay(500);
                slagboom.detach();
                terminal.println(F(" heeft de parking verlaten."));
                terminal.flush();
              }
              //ThingSpeak.writeField(channelNumber, 1, i, APIKey);
              Blynk.run();
            }
          i++;
          }
      i = 0;
    }

    //Function for reading the tag
    void ReadSerial(String &ReadTagString)
    {
      int bytesread = 0;
      int val = 0;
      char code[10];
      String TagCode="";

      if(Serial.available() > 0)
      {
        if((val = Serial.read()) == 10)
        {
          bytesread = 0;
          while(bytesread<10) // Reads the tag code
          {
            if( Serial.available() > 0)
            {
              val = Serial.read();
              if((val == 10)||(val == 13)) // If header or stop bytes before the 10 digit reading
              {
                break; // Stop reading
              }
              code[bytesread] = val; // Add the digit
              bytesread++; // Ready to read next digit
            }
          }
          if(bytesread == 10)  // If 10 digit read is complete
          {
            for(int x=6;x<10;x++) //Copy the Chars to a String
            {
              TagCode += code[x];
            }
            ReadTagString = TagCode; //Returns the tag ID
            while(Serial.available() > 0) //Burn off any characters still in the buffer
            {
            Serial.read();
            }

          }
          bytesread = 0;
          TagCode="";
        }
      }
    }
Any help would be very much appreciated.
Thanks in advance.

Edit: here's the changes I made to the loop():

    void loop() {
      if (Serial.available() > 0)
      {
        ReadSerial(RFIDTAG);
      }
      unsigned long millisScanned;
      if (DisplayTAG != RFIDTAG)
      {
        DisplayTAG=RFIDTAG;
        tagCompare(RFIDTAG);
        millisScanned = millis();
      }
      unsigned long millisReference = millisScanned + 10000;
      if ((DisplayTAG == RFIDTAG) && (millis() >= millisReference))
      {
        tagCompare(RFIDTAG);
        millisScanned = millis();
      }
    }

body:
If you wish to allow even for duplicate scans, but only want to check it if the RFID reader returns a new scan string, then you don't even need `millis()`

    void loop() {
      static bool pendingTag = false;
      if (Serial.available() > 0)
      {
        ReadSerial(RFIDTAG);
        pendingTag = true;   // Indicate that this is a new scan to check
      }
      if (pendingTag)
      {
        tagCompare(RFIDTAG);
        pendingTag = false;  // The tag is checked, no need to check again
        DisplayTAG=RFIDTAG;  // Not even sure if you use this anywhere else.
      }
    }


message:
Only one of 4 LEDs are lighting up

Before you ask - I've checked that the LEDs worked before putting them in my circuit. They all work.

I've connected 4 LEDs, shown in the arrangement below, up to my Adruino Lilypad. Pin 9 was used as the + 5V, the "- pin" was used as ground. In the schematic below, the "1" represents pin 9.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/W8qNq.png)

<!-- End schematic -->

[![enter image description here][1]][1]

When I start my sketch, I set pin 9 to high to check that all the LEDs are working. (this is a PWM pin so I write, `analogWrite(9, 255);`). At this point, only D5 lights up. If I connect up the two wires connecting R9-D6 and R10-D7, then both D5 and D8 light up... but never D7 or D6?

Doing some basic circuit calcs, the total resistance of the circuit is 100 Ohms (1 / (1 / (100 + 100)) + (1 / (100 + 100))). I'm powering from the usb connection to the computer so power source should be 5 V. Total current draw should therefore be 50 mA? Is that too much? If so, why does only D5 - or D5 and D8 when adjusting the circuit - light up?

  [1]: https://i.stack.imgur.com/MLyli.jpg

body: Those LEDs are 3.3V forward voltage. With two in series you need at least 6.6V to light them up.


message:
Arduino memory issue with old HP HDSP-2000 display chips

[![HDSP-2000 / HDSP-2011][1]][1]

  [1]: https://i.stack.imgur.com/ZdbWg.jpg

I'm running into memory issues with an Arduino Nano driving some old HDSP-2000/HDSP-2011 chips.

I cannot seem to get the ASCII 5x7 array into `PROGMEM` and have it read properly. It's so low on memory that I set up a second Arduino to send `char[]` strings through I2C to keep the Nano from locking up. This sort of worked to my advantage that I can multi-task and I'll probably keep it that way but it still keeps locking up or spitting gibberish.

The display Arduino is constantly bit-banging the displays - multiplexed with two 14-bit (acts as one 28-bit) Serial in / parallel out shift registers and and 5 column drivers. All displays use 5 common anode + columns, which have to be pulse timed with the registers.

<!-- language-all: lang-C++ -->

    #include <Wire.h>

    //*** HDSP2011 Display Demo
    //*** ASCII-DEMO
    //*** phuinink@gmail.com
    //*** Paul Huinink has a webpage on displays www.huinink.info and specifically HDSP200X series displays www.spagmon.com
    //*** Modified December-2013 by Patrick Hickey: added HP HDSP single digit display and RGB LED
    //*** Patrick Hickey ph@nipht.com

    //modified 3/2018 by Brandon McRee - removed support for LED and single digit HDSP DISPLAY

    //figure out latch pin

    // an array of 5 bytes per ASCII
    // 5 bytes cause 5 columns
    // 7 bits per column (no LSB)

    const byte ascii_5x7[] = {    //when I put this in PROGMEM i get gibberish, without it the SRAM is 87% full...
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0xF2, 0x00, 0x00,// !
        0x00, 0xE0, 0x00, 0xE0, 0x00,// "
        0x28, 0xFE, 0x28, 0xFE, 0x28,// #
        0x24, 0x54, 0xFE, 0x54, 0x48,// $
        0xC4, 0xC8, 0x10, 0x26, 0x46,// %
        0x6C, 0x92, 0xAA, 0x44, 0x0A,// &
        0x00, 0xA0, 0xC0, 0x00, 0x00,// 39
        0x00, 0x38, 0x44, 0x82, 0x00,// 40
        0x00, 0x82, 0x44, 0x38, 0x00,// 41
        0x28, 0x10, 0x7C, 0x10, 0x28,// *
        0x10, 0x10, 0x7C, 0x10, 0x10,
        0x00, 0x0A, 0x0C, 0x00, 0x00,
        0x10, 0x10, 0x10, 0x10, 0x10,
        0x00, 0x06, 0x06, 0x00, 0x00,
        0x04, 0x08, 0x10, 0x20, 0x40,
        0x7C, 0x8A, 0x92, 0xA2, 0x7C,//48 0
        0x00, 0x42, 0xFE, 0x02, 0x00,//49 1
        0x42, 0x86, 0x8A, 0x92, 0x62,//50 2
        0x84, 0x82, 0xA2, 0xD2, 0x8C,
        0x18, 0x28, 0x48, 0xFE, 0x08,
        0xE4, 0xA2, 0xA2, 0xA2, 0x9C,
        0x3C, 0x52, 0x92, 0x92, 0x0C,
        0x80, 0x8E, 0x90, 0xA0, 0xC0,
        0x6C, 0x92, 0x92, 0x92, 0x6C,
        0x60, 0x92, 0x92, 0x94, 0x78,
        0x00, 0x6C, 0x6C, 0x00, 0x00,
        0x00, 0x6A, 0x6C, 0x00, 0x00,
        0x10, 0x28, 0x44, 0x82, 0x00,
        0x28, 0x28, 0x28, 0x28, 0x28,
        0x00, 0x82, 0x44, 0x28, 0x10,
        0x40, 0x80, 0x8A, 0x90, 0x60,
        0x4C, 0x92, 0x9E, 0x82, 0x7C,
        0x7E, 0x88, 0x88, 0x88, 0x7E,//65 A
        0xFE, 0x92, 0x92, 0x92, 0x6C,
        0x7C, 0x82, 0x82, 0x82, 0x44,
        0xFE, 0x82, 0x82, 0x44, 0x38,
        0xFE, 0x92, 0x92, 0x92, 0x82,
        0xFE, 0x90, 0x90, 0x90, 0x80,// 70
        0x7C, 0x82, 0x92, 0x92, 0x5E,
        0xFE, 0x10, 0x10, 0x10, 0xFE,
        0x00, 0x82, 0xFE, 0x82, 0x00,
        0x04, 0x02, 0x82, 0xFC, 0x80,
        0xFE, 0x10, 0x28, 0x44, 0x82,
        0xFE, 0x02, 0x02, 0x02, 0x02,
        0xFE, 0x40, 0x30, 0x40, 0xFE,
        0xFE, 0x20, 0x10, 0x08, 0xFE,
        0x7C, 0x82, 0x82, 0x82, 0x7C,
        0xFE, 0x90, 0x90, 0x90, 0x60,// P
        0x7C, 0x82, 0x8A, 0x84, 0x7A,
        0xFE, 0x90, 0x98, 0x94, 0x62,
        0x62, 0x92, 0x92, 0x92, 0x8C,
        0x80, 0x80, 0xFE, 0x80, 0x80,
        0xFC, 0x02, 0x02, 0x02, 0xFC,
        0xF8, 0x04, 0x02, 0x04, 0xF8,
        0xFC, 0x02, 0x0C, 0x02, 0xFC,
        0xC6, 0x28, 0x10, 0x28, 0xC6,
        0xE0, 0x10, 0x0E, 0x10, 0xE0,
        0x86, 0x8A, 0x92, 0xA2, 0xC2,
        0x00, 0xFE, 0x82, 0x82, 0x00,
        0x40, 0x20, 0x10, 0x08, 0x04,
        0x00, 0x82, 0x82, 0xFE, 0x00,
        0x20, 0x40, 0x80, 0x40, 0x20,
        0x02, 0x02, 0x02, 0x02, 0x02,
        0x00, 0x80, 0x40, 0x20, 0x00,
        0x04, 0x2A, 0x2A, 0x2A, 0x1E,
        0xFE, 0x12, 0x12, 0x12, 0x0C,
        0x1C, 0x22, 0x22, 0x22, 0x22,
        0x0C, 0x12, 0x12, 0x12, 0xFE,// 100 d
        0x1C, 0x2A, 0x2A, 0x2A, 0x1A,// 101 e
        0x00, 0x10, 0x7E, 0x90, 0x40,
        0x12, 0x2A, 0x2A, 0x2A, 0x3C,
        0xFE, 0x10, 0x10, 0x10, 0x0E,
        0x00, 0x00, 0x5E, 0x00, 0x00,
        0x04, 0x02, 0x02, 0xBC, 0x00,
        0x00, 0xFE, 0x08, 0x14, 0x22,
        0x00, 0x82, 0xFE, 0x02, 0x00,
        0x3E, 0x20, 0x1C, 0x20, 0x3E,
        0x3E, 0x10, 0x20, 0x20, 0x1E,
        0x1C, 0x22, 0x22, 0x22, 0x1C,
        0x3E, 0x28, 0x28, 0x28, 0x10,
        0x10, 0x28, 0x28, 0x28, 0x3E,
        0x3E, 0x10, 0x20, 0x20, 0x10,
        0x12, 0x2A, 0x2A, 0x2A, 0x24,
        0x20, 0x20, 0xFC, 0x22, 0x24,
        0x3C, 0x02, 0x02, 0x02, 0x3C,
        0x38, 0x04, 0x02, 0x04, 0x38,
        0x3C, 0x02, 0x0C, 0x02, 0x3C,// x
        0x22, 0x14, 0x08, 0x14, 0x22,// y
        0x20, 0x12, 0x0C, 0x10, 0x20,// z
        0x22, 0x26, 0x2A, 0x32, 0x22,//123 {
        0x00, 0x10, 0x6C, 0x82, 0x82,//124 |
        0x00, 0x00, 0xEE, 0x00, 0x00,//125 }
        0x82, 0x82, 0x6C, 0x10, 0x00,
        0x20, 0x40, 0x40, 0x40, 0x80,
        0xA8, 0x68, 0x3E, 0x68, 0xA8,
        0xBE, 0x2A, 0x2A, 0x2A, 0xA2,
        0x00, 0x20, 0x50, 0xA0, 0x00,
        0x04, 0x22, 0x7C, 0xA0, 0x40,
        0x84, 0xFC, 0x04, 0x00, 0x20,
        0xFE, 0x02, 0x02, 0x12, 0x02,
        0x1C, 0x22, 0x14, 0x08, 0x36,
        0x4E, 0x3E, 0x60, 0x40, 0x40,
        0x0C, 0x12, 0x52, 0xB2, 0x1C,//136 ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Âª
        0x08, 0x1C, 0x2A, 0x2A, 0x2A,
        0xF8, 0x40, 0x40, 0x3C, 0x02,
        0x7C, 0x92, 0x92, 0x7C, 0x00,
        0x42, 0x44, 0x38, 0x04, 0x02,
        0x20, 0x3E, 0x20, 0x3E, 0x22,
        0x10, 0x20, 0x3C, 0x22, 0x20,
        0x18, 0x24, 0x7E, 0x24, 0x18,
        0x1C, 0x22, 0x0C, 0x22, 0x1C,
        0x82, 0xC6, 0xAA, 0x92, 0x82,
        0x3A, 0x46, 0x40, 0x46, 0x3A,
        0x54, 0x54, 0x54, 0x54, 0x54,
        0x44, 0x28, 0x10, 0x28, 0x44,
        0x10, 0x10, 0x54, 0x10, 0x10,
        0x00, 0x70, 0x88, 0x88, 0x70,
        0x60, 0x90, 0x8A, 0x80, 0x40,
        0xFE, 0xFE, 0x92, 0x92, 0x92,
        0x0A, 0x1A, 0x2A, 0x4A, 0x8A,
        0x8A, 0x4A, 0x2A, 0x1A, 0x0A,
        0x28, 0x2C, 0x38, 0x68, 0x28,
        0x04, 0xFE, 0x80, 0x80, 0x80,
        0x4C, 0x92, 0x92, 0x7C, 0x00,//157 ÃƒÆ’Ã†â€™Ãƒâ€¹Ã…â€œ
        0x04, 0x02, 0x7C, 0x80, 0x40,
        0x38, 0x44, 0x38, 0x44, 0x38,
        0xAA, 0x54, 0xAA, 0x54, 0xAA,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0xBE, 0x00, 0x00,
        0x38, 0x44, 0xFE, 0x44, 0x00,
        0x12, 0x7E, 0x92, 0x92, 0x42,
        0xBA, 0x44, 0x44, 0x44, 0xBA,
        0xA8, 0x68, 0x3E, 0x68, 0xA8,
        0x00, 0x00, 0xEE, 0x00, 0x00,
        0x50, 0xAA, 0xAA, 0xAA, 0x14,
        0x00, 0x80, 0x00, 0x80, 0x00,
        0x7C, 0xBA, 0xAA, 0xAA, 0x7C,
        0x12, 0xAA, 0xAA, 0xAA, 0x7A,
        0x10, 0x28, 0x54, 0xAA, 0x44,
        0x80, 0x80, 0x80, 0x80, 0xC0,
        0x00, 0x00, 0x00, 0x00, 0x00,
        0x7C, 0xAA, 0xBA, 0x82, 0x7C,
        0x80, 0x80, 0x80, 0x80, 0x80,
        0x00, 0xE0, 0xA0, 0xE0, 0x00,
        0x22, 0x22, 0xFA, 0x22, 0x22,
        0x00, 0x48, 0x98, 0xA8, 0x48,
        0x00, 0x00, 0xA8, 0xA8, 0x70,
        0x00, 0x00, 0x40, 0x80, 0x00,
        0x04, 0xF8, 0x10, 0x10, 0xE0,
        0x60, 0xFE, 0x80, 0xFE, 0x80,
        0x00, 0x00, 0x10, 0x10, 0x00,
        0x08, 0x00, 0x02, 0x04, 0x00,
        0x00, 0x48, 0xF8, 0x08, 0x00,
        0x00, 0xE8, 0xA8, 0xE8, 0x00,
        0x44, 0xAA, 0x54, 0x28, 0x10,
        0xF0, 0x04, 0x0C, 0x14, 0x2E,
        0xF0, 0x00, 0x12, 0x26, 0x1A,
        0xFE, 0xFE, 0xFE, 0xFE, 0xFE,
        0x0C, 0x12, 0xA2, 0x02, 0x04,
        0x1E, 0xA8, 0x68, 0x28, 0x1E,
        0x1E, 0x28, 0x68, 0xA8, 0x1E,
        0x1E, 0xA8, 0xA8, 0xA8, 0x1E,
        0x9E, 0xA8, 0xA8, 0xA8, 0x9E,
        0x9E, 0x28, 0x28, 0x28, 0x9E,
        0x1E, 0x68, 0xA8, 0x68, 0x1E,
        0x7E, 0x90, 0xFE, 0x92, 0x92,
        0x70, 0x8A, 0x8C, 0x88, 0x88,
        0x3E, 0xAA, 0x6A, 0x2A, 0x22,
        0x3E, 0x2A, 0x6A, 0xAA, 0x22,
        0x3E, 0xAA, 0xAA, 0xAA, 0x22,
        0xBE, 0x2A, 0x2A, 0x2A, 0xA2,
        0x00, 0xA2, 0x7E, 0x22, 0x00,
        0x00, 0x22, 0x7E, 0xA2, 0x00,
        0x00, 0xA2, 0xBE, 0xA2, 0x00,
        0x00, 0xA2, 0x3E, 0xA2, 0x00,
        0x10, 0xFE, 0x92, 0x82, 0x7C,
        0xBE, 0x90, 0x88, 0x84, 0xBE,
        0x1C, 0xA2, 0x62, 0x22, 0x1C,
        0x1C, 0x22, 0x62, 0xA2, 0x1C,
        0x1C, 0xA2, 0xA2, 0xA2, 0x1C,
        0x9C, 0xA2, 0xA2, 0xA2, 0x9C,
        0x9C, 0x22, 0x22, 0x22, 0x9C,
        0x44, 0x28, 0x10, 0x28, 0x44,
        0x3A, 0x4C, 0x54, 0x64, 0xB8,
        0x3C, 0x82, 0x42, 0x02, 0x3C,
        0x3C, 0x02, 0x42, 0x82, 0x3C,
        0x3C, 0x82, 0x82, 0x82, 0x3C,
        0xBC, 0x02, 0x02, 0x02, 0xBC,
        0x60, 0x10, 0x4E, 0x90, 0x60,
        0xFE, 0x44, 0x44, 0x44, 0x38,
        0x7E, 0xA4, 0xA4, 0x58, 0x00,
        0x04, 0xAA, 0x6A, 0x2A, 0x1E,
        0x04, 0x2A, 0x6A, 0xAA, 0x1E,
        0x04, 0xAA, 0xAA, 0xAA, 0x1E,
        0x84, 0xAA, 0xAA, 0xAA, 0x9E,
        0x04, 0xAA, 0x2A, 0xAA, 0x1E,
        0x04, 0x6A, 0xAA, 0x6A, 0x1E,
        0x2E, 0x2A, 0x1C, 0x2A, 0x3A,
        0x30, 0x4A, 0x4C, 0x48, 0x00,
        0x1C, 0xAA, 0x6A, 0x2A, 0x1A,
        0x1C, 0x2A, 0x6A, 0xAA, 0x1A,
        0x1C, 0xAA, 0xAA, 0xAA, 0x1A,
        0x1C, 0xAA, 0x2A, 0xAA, 0x1A,
        0x00, 0x80, 0x5E, 0x00, 0x00,
        0x00, 0x00, 0x5E, 0x80, 0x00,
        0x00, 0x40, 0x5E, 0x40, 0x00,
        0x00, 0x40, 0x1E, 0x40, 0x00,
        0x0C, 0x12, 0x52, 0xB2, 0x1C,
        0xBE, 0x90, 0xA0, 0xA0, 0x9E,
        0x0C, 0x92, 0x52, 0x12, 0x0C,
        0x0C, 0x12, 0x52, 0x92, 0x0C,
        0x0C, 0x52, 0x52, 0x52, 0x0C,
        0x4C, 0x52, 0x52, 0x52, 0x4C,
        0x0C, 0x52, 0x12, 0x52, 0x0C,
        0x10, 0x10, 0x10, 0x54, 0x10,
        0x18, 0x26, 0x3C, 0x64, 0x18,
        0x1C, 0x82, 0x42, 0x02, 0x1C,
        0x1C, 0x02, 0x42, 0x82, 0x1C,
        0x1C, 0x42, 0x42, 0x42, 0x1C,
        0x1C, 0x42, 0x02, 0x42, 0x1C,
        0x20, 0x12, 0x4C, 0x90, 0x20,
        0xFE, 0x48, 0x48, 0x30, 0x00,
        0x20, 0x92, 0x0C, 0x90, 0x20,

    };

    int column[] = {
        8,7,6,5,4}; // change this to other general input/output arduino-pins as you like d8=pin 1
    int data = 2;   // change this to other general input/output arduino-pins as you like
    int clock = 3;  // change this to other general input/output arduino-pins as you like

    int brightness = 2000; // keep high for max visibility. To high will cause flikkering

    const int numberOflDisplays = 4; // change this if total number of HDSP200x's is different.

    int tekstDat[numberOflDisplays * 4 * 5]; // this is the array that store's what on the displays. 4 digits per display and 5 columns per digit.

    unsigned long tijd; // used to trigger events in one of the examples below

    char buf[40];
    boolean flagRx = false; //allowed to receive if false

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

        for (int i = 0; i < 5; i++){
            pinMode(column[i], OUTPUT);
        }
        for (int i = 0; i < 5; i++){
            digitalWrite(column[i], LOW);
        }
        pinMode(data, OUTPUT);
        pinMode(clock, OUTPUT);
        digitalWrite(data, LOW);
        digitalWrite(clock, HIGH);
        tijd = millis();

        Wire.begin(8);                // join i2c bus with address #8  >>important<<
        Wire.onReceive(receiveEvent); // register event

    }

    //***********************************************************************************end setup******************************************************

    void loop(){

        char PROGMEM clr[] = "    ";
        char PROGMEM scroll[]  = "1979 TECH CONTROL PANEL by Brandon McRee";
        char PROGMEM scroll2[] = "Remember Stupid... you have to drive this home :)";

        if(flagRx == false){
            delay(10); //needs this delay to be stable
            scrollText(scroll, 8); //scrolling text, speed : second number is var howslow how slow this is a test of fastdraw text (short strings)
            delay(1000);
            //scrollText(scroll2, 10);
            delay(10);
            flagRx = true; // can now recieve
        }
        else{
            writeText(buf);
            for (int i = 0; i< 50; i++) draw(); //does this continuously - display HDSP2011

        }
        /*
                scrollText(scroll3, 10);
                delay(10);

            //short quick text write
            scrollText(hello, 8);
            scrollText(world, 8);
            delay(500);

                delay(5);
            writeText("TEST") ;                   //letters only? special charachters
            for (int i = 0; i< 100; i++) draw();
                    delay(5);
            writeText("ABCDEFGHIJKLMNOPQRSTUVWXYZ") ;
            for (int i = 0; i< 70; i++) draw();
                    delay(5);
            writeText("1234567890") ;
            for (int i = 0; i< 100; i++) draw();
                    delay(5);
            writeText("!@#$%^&*()") ;
            for (int i = 0; i< 50; i++) draw(); //delay??
                    delay(5);

            delay(1000);

                */

        writeText(buf);
        for (int i = 0; i< 50; i++) draw(); //does this continuously

    }
    //****************end of main loop *********************************

    void receiveEvent(int howMany) {

        int i;
        for (i=0; i<howMany; i++){
            buf[i] = Wire.read(); //read I2C data (address 8)
        }

        flagRx = true;    // set flag, we received something. will figure out how to clear when

        // while (1 < Wire.available()) { // loop through all but the last

    }

    //int x = Wire.read();    // receive byte as an integer not used
    //Serial.println(x);          // print the integer

    void writeDigit(int positie, int ascii){
        for (int i =0; i< 5;i++){
            tekstDat[(numberOflDisplays * 4 - positie) * 5 + i] = ascii_5x7[ascii*5+i];
        }
    }

    void scrollText(String tekkst, long howSlow){
        int leng = tekkst.length();
        for (int u=-numberOflDisplays*4;u<leng;u++){ // first N digits will be spaces. N = all digits of display. So one screen blank before first character apears.
            for (int v=0; v< numberOflDisplays*4;v++){
                if (( (u+v) >= 0 ) && ((u+v) < leng)){ // separete leading and tailing spaces from actual string
                    char oneChar= tekkst.charAt(u+v);
                    writeDigit(v+1, oneChar); // write the character of the string
                }
                else{
                    writeDigit(v+1, 32); // write ascii-value 32 = a space.
                }
            }
            for (long teller = 0; teller < howSlow; teller++){
                draw();
            }
        }
    }

    void writeText(String tekst){
        int tl = tekst.length();
        int spacesNeeded = 4 * numberOflDisplays - tl;
        if (spacesNeeded <0){
            tl = 4 * numberOflDisplays;
        }
        else{
            for (int u = 0; u < spacesNeeded; u++){
                tekst.concat(" ");
            }
            tl = 4 * numberOflDisplays;
        }
        char tekst_[tl];
        for (int vv = 0; vv < tl; vv++){
            char tt = tekst.charAt(tl-vv-1);
            for (int i =0; i< 5;i++){
                //tekstDat[vv*5+i] = ascii_5x7[tt*5+i]; //old using SRAM
                //tekstDat[vv*5+i] = (pgm_read_byte(ascii_5x7))[tt*5+i]; //new  try and read from PROGMEM does not compile :/
            }
        }
    }

    void dot(byte x, byte y, boolean oo){
        if ((x < (numberOflDisplays *4 * 5)) && (y < 7)){
            byte oldByte = tekstDat[x] & (0xFF - (2<<y));
            tekstDat[x] = oldByte | (2<<y);
        }
    }

    void draw(){
        for (int Kolom = 0; Kolom < 5; Kolom++){ // 5 columns to be strobed
            // pumping in 3 x 4 x 7 bits per one stobe of the column
            for (int displayNo = 0; displayNo < numberOflDisplays; displayNo++){  // number of  displays
                for (int digitNo = 0; digitNo < 4; digitNo++){ // 4 characters per display
                    for (int diodeNo = 0; diodeNo < 7; diodeNo++){ // 7 row-elements
                        digitalWrite(clock, HIGH);
                        digitalWrite(data, tekstDat[Kolom + 5*(displayNo*4 + digitNo) ] &(2<<diodeNo)); // magic
                        digitalWrite(clock, LOW);
                    }
                }
            }
            digitalWrite(column[Kolom], HIGH);
            delayMicroseconds(brightness);
            digitalWrite(column[Kolom], LOW);
        }
    }

body:
Take a look at an ASCII table such as the [one here][1].

You could remove the first 32 ASCII characters which are the control characters and don't show up on the display. That would save 160 bytes. You will just need to make sure your index lines up.

You can then remove the last 127 characters which make up the extended character set. These are rarely used in the English language. This would save you an additional 635 bytes.

Overall that would save you 795 precious bytes.

  [1]: http://www.theasciicode.com.ar/


body:
Ran into the same issue. Added the following line to setup():

```
// The following line is magic needed for pgm_read_byte() to function.
if (millis() > 100000L) Serial.println((uint16_t) font, HEX);
```

Note the Serial.println() is never executed, but the compiler doesn't know that.
Without this line pgm_read_byte() produces garbage.
With this line added to setup() the code runs fine.

Disassembling the code it looks as if without the Serial.println((uint16_t) font) the compiler optimizes away the begin address of the array, dropping "font" from the symbol table.

Complete sketch at https://github.com/koendv/retroleds


message:
Upcoming Project

Hey guys I have a project that will require 20 I/O pins with serial communication from a computer to control each of the pins. I would like something as small as possible would a arduino micro or uno work for this project or will i need to go bigger like a mega. I have looked at all the pinouts but am confused to know of which pins I can use as digital I/O or not.
Thanks

body: If you require 20 I/O pins then use Arduino Mega. If it’s too big then use Nano, Micro or Pro Mini (you need a serial thingy to program the Mini) with I/O expanders like PCF8574P with I2C communication or MCP23S17 with SPI communication.


body:
There are a couple of options

 1. Easiest = Use an Arduino with a greater number of pins (e.g. MEGA2560)
 2. Easy = Use an add-on board (e.g. Teensy)
 3. Harder = Use shift registers (see https://arduino.stackexchange.com/questions/117/is-there-a-way-to-have-more-than-14-output-pins-on-arduino)

Further discussion on these options [here][1].

  [1]: http://forum.arduino.cc/index.php?topic=505084.0


message:
Is it possible to use extra AVR Flash memory as non-volatile EEPROM-like Flash memory storage?

In STM32 microcontrollers it is possible to use a technique that ST calls **IAP**, or **[In-Application Programming][1]**, in order to write to the Flash memory from your running application. They even have a nice Application Note (ex: [AN2594][2]) to describe a really ingenious way to use two Flash memory pages to emulate EEPROM while using "wear-leveling" to reduce Flash memory wear during erase cycles.

I have wondered for years: can AVR do this? Ex: the ATmega328 mcu in the Arduino Uno, Nano, etc--**can you write code to store data from your application into Flash memory, thereby increasing non-volatile storage space for data acquisition for instance?**

If so, can you please point me to some resources or examples, including example code, reference manuals or datasheets, etc, that might help me implement this? I've done some looking in the datasheet and haven't found anything so far but maybe I'm just not looking hard enough or know well enough what I'm looking for.

  [1]: http://www.st.com/content/ccc/resource/technical/document/programming_manual/10/98/e8/d4/2b/51/4b/f5/CD00283419.pdf/files/CD00283419.pdf/jcr:content/translations/en.CD00283419.pdf
  [2]: http://www.st.com/content/ccc/resource/technical/document/application_note/ee/ef/d7/87/cb/b7/48/52/CD00165693.pdf/files/CD00165693.pdf/jcr:content/translations/en.CD00165693.pdf

body:
Take a look at section 30.8 in the datasheet:
http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf

It has all the information to reprogram the bootloader section of the flash during runtime.

The bootloader partition size can be adjusted as well.


body:
Yes you can. This Arduino IDE add on lets you make calls to code store in the bootload of memory so you can make changes to the flash memory.
<https://majek.sh/en/writing-to-internal-flash-on-arduino/>

The number of times you rewrite a cell are limited.
I'd suggest you are better off with adding a FRAM memory chip.
Get a 5V part with SPI interface. Fast reads, virtually unlimitless writes (trillions)
<https://www.digikey.com/products/en/integrated-circuits-ics/memory/774?k=fram+memory&k=&pkeyword=fram+memory&pv276=15&FV=ffe00306,1f140000,1fec000b&quantity=0&ColumnSort=0&page=1&stock=1&pageSize=25>


body:
The answer is **"yes, you *can* use extra AVR Flash memory as non-volatile EEPROM-like Flash memory storage, very similar to an STM32 microcontroller."**

One of these days I'm going to write an Arduino library to make this really easy for the beginner. For now, however, I'm going to simply post links to valuable references that contain the full answers and that I still need to thoroughly study myself.

## Documentation on how to implement Flash memory reading/writing:
-This is frequently called "self programming" by Atmel (now owned by Microchip).

To find these resources I went to the [main ATmega328 reference page][1] then clicked the "Documentation" link, then I searched the web page for the word "flash".

Here's what I found (in order of importance--most pertinent references first):

1. [AVR106: C functions for reading and writing to Flash memory on tinyAVR and megaAVR devices][2]
 1. "Description: This application note provides C functions for accessing the Flash memory using the Self programming Program memory which allows to reprogram the Flash memory during program run."
 2. "Introduction: The Atmel® AVR® devices have a feature called Self programming Program memory. This feature enables an AVR device to reprogram the Flash memory while executing the program. Such a feature is helpful for applications that must self-update firmware or store parameters in Flash. This application note provides the details about the C functions for accessing the Flash memory."
 3. This Application Note contains source code, including with the following ready-to-use C functions:
  - `ReadFlashByte()`
  - `ReadFlashPage()`
  - `WriteFlashByte()`
  - `WriteFlashPage()`
  - `RecoverFlash()`
2. [AVR105: Power efficient high endurance parameter storage in tinyAVR and megaAVR devices Flash memory][3]
3. [AVR116: Wear Leveling on DataFlash][4]
4. [Atmega328 datasheet][5]
 - Section 30: Boot Loader Support – Read-While-Write Self-programming (BTLDR), p. 328-344.
 - As pointed out by user [SDF in his answer][6], especially pay attention to Section 30.8: Self-Programming the Flash, p. 334-342.
 - Also see Section 12.2: In-System Reprogrammable Flash Program Memory, p36
 - And Section 31.6: Page Size, p. 349.

  [1]: https://www.microchip.com/wwwproducts/en/ATmega328
  [2]: http://www.microchip.com//wwwAppNotes/AppNotes.aspx?appnote=en591795
  [3]: http://www.microchip.com//wwwAppNotes/AppNotes.aspx?appnote=en591475
  [4]: http://www.microchip.com//wwwAppNotes/AppNotes.aspx?appnote=en591954
  [5]: http://ww1.microchip.com/downloads/en/DeviceDoc/ATmega328_P AVR MCU with picoPower Technology Data Sheet 40001984A.pdf
  [6]: https://arduino.stackexchange.com/a/51278/7727


message:
How to keep warm arduino uno board with 12v dc supply

I have an arduino uno board with ESP8266 module and i have done all connection using breadboard.

Now when i run arduino uno with USB cable for long time then its not getting hot ! but when i supply power with 12v dc adapter in black barrele then its getting too much hot (i cant touch with my fingure).

Now when i remove the ESP8266 module power and test it again with 12v dc power supply then its not getting hot !

So what is the problem with ESP8266 module ? Is my wiring creates heat ?

body:
See https://arduino.stackexchange.com/questions/23815/can-i-use-arduinos-3-3-v-output-directly-to-esp8266/23819

From that page:

> The specs for the Uno say that it does not provide as much current on the 3.3V line as the specs for the ESP8266 requires. You will need to provide another regulator that can supply enough current.

Also, putting 12V into the barrel jack is making work for the on-board voltage regulator (located near the barrel jack) because it has to convert 12V to 5V (making heat in the process). You would be better off putting a lower voltage into the barrel jack, ideally around 7V (but not lower).

Alternatively, just power through the USB port as you have been, and plug the USB cable into a USB charger.

---

To summarize, both the 5V and 3.3V voltage regulators are probably working very hard, thus getting hot.


message:
Unable to get Arduino Ethernet Shield IP address connected to Raspberry

My Arduino Uno with Ethernet Shield is connected to a Raspberry (rasp1) and the Ethernet Shield is connected to another Raspberry (rasp2) by Ethernet cable; rasp2 has a private IP address (192.168.10.0). I want to find out the Arduino IP address.

I used the example sketch  DHCPAddressPrinter but when running it the Serial Monitor remains empty (as Mac Address I used the address located underneath the shield).

Code Used:

<!-- language-all: lang-C++ -->

    #include <SPI.h>
    #include <Ethernet.h>

    // Enter a MAC address for your controller below.
    // Newer Ethernet shields have a MAC address printed on a sticker on the shield
    byte mac[] = {
        0x90, 0xA2, 0xDA, 0x11, 0x32, 0x49
    };

    // Initialize the Ethernet client library
    // with the IP address and port of the server
    // that you want to connect to (port 80 is default for HTTP):
    EthernetClient client;

    void setup() {
        // Open serial communications and wait for port to open:
        Serial.begin(9600);
        // this check is only needed on the Leonardo:
        while (!Serial) {
            ; // wait for serial port to connect. Needed for Leonardo only
        }

        // start the Ethernet connection:
        if (Ethernet.begin(mac) == 0) {
            Serial.println("Failed to configure Ethernet using DHCP");
            // no point in carrying on, so do nothing forevermore:
            for (;;)
            ;
        }
        // print your local IP address:
        Serial.print("My IP address: ");
        for (byte thisByte = 0; thisByte < 4; thisByte++) {
            // print the value of each byte of the IP address:
            Serial.print(Ethernet.localIP()[thisByte], DEC);
            Serial.print(".");
        }
        Serial.println();
    }

    void loop() {

body:
`192.168.10.0` is not a valid IP address (unless it's on a /32 subnet which makes no sense on ethernet).

You need to allocate a proper IP address within a proper subnet, such as `192.168.10.1/24` (i.e., IP `192.168.10.1` and netmask `255.255.255.0`), and either manually provide a similar IP address to the Arduino (such as `192.168.10.2/24` [IP `192.168.10.2` netmask `255.255.255.0`]), or install and configure a DHCP server on the Raspberry to hand out IP addresses within that subnet range (e.g., `192.168.10.100/24` to `192.168.10.200/24`) for the Arduino to then be able to use DHCP mode.

Most of that is outside the scope of an Arduino SE site, though.


message:
Non-blocking analogRead

In my recent project, I'm working with the motor. I have to drive the motor for the specific time like for 2 minutes, 3 minutes, 4 minutes and 5 minutes. I already created functions for that. And motor drive based on readings taken from the sensor.

My code is below:

    #define PIN_OUTPUT 6

    const int kPinIN1 = 4;
    const int kPinIN2 = 5;

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

      pinMode(kPinIN1, OUTPUT);
      pinMode(kPinIN2, OUTPUT);
    }

    void loop()
    {
      Serial.println(analogRead(A0));

      if(analogRead(A0) > 100 && analogRead(A0) < 200)
      {
        motorDriveFor2Min();
      }
      else if(analogRead(A0) > 200 && analogRead(A0) < 300)
      {
        motorDriveFor3Min();
      }
      else if(analogRead(A0) > 300 && analogRead(A0) < 400)
      {
        motorDriveFor4Min();
      }
      else if(analogRead(A0) > 400 && analogRead(A0) < 500)
      {
        motorDriveFor5Min();
      }
    }

    void motorDriveFor2Min()
    {
      digitalWrite(kPinIN1, HIGH);
      digitalWrite(kPinIN2, LOW);

      analogWrite(PIN_OUTPUT, 255);

      verboseDelay(7000);

      digitalWrite(kPinIN1, LOW);
      digitalWrite(kPinIN2, HIGH);

      analogWrite(PIN_OUTPUT, 255);

      verboseDelay(7000);

      digitalWrite(kPinIN1, HIGH);
      digitalWrite(kPinIN2, LOW);

      analogWrite(PIN_OUTPUT, 255);

      verboseDelay(7000);

      digitalWrite(kPinIN1, LOW);
      digitalWrite(kPinIN2, HIGH);

      analogWrite(PIN_OUTPUT, 255);

      verboseDelay(7000);

      digitalWrite(kPinIN1, HIGH);
      digitalWrite(kPinIN2, LOW);

      analogWrite(PIN_OUTPUT, 255);

      verboseDelay(7000);

      digitalWrite(kPinIN1, LOW);
      digitalWrite(kPinIN2, HIGH);

      analogWrite(PIN_OUTPUT, 255);

      verboseDelay(7000);

      digitalWrite(kPinIN1, HIGH);
      digitalWrite(kPinIN2, LOW);

      analogWrite(PIN_OUTPUT, 255);

      verboseDelay(7000);

      digitalWrite(kPinIN1, LOW);
      digitalWrite(kPinIN2, HIGH);

      analogWrite(PIN_OUTPUT, 255);

      verboseDelay(7000);

      digitalWrite(kPinIN1, HIGH);
      digitalWrite(kPinIN2, LOW);

      analogWrite(PIN_OUTPUT, 255);

      verboseDelay(64000);
    }

    void motorDriveFor3Min()
    {
      motorDriveFor2Min();

      digitalWrite(kPinIN1, HIGH);
      digitalWrite(kPinIN2, LOW);

      analogWrite(PIN_OUTPUT, 255);

      verboseDelay(7000);

      digitalWrite(kPinIN1, LOW);
      digitalWrite(kPinIN2, HIGH);

      analogWrite(PIN_OUTPUT, 255);

      verboseDelay(7000);

      digitalWrite(kPinIN1, HIGH);
      digitalWrite(kPinIN2, LOW);

      analogWrite(PIN_OUTPUT, 255);

      verboseDelay(7000);

      digitalWrite(kPinIN1, LOW);
      digitalWrite(kPinIN2, HIGH);

      analogWrite(PIN_OUTPUT, 255);

      verboseDelay(7000);

      digitalWrite(kPinIN1, HIGH);
      digitalWrite(kPinIN2, LOW);

      analogWrite(PIN_OUTPUT, 255);

      verboseDelay(32000);
    }

    void motorDriveFor4Min()
    {
      motorDriveFor3Min();

      digitalWrite(kPinIN1, HIGH);
      digitalWrite(kPinIN2, LOW);

      analogWrite(PIN_OUTPUT, 255);

      verboseDelay(7000);

      digitalWrite(kPinIN1, LOW);
      digitalWrite(kPinIN2, HIGH);

      analogWrite(PIN_OUTPUT, 255);

      verboseDelay(7000);

      digitalWrite(kPinIN1, HIGH);
      digitalWrite(kPinIN2, LOW);

      analogWrite(PIN_OUTPUT, 255);

      verboseDelay(46000);
    }

    void motorDriveFor5Min()
    {
      digitalWrite(kPinIN1, HIGH);
      digitalWrite(kPinIN2, LOW);

      analogWrite(PIN_OUTPUT, 255);

      verboseDelay(120000);

      digitalWrite(kPinIN1, HIGH);
      digitalWrite(kPinIN2, LOW);

      analogWrite(PIN_OUTPUT, 255);

      verboseDelay(7000);

      digitalWrite(kPinIN1, LOW);
      digitalWrite(kPinIN2, HIGH);

      analogWrite(PIN_OUTPUT, 255);

      verboseDelay(7000);

      digitalWrite(kPinIN1, HIGH);
      digitalWrite(kPinIN2, LOW);

      analogWrite(PIN_OUTPUT, 255);

      verboseDelay(7000);

      digitalWrite(kPinIN1, LOW);
      digitalWrite(kPinIN2, HIGH);

      analogWrite(PIN_OUTPUT, 255);

      verboseDelay(7000);

      digitalWrite(kPinIN1, HIGH);
      digitalWrite(kPinIN2, LOW);

      analogWrite(PIN_OUTPUT, 255);

      verboseDelay(7000);

      digitalWrite(kPinIN1, LOW);
      digitalWrite(kPinIN2, HIGH);

      analogWrite(PIN_OUTPUT, 255);

      verboseDelay(7000);

      digitalWrite(kPinIN1, HIGH);
      digitalWrite(kPinIN2, LOW);

      analogWrite(PIN_OUTPUT, 255);

      verboseDelay(7000);

      digitalWrite(kPinIN1, LOW);
      digitalWrite(kPinIN2, HIGH);

      analogWrite(PIN_OUTPUT, 255);

      verboseDelay(7000);

      digitalWrite(kPinIN1, LOW);
      digitalWrite(kPinIN2, HIGH);

      analogWrite(PIN_OUTPUT, 255);

      verboseDelay(120000);
    }

    void verboseDelay(unsigned long ms)
    {
      unsigned long now = millis();
      unsigned long start = now;

      do
      {
        now = millis();
      }
      while (now - start < ms);
    }

Here, I have four functions named ``motorDriveFor2Min()``, ``motorDriveFor3Min()``, ``motorDriveFor4Min()`` and ``motorDriveFor5Min()`` for my specific time means for 2 minutes, 3 minutes, 4 minutes and 5 minutes respectively.

So, suppose If I want to drive motor for 4 min then I have to call function ``motorDriveFor4Min()`` and for that, I have to set my reading between 300 & 400. But I can't able to do that because when my reading reaches at 100 then it starts executing another function means ``motorDriveFor2Min()`` and then continuously run that functionality. During that time I try to change the reading but nothing happens. After restating Arduino it run according to the reading.

So, I thought maybe delay() function block everything. So I replace inbuilt delay function with custom delay function. But that can't solve my problem. Then I google it out and I found out that analogRead may cause this problem. Any suggestion for this.

body:
It's not analogRead. It's not (just) delay. It's the whole method of your program.

The way it's written you can do *nothing* else while driving a motor for X minutes.

You need to rethink your whole program so that it's not "run for X minutes" each time, but instead "Run the motor until the time is up" and constantly re-evaluate what the time should be.

That means:

* No "run for X" functions.
* No `delay()` functions (of *any* form - yours is as bad as the normal one).
* A state machine to determine what should be happening when.
* Constantly referencing both `millis()` and `analogRead()` to determine what state the state machine should be in or progress to and when.


message:
Change format preferences for Arduino IDE in Linux

How can I change Arduino IDE preferences for formatting? I found the preferences file: `<user>/.arduino15/preferences.txt`, but there are no lines that control IDE formatting. In Windows there is a special file for formatting: `<ArduinoIDE_folder>/lib/formatter.conf`.

body:
It happened, that my `formatter.conf` was in `/usr/share/arduino/lib/`. So I copied it to `/home/<user>/.arduino15/` folder and made changes that I needed. And also:

> Copy it in the same folder of file "preferences.txt" and modify the copy. This way, you won't lose your custom formatter settings when upgrading the IDE.


message:
Can't assign String to Array of String

I have to input 5 words and organize.
In order to organize words, I have to get them into Array of String to compare.
I succeed to get `char[buffer]` into `String in_str` but somehow `in_str` doesn't
get into `str[5]`.
is `String str[i]=in_str;`  Wrong?? How can I put `in_str` to Array of `String str`??

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

    void loop() {
      int state = 1, len = 0 ,i=0, k=1;
      char buffer[128];
      String str[5];
      while (true) {
        if (state == 1) {
          Serial.print("Enter the ");
          Serial.print(k);
          Serial.print("th Word --> ");
          state = 2;
        }
        while (Serial.available()) {
          char data = Serial.read();
          if (data == '\n') {
            buffer[len] = '\0';
            String in_str = buffer;
            String str[i]=in_str;
            Serial.println(in_str);

            i=i+1;
            k=k+1;
            len = 0;
            if(i>4){state = 3; }
            else {state = 1;}
            break;
          }
          buffer[len++] = data;
        }
      if(state==3){
        Serial.println("After Sorting");
       for (int i = 0; i < 4; i++) {
        for (int j = i + 1; j < 5; j++) {
          int compare = str[i].compareTo(str[j]);
          if (compare > 0) {         String temp = str[i];
            str[i] = str[j];
            str[j] = temp;
          }
        }
      }

       for (int i = 0; i < 5; i++) {
        Serial.println(String(i) + " : " + str[i]);
      }

        break;
      }

      }
    }

body:
When you write `String str[i]=in_str;` that is wrong. You only write the type when you are declaring the variable, once.

When assigning, you need only write the variable name, not the type: `str[i]=in_str;`


message:
Fixing Error function 'long int map

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/woLd3.png

    Arduino: 1.8.5 (Windows 8.1), Board: "Arduino/Genuino Uno"

    C:\Users\julie_000\Documents\Arduino\BIO_199\BIO_199.ino: In function 'void loop()':

    BIO_199:19: error: too few arguments to function 'long int map(long int, long int, long int, long int, long int)'

       t1 = map(2, 0, 1023, 2);

                             ^

    In file included from sketch\BIO_199.ino.cpp:1:0:

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:253:6: note: declared here

     long map(long, long, long, long, long);

          ^

    exit status 1
    too few arguments to function 'long int map(long int, long int, long int, long int, long int)'

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

How do I fix this error?

body:
`map` takes 5 parameters, not 4.  You have the original lower and upper bounds, the desired lower and upper bounds, but you forgot the actual value you want to map:

    map(value, fromLow, fromHigh, toLow, toHigh)

So

    t1 = map(t2, 2, 0, 1023, 2);

(assuming those numbers are actually meaningful...)


message:
Sending servo position data from one Arduino to another

I'm trying to take the position data generated from this servo sweep, and send over serial to another Arduino. The position data is stored as `pos` in the code I included, what would be the best method for doing this?

    /* Sweep
     by BARRAGAN <http://barraganstudio.com>
     This example code is in the public domain.

     modified 8 Nov 2013
     by Scott Fitzgerald
     http://www.arduino.cc/en/Tutorial/Sweep
    */

    #include <Servo.h>

    Servo myservo;  // create servo object to control a servo
    // twelve servo objects can be created on most boards

    int pos = 0;    // variable to store the servo position

    void setup() {
      myservo.attach(9);  // attaches the servo on pin 9 to the servo object
    }

    void loop() {
      for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
        // in steps of 1 degree
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);                       // waits 15ms for the servo to reach the position
      }
      for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);                       // waits 15ms for the servo to reach the position
      }
    }

body:
Yes, sending data over Serial is as simple as using `Serial.write()` or it's siblings. When sending data over Serial you have to consider, how you want to send it.

 1. **Raw binary data:** You can simply use the `Serial.write()` command, which will send the variable as binary data. If you whatch this on the serial monitor of your PC, you will not see readable numbers, because what is shown there is interpreted as ASCII-encoded data, where every byte value has a corresponding character (for example the value 97 is the letter 'a'). On the other Arduino you just use `Serial.read()` to write the byte data directly to a variable. This is practical, if you are sending always the same amount of data (like the value of one sensor). If the length of a message is variable, you have to use a delimiter, to mark the end of a message. Here the second way is more save.
 2. **ASCII encoded data:** You can send your data human readable as ASCII encoded data. The value 128 then would consist of 3 bytes, one for each character. Here you always have to use a delimiter, so that the receiver can tell the values apart. A common message delimiter is the newline character '\n'. On Windows you also often have newline and carriage return '\r' together. For decoding you can use one of the many functions, that convert a string/character array to a number with the wanted format (in your case integer), for example `atoi()`.

Refer to the Serial examples in the Arduino IDE to see the code in action.

Note: Since the value of `pos` only varies between 0 and 180, you can use one byte to save and transmit it, instead of the 2 bytes the integer uses.


message:
Servo issue, won't go into negative range

I'm trying to create a small laser "turret" with x-axis control. The arduino receives input through IR sensor. I'm having a problem where my servo will preform my up and reset function(moves and prints as intended), but When i preform the down function the servo does not move. I believe the function is executing (it outputs angle to LCD and text to serial monitor) but there is no movement.
Any help would be greatly appreciated!

    #include <IRremote.h>
    #include <LiquidCrystal_I2C.h>
    #include <Servo.h>

    int IRPIN = 3;
    int angle = 0;
    int test = 0;
    IRrecv irrecv(IRPIN);
    decode_results results;
    Servo spinnything;
    LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

    void setup()
    {
     irrecv.enableIRIn();
     lcd.begin(16, 2);
     lcd.backlight();
     spinnything.attach(5);
     spinnything.write(angle);
     lcd.setCursor(0, 0);
     lcd.print("WARNING");
     lcd.setCursor(2, 1);
     lcd.print("!!!LASER!!!");
     delay(1500);
     lcd.clear();
    }

    void loop()
    {
     if (irrecv.decode(&results)) {
      irrecv.resume();
     }
     if (results.value == 0xE172C837) {
      up();
      results.value = 0x00000000;
     }
     if (results.value == 0xE17228D7) {
      down();
      results.value = 0x00000000;
     }if (results.value == 0xE1724CB3) {
      reset();
      results.value = 0x00000000;
     }
     lcd.setCursor(0,0);
     delay(10);
    }

    void up() {
     if (angle < 180) {
      angle = angle + 18;
      spinnything.write(angle);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Current Angle");
      lcd.setCursor(3, 1);
      lcd.print("=");
      lcd.setCursor(5, 1);
      lcd.print(angle);
      Serial.print("up");
     }
    }
    void down() {
     if (angle > -180) {
      angle = angle - 18;
      spinnything.write(angle);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Current Angle");
      lcd.setCursor(3, 1);
      lcd.print("=");
      lcd.setCursor(5, 1);
      lcd.print(angle);
      Serial.print("down");
     }
    }
    int reset() {
     angle = 0;
     spinnything.write(angle);
     lcd.clear();
     lcd.setCursor(0, 0);
     lcd.print("Current Angle");
     lcd.setCursor(3, 1);
     lcd.print("=");
     lcd.setCursor(5, 1);
     lcd.print(angle);
     Serial.print("reset");

    }

body:
First of all `Servo.write(int)` takes a value ranging from 0 to 180 degrees.
Then, servos themselves can only move from 0 to 180 usually. Some can do more, some can do less. But regardless of how much a servo actually moves, you should expect that doing `Servo.write(0)` the servo would rotate all the way to one side, doing `Servo.write(180)` it should go to the other side, doing `Servo.write(90)` it should stay in the middle.

Also, `lcd.setCursor(5, 1);` is basically useless as the lcd driver itself would advance the cursor as the previous characters are written. Just do `lcd.print("= ");` if you want an additional space between the equals symbol and the number


message:
Fastest reading through i2c

I have an ADXL345 accelerometer and I read it with an arduino through I2C. I want to get readings at a frequency higher than 500Hz. According to the documentation this should be easily achievable, however I've downloaded and used multiple libraries and none of them was able to achieve a sampling rate higher than 100Hz. They were all based on the arduino Wire library which doesn't seen very efficient. Could someone point me to a library or give me pieces of code that will allow me to sample data at 500+Hz? I send the data to matlab, not that it probably matters.

body:
If you want highest possible frequency, I'd use SPI instead.
With 16 MHz Arduino, SPI clock can be 4MHz.

The chip only supports I2C at 400 KHz clock, which is way slower.
<http://www.analog.com/media/en/technical-documentation/data-sheets/ADXL345.pdf>


message:
Can't power HC-05(5v) with Arduino Pro mini (3.3v)?

I am trying to use HC-05 (5V) with Arduino Pro Mini (3.3v) but I have had little success.

I am using a coin cell to power the pro mini which powers it on and is working fine.

But, my HC-05 doesn't power on. I am trying to power it externally using two 3.7v Lipo-batteries that gives a total of 7.4v but I have tried numerous changes and nothing seems to work.

Circuit Diagram attached below.
[![enter image description here][1]][1]

**Also, HC 05 has an onboard regulator for levelling it to 3.3v**
[![enter image description here][2]][2]

Please Help!!!

  [1]: https://i.stack.imgur.com/EWLjQ.jpg
  [2]: https://i.stack.imgur.com/MHqxz.jpg

body:
It seems like 7.4V DC is greater than the 5V regulator input range on the HC-05.

For example, in the [Core Electronics tutorial][1] for the HC-05 (the tutorial PDF calls it a JY-MCU. I can't find any major differences), the pinout table says the voltage should be from 3.6V to 6V DC:

[![enter image description here][2]][2]

These same values are confirmed by a back-of-the-circuit-board photo from [arduino-info.wikispaces][3]:

[![enter image description here][4]][4]

[Components101][5] says the range is 4V to 6V.

Unfortunately your coin cell voltage is too low. That leaves you with the following options to drop your voltage (if you must use the 7.4V DC battery). Your choice will probably depend on the Wh capacity of your battery, and how efficient you need the voltage drop circuit to be.

 1. Zener diode (few components, inefficient use of power)
 2. Voltage divider with resistors (few components, inefficient use of power)
 3. Linear regulator (few (IC) or many (discrete) components, inefficient use of power)
 4. Switching regulator (many components, efficient use of power (because it does not use a resistor to drop the voltage)

Further details on each of these options are at [Lower Voltage Methods Other than Voltage Dividing][6].

  [1]: https://core-electronics.com.au/attachments/guides/Product-User-Guide-JY-MCU-Bluetooth-UART-R1-0.pdf
  [2]: https://i.stack.imgur.com/LHcly.png
  [3]: https://arduino-info.wikispaces.com/BlueTooth-HC05-HC06-Modules-How-To
  [4]: https://i.stack.imgur.com/Vkt8s.jpg
  [5]: https://components101.com/wireless/hc-05-bluetooth-module
  [6]: https://electronics.stackexchange.com/questions/154553/lower-voltage-methods-other-than-voltage-dividing


message:
Understanding how a tilt switch works

I am learning Arduino and pardon me if this is nooby. I am trying to make an LED glow when the tilt switch is tilted. The LED should not glow if the tilt is in normal position. The circuit and the code are in the attached image.

Based on my understanding of the code, I thought that when the tilt switch pin 5 is passed with HIGH signal from 5V the IF condition gets satisfied and tje LED on pin 13 would glow.

But it does not happen. The LED just glows before I tilt the tilt switch. Could you please clarify/correct my mistake. Thank you.

[![Circuit][1]][1]

  [1]: https://i.stack.imgur.com/65vox.jpg

Attaching the code below as per suggestion

    int ledPin = 13;
    int switchPin = 5;

    void setup() {
      pinMode(ledPin,OUTPUT);
      pinMode(switchPin,INPUT);
    }

    void loop() {
      Serial.begin(9600);
      if (digitalRead(switchPin) == HIGH) {
        digitalWrite(ledPin,HIGH);
        Serial.print("we are here");
      }
      if (digitalRead(switchPin) == LOW) {
        digitalWrite(ledPin,LOW);
        Serial.print("there");
      }
    }

body:
Understanding how PULLUP works lead to the solution. Also learnt that switches are supposed to be connected to ground. Thank you all for your time. Especially chrisl.

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/RIK90.png


message:
Keypad Type 11 numbers only?

Can someone give me any idea what condition should i use in input 11 numbers only in the switch case? I only want to type and input 11 numbers only but The problem is it can type more than 11 numbers.

    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    #include "Keypad.h"

    LiquidCrystal_I2C lcd(0x3F,16,2);  // set the LCD address to 0x27 for a 16 chars and 2 line display

    const byte Rows= 4; //number of rows on the keypad i.e. 4
    const byte Cols= 3; //number of columns on the keypad i,e, 3

    //we will definne the key map as on the key pad:

    char keymap[Rows][Cols]=
    {
    {'1', '2', '3'},
    {'4', '5', '6'},
    {'7', '8', '9'},
    {'*', '0', '#'}
    };

    //  a char array is defined as it can be seen on the above

    //keypad connections to the arduino terminals is given as:

    byte rPins[Rows]= {1,2,3,4}; //Rows 0 to 3
    byte cPins[Cols]= {5,6,7}; //Columns 0 to 2

    // command for library forkeypad
    //initializes an instance of the Keypad class
    Keypad kpd= Keypad(makeKeymap(keymap), rPins, cPins, Rows, Cols);

    char entryStr[8];
    int i=0;
    long number1=0;
    long number2=0;

    void setup()
    {
       Wire.begin();
       lcd.init();
       lcd.backlight();
       Serial.begin(9600);
       delay(100);

    }

body:
Three simple approaches.

 1. You could get a string, and limit it to 11 characters in length. You then convert the string to `num`
 2. You could check that 9999999999<`num`<=99999999999
 3. You could count the number of valid 'kpd.getKey()' and when it gets to 11 exit the function (returning `num` as it stands)

The OP suggests only 11 digits. Of course, if less that 11 digits are acceptable, the returning value could be padded with `0`.

`lcd.print1 can natively takes a string, and the best approach is to treat `num` as a string instead of as a number. A number (in itself) is only useful if you want to do arithmetic. A lot of times a series of digits are used as an identifier - these are not really numbers but strings with a limited character set.

Some examples (not tested):

**Example 1:** counting the digits entered. Simply added a counter `numcount` - you can see where I use it in the conditional loop, where I increment it, and where I clear it.

    long GetNumber()
    {

      long num = 0;
      long numcount = 0;
      char key = kpd.getKey();
      while(key != '#' && numcount <= 11)
      {
        switch (key)
        {
        case NO_KEY:
          break;
        case '0':
    [... skipped for brevity ...]
        case '9':
          lcd.print(key);
          num = num * 10 ;
          num= num+ (key-'0');
          numcount += 1;
          break;
      case '*':
        num = 0;
        numcount = 0;
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Re-type number:");
        lcd.setCursor(0,1);
        break;
      }
      key = kpd.getKey();
    }
    return num;
    }

**Example 2:** Simple check on the value of `num`. In this case both the "#" and `num` reaching a certain value will exit the function in a controlled way. A better loop method would be to `loop ... until` - checking the condition at the end of the loop rather than at the beginning.

    long GetNumber()
    {
      long num = 0;
      char key = kpd.getKey();
      while(key != '#' && num <= 99999999999)
      {
        switch (key)
        {
        case NO_KEY:
          break;
        case '0':
        [... skipped for brevity ...]
        case '9':
          lcd.print(key);
          num = num * 10 ;
          num= num+ (key-'0');
          break;
        case '*':
          num = 0;
          lcd.clear();
          lcd.setCursor(0,0);
          lcd.print("Re-type number:");
          lcd.setCursor(0,1);
          break;
        }
        key = kpd.getKey();
          }
      return num;
    }

**Example 3:** using a string. Same comment about checking conditions at the end of the loop instead of the beginning apply. I haven't worked with strings in C for a few decades, so the routines I used (`strlen`, `strcat`) may need some work or tweaking.

    string GetNumber()
    {
      string num = "";
      char key = kpd.getKey();
      while(key != '#' && strlen(num) <= 11)
      {
        switch (key)
        {
        case NO_KEY:
          break;
        case '0':
        [... skipped for brevity ...]
        case '9':
          lcd.print(key);
          num = strcat(num,key)num * 10 ;
          break;
        case '*':
          num = "";
          lcd.clear();
          lcd.setCursor(0,0);
          lcd.print("Re-type number:");
          lcd.setCursor(0,1);
          break;
        }
        key = kpd.getKey();
        }
      return num;
    }


message:
Debouncing Multiple Buttons

I'm creating a binary calculator with my Arduino. This will take two different binary numbers and add them together. I am focusing right now on the Byte One Input screen. For this, I can use two buttons, the left to change to selected bit to either 0 or 1 when pressed, and the right button to move to the next bit, or when at the end, to move to the next screen. I am having difficulty with the debouncing of the buttons.

Right now, the debouncing is not working and the position changes from 1 to 8 or 16 instead of to the second bit when I hit the right button.

Any help would be great!

**Fixed Code: See accepted answer below.**

           #include <LiquidCrystal.h>
    /*(RS, E, D4, D5, D6, D7)*/
    LiquidCrystal lcd(12,11,5,4,3,2);
    #include <Button.h>

    int page = 0;
    int binary[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    int con = 80;
    char btn_push;
    int pos = 0;

    const int button1Pin = 8;
    const int button2Pin = 9;
    int button1State = HIGH;
    int button2State = HIGH;
    int lastButton1State = HIGH;
    int lastButton2State = HIGH;

    unsigned long debounceDelay = 50;

    //****************************************************************setup*****************************************
    void setup() {
      pinMode(button1Pin, INPUT_PULLUP);
      pinMode(button2Pin, INPUT_PULLUP);

      Serial.begin(9600);
      analogWrite(6,con);
      mylcd.begin();
      lcd.print("Welcome");
    }

    //************************************************************loop************************************************

    void loop() {

      int reading1 = digitalRead(button1Pin);
      int reading2 = digitalRead(button2Pin);

      if (reading1 == lastButton1State &&
          reading2 == lastButton2State)
        return;  // do nothing if no change

      delay (debounceDelay);  // debounce

      // re-read so we can catch both buttons down at once
      reading1 = digitalRead(button1Pin);
      reading2 = digitalRead(button2Pin);

      // save for next time
      lastButton1State = reading1;
      lastButton2State = reading2;

      if (reading1 == LOW && reading2 == HIGH)     // first one down
        btn_push = 'D';
      else if (reading1 == HIGH && reading2 == LOW)  // second one down
        btn_push = 'U';
      else if (reading1 == LOW && reading2 == LOW)  // both
        btn_push = 'S';
      else
        return;  // nothing interesting

     Serial.print("btn_push = ");
     Serial.println(btn_push);

        // page select
        switch (page) {

        case 0:
          page0();
          break;
        case 1:
          page1();
          break;
        case 2:
          page2();
          break;
        case 3:
          page3();
          break;
        case 4:
          page4();
          break;
        }

    }

    // The rest is the same, excluding the functions that are no longer needed

body: The button stays down long enough for you to cycle through more than once, first setting binary[i] to 1 then to 0, etc. you need to add some logic to say “this is the first time I’ve seen this button state”