text:
How to set up a long press with something other than a button?
I wrote a program for a night light. There are 4 modes:

on,
adjustable brightness,
timer,
off.

For input, instead of using a button, I am using a distance sensor. Once a certain distance is read (eg. when passing your hand over the distance sensor) it changes to the next mode.
For the adjustable brightness mode it reads the distance sensor and is mapped to a PWM. The output pin is connected to a MOSFET which is switching a 12 volt LED.
This seems a slow way to cycle thru the system. I would like instead, if the user waved their hand over the sensor, it would turn on or off. However, if the user waited for 3 seconds with their hand over the sensor it would enable a dimmable mode. I'm not concerned about the timer function anymore and will be removing it.
All the code is already there except I need help writing a function that will keep track of how long its been reading a certain distance. Let's say for instance if the sensor reads a distance between 1 inch to 3 inches for 3 seconds it will then go into the dimmable mode. If it's under that then it will only toggle on/off. If the hand remains longer then 3 seconds it will also trigger the dimmable mode.
//----------------------------------------------------------
// USING A DISTANCE SENSOR TO CYCLE THRU DIFFERENT MODE
// FOR AN LED NIGHT LIGHT
// vonderasche
//----------------------------------------------------------

// declares library for distance sensor
#include <NewPing.h>
// constants
#define TRIGGER_PIN  12
#define ECHO_PIN     13
#define MAX_DISTANCE 200
const unsigned long onTime = 5000;
const unsigned long onTimer = 1200000;

int state = 1;

// declares NewPing object
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

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

void loop() {
    delay(50);
    // take distances reading
    int distance = sonar.ping_in();
    static enum { ON, ADJUST, TIMER } state;

    // if distance range is between certain values switch the state
    if (distance > 1 && distance < 3) {
        switch(state) {
        case ON:
          {
            // turns LEDs on
            Serial.println("ON");
            analogWrite(3, 255);
            analogWrite(5, 255);
            state = ADJUST;
            delay(1000);
          }
          break;
        case ADJUST:
          {
            // allows user to set brightness based on hand distance to sensor
            Serial.println("Adjusting Brightness");
            int distance2 = 0;
            int mappedBrightness = 0;
            unsigned long previousMillis = millis();
            unsigned long currentMillis = millis();

            // timer for setting brightness
            while ((currentMillis - previousMillis) < onTime) {
                int distance2 = sonar.ping_in();
                if (distance2 >= 1 && distance2 <= 6) {
                    mappedBrightness = map(distance2, 0, 6, 13, 255);
                    analogWrite(3, mappedBrightness);
                    analogWrite(5, mappedBrightness);
                }
                currentMillis = millis();
            }
            Serial.print("Mapped Brightness = ");
            Serial.println(mappedBrightness);
            delay(1000);
            state = TIMER;
          }
          break;

        case TIMER:
          {
            Serial.println("TIMER - 20 MINS");
            // variable declaration
            unsigned long ontime = 50;
            unsigned long previousMillis = millis();
            unsigned long currentMillis = millis();

            // dims leds to 25 percent
            analogWrite(3, 64);
            analogWrite(5, 64);
            delay(1000);
            // timer for leds
            while ((currentMillis - previousMillis) < onTimer) {
                int distance2 = sonar.ping_in();
                //breaks timer if hand swipe
                if (distance2 >= 1 && distance2 <= 4) {
                    break;
                }
                currentMillis = millis();
            }
            // turn off leds - either hand swipe happened or timer is up
            Serial.println("Turn off LEDs.");
            analogWrite(3, 0);
            analogWrite(5, 0);
            delay(1000);
            state = ON;
          }
          break;
        }
    }
}

Is the dimmer mode used to the case ADJUST: state or planned for another state ?

The dim mode works. Right now the program progresses from case one to case four in sequence. I would rather have on/off or if the hand is held over the sensor long enough the dim mode is triggered

So if delay < 3s ==> switch between ON & OFF state, otherwise ==> go to the ADJUST state ? But is the brightness controlled by the extra delay instead of distance2 ?  And what about the TIMER state ?

This is not too different from the long press of a button. Lets consider the code to detect a long button press of greater than 3 seconds.
buttonState = digitalRead(PIN1);

if (buttonstate == HIGH)
{
    if ((currentMillis - previousMillis) > THREE_SECONDS)
    {
        // Put your code here
    }
}
else  // ie. buttonState == LOW
{
    previousMillis = currentMillis;
}

OK, so the code could be optimized. However, it shows the code for a long button press and hopefully its easy to understand for any newbies out there. The code above reads the button state and if it is HIGH (ie. pressed), it will then check to see if the timer has run for more than 3 seconds. However, if the button is released, the timer resets.
Now lets consider the code for a distance sensor:
int distance = sonar.ping_in();

if (distance >= 1 && distance <= 3)
{
    if ((currentMillis - previousMillis) > THREE_SECONDS)
    {
        // Put your code here
    }
}
else  // ie. outside of the range
{
    previousMillis = currentMillis;
}

You will notice that only the first two lines change. I hope this helps!!


text:
Can you pass params to an arduino sketch?
I was wondering if there is a way to pass parameters to an arduino sketch at the upload step.
Edit: The reason this would be helpful is because I have a bunch of esp8266 units that need to have details about their specific location but changing variables around per upload feels tedious.
If this is not possible the other solution that I am probably going to try is to have a sketch to just flash these details to eeprom and then read it from there whenever it is needed. Also storing them in eeprom feels a bit better than as literals in these sketches.

You might be able to do something tricky to the binary image with dd

Is there a dd equivalent for windows?

googling finds: http://www.chrysocome.net/dd

http://www.nongnu.org/avrdude/user-manual/avrdude_6.html indicates you can save separate eeprom images in addition to the code.

That might be perfect.

ESP8266 doesn't use avrdude.

Right, either way I tried the method below my edit and it worked out fine.

Every ESP8266 has a unique MAC address. You could that information to distinguish between the different units.
Something like if( mac='00:0a:95:9d:68:16' ){ ... }

Yes but I need each unit to know where it is located, I do not want to have an external lookup for its location.

You could store all the locations in an array in your code. Then use the MAC address to look up the right location from the list. The only downside is that you need to know the locations and mac-addresses ahead of time.

Another option, if you can afford the pins, is to install DIP switches or ground-jumpers on a few pins and set / wire a different n-bit code onto each board. Set those pins to INPUT_PULLUP, read them at setup, and wallah! each board is unique. You can put the lookup table (binary number -> parameter string, f/ex) in Flash so it doesn't take up scarce RAM.

To add to the above, you could use two pins with dip switches and add resisters to make a ladder. then just read the R value?

In that case you'd only need one (analog) pin.

source: Stack Exchange

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

sort: votes


text:
code for automatic door
I want it running as a normal automatic door so both sensors work as a separate activate. The only problem I've seen is that the servo remains active waiting for another high read and you can hear the buzz of it trying to keep position.
It didn't used to do this before the code change. While its open, if it reads another high it will remember and rerun the open wait close after it closes.
Eg. The door activates and while open 3 people walk thru so when the door closes it will then run 3 more times with out anyone being there.
Edit: Code changed
    #include <Servo.h>

  Servo myservo;

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

  //amount of time we give the sensor to calibrate(10-60 secs according to       the datasheet)

  int calibrationTime = 30;

  int pirPin = 12; //digital pin connected to the PIR's output
  int pirPos = 13; //connects to the PIR's 5V pin
  int pirPin2 = 6; //digital pin connected to the PIR's output
  int pirPos2 = 10; //connects to the PIR's 5V pin
  const int position_closed = 0;      // door closed position [deg]
  const int position_open = 90;      // door open position [deg]
  const uint32_t delay_step = 15;     // delay between servo steps [ms]
  const uint32_t delay_open = 60000;  // how long the door stays open [ms]

  void setup()

  {
      myservo.attach(4); //attaches servo to pin 4
Serial.begin(9600); //begins serial communication
pinMode(pirPin, INPUT);
pinMode(pirPos, OUTPUT);
digitalWrite(pirPos, HIGH);
pinMode(pirPin2, INPUT);
pinMode(pirPos2, OUTPUT);
digitalWrite(pirPos2, HIGH);

//give the sensor time to calibrate
Serial.println("calibrating sensor ");
for(int i = 0; i < calibrationTime; i++)
{
    Serial.print(calibrationTime - i);
    Serial.print("-");
    delay(1000);
}
Serial.println();
Serial.println("done");
  }

  void loop()
  {
static enum { CLOSED, OPENING, OPEN, CLOSING } state;
static int position;          // door position
static uint32_t last_change;  // last time state or position changed
uint32_t now = millis();

// When presence is detected, switch to the OPENING state.
if ((digitalRead(pirPin) == HIGH || digitalRead(pirPin2) == HIGH)
        && state != OPENING) {
    state = OPENING;
    last_change = now;
}
else switch (state) {
    case CLOSED:
        break;
    case OPENING:
        if (position == position_open) {
            state = OPEN;
            last_change = now;
        } else if (now - last_change >= delay_step) {
            myservo.write(++position);
            last_change = now;
        }
        break;
    case OPEN:
        if (now - last_change >= delay_open) {
            state = CLOSING;
            last_change = now;
        }
        break;
    case CLOSING:
        if (position == position_closed) {
            state = CLOSED;
            last_change = now;
        } else if (now - last_change >= delay_step) {
            myservo.write(--position);
            last_change = now;
        }
        break;
      }
  }

Please edit your question to include what behaviour you DO see when it the code runs. e.g. Do you see the serial output expected during setup (calibrating sensor and SENSOR ACTIVE) ?

Are you trying to go from 0 to 180, delay, go from 180 to 90, delay, go from 90 to 0 ?   (i.e. 3 stages :- open, close partway, close fully, with delays between) ?

On top of what @KennetRunner said we need to know the expected behaviour: do you want any PIR to open the door or do you want both PIRs to detect something in order to open the door? Because you are in the second condition from the code above....

KennetRunner already explained what is wrong with your code. Here I will
try to give advice on the proper way to implement the automatic door.
First thing is to get rid of delay(). While your program is inside a
call to delay(), it can do nothing but wait until the delay is over.
This is acceptable if the program has only one single task to perform,
like blinking an LED. As soon as you have two tasks, delay() is a
nuisance because it blocks all the tasks.
Case in hand: after keeping the door open for one minute, your program
would close it, irrespective of whether there is someone in the way. It
could not see the person come because it was busy delaying the closing
of the door.
The standard way to get rid of delay() is to never wait inside
loop(). Instead, if there is something to do right now, do it; if
not, just don't do it, but do not wait. Pseudo-code:
void loop()
{
    if (it_is_time_to_do_foo()) {
        do_foo();
    }
    if (it_is_time_to_do_bar()) {
        do_bar();
    }
    /// etc...
}

You would use the millis() function to know when the time has
come to do some task, as explained in the Blink Without Delay
Arduino tutorial. This is really the second tutorial every Arduino user
should read, right after learning how to blink an LED.
Next, you have to learn how to implement a finite state machine. I
recommend the Finite State Machine tutorial by Majenko,
a regular contributor to this site.
Your problem can be very naturally mapped into a machine with four
states: CLOSED, OPENING, OPEN and CLOSING. You then write the rules
about what to do in each state, and when to transition to another state.
For example:

when the door is CLOSED

if the sensors detect someone, transition to the OPENING state

when the door is OPENING

if it's time to move the servo by one step, do it
if we have already moved all the way to the open position, we can
say the door is OPEN now

when the door is OPEN

if it's time to close it, transition to the CLOSING state
if the sensors detect someone, reset the timer <<<< note this!

when the door is CLOSING

if the sensors detect someone, transition to the OPENING state
if it's time to move the servo by one step, do it
if we have already moved all the way to the closed position, we say
the door is now CLOSED

A few things to note here:

See the line marked by “<<<<”: this will prevent the aforementioned
problem of the door closing into someone.
The first rule for the CLOSING state follows from a similar rationale.
I made up some of these rules, as the job of your program was not
completely specified in your question. Feel free to change those rules
to your taste.

And here is my proposed implementation. Warning: not tested. As
usual with FSMs, it is based on a big switch/case statement going
through all the possible states. However, to avoid repeating rules, I
factored the “if there is someone, start OPENING” rule out of the
switch. I also folded “if there is someone, reset the timer” into the
same rule.
const int position_closed = 0;      // door closed position [deg]
const int position_open = 180;      // door open position [deg]
const uint32_t delay_step = 15;     // delay between servo steps [ms]
const uint32_t delay_open = 60000;  // how long the door stays open [ms]

void loop()
{
    static enum { CLOSED, OPENING, OPEN, CLOSING } state;
    static int position;          // door position
    static uint32_t last_change;  // last time state or position changed
    uint32_t now = millis();

    // When presence is detected, switch to the OPENING state.
    if ((digitalRead(pirPin) == HIGH || digitalRead(pirPin2) == HIGH)
            && state != OPENING) {
        state = OPENING;
        last_change = now;
    }
    else switch (state) {
        case CLOSED:
            break;
        case OPENING:
            if (position == position_open) {
                state = OPEN;
                last_change = now;
            } else if (now - last_change >= delay_step) {
                myservo.write(++position);
                last_change = now;
            }
            break;
        case OPEN:
            if (now - last_change >= delay_open) {
                state = CLOSING;
                last_change = now;
            }
            break;
        case CLOSING:
            if (position == position_closed) {
                state = CLOSED;
                last_change = now;
            } else if (now - last_change >= delay_step) {
                myservo.write(--position);
                last_change = now;
            }
            break;
    }
}

thanks for the code ive included it over what i had the only problem ive seen is that the servo remains active waiting for another high read and u can hear the buzz of it trying to keep position and while its open if it reads another high it will remember and rerun the open wait close after it closes

@ANDREW: I couldn't quite make a sense of your last comment. “the servo remains active [...] trying to keep position”: this is normal, and it's exactly what a servo is meant to do when you do not ask it to move elsewhere. “it will remember and rerun the open wait close”: I could not replicate the behavior you describe.

U can hear the constant buzzing noise it creates when running. the last code I used only made a noise when moving not when waiting for next high. I was thinking of adding detach at the end and attach at the start that might help

You expect the servo to be noisy when it's moving or when, in a static position, it is fighting some load. If static and unloaded, it shouldn't make much noise.

Your code is looping 180 times, EACH TIME it :

Sets the servo to 180
Delays for 2 seconds
Sweeps the servo from 180 to 90 in single steps
Sets the servo to 90
Delays for 60 seconds
Sweeps the servo from 90 to 180 in single steps

So you code will take more than 3 hours to complete.
I think you would be better pulling the code that moves the servo out into its own function: Something like:
void moveServo(servoStart, servoEnd, servoStep, servoInterval)
{
  for(int servoPos = servoStart; servoStart < servoEnd; servoStep)
  {
     myservo.write(servoPos);
     delay(servoInterval);
  }
}

then simply call it from your main loop, like this:
void loop()
{

    if((digitalRead(pirPin) == HIGH) && (digitalRead(pirPin2) == HIGH))
    {
      moveServo(0, 180, 1, 15);
      delay(2000);
      moveServo(180, 90, -1, 15);
      delay(60000);
      moveServo(90, 0, -1, 15);
    }
}

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


text:
FastLED - How to Control specific LEDs
I am fearly new to Arduino and FastLED. I found a nice Sketch which fits almost perfectly to my needs.
Just one Problem:
I dont want the Sketch to effect ALL LEDs in one color.
I want some LEDs in Red (ex. LEDs 0-4) Some in green and others in blue.
They could all have the same effect and timing, but it would be really neat if I could make them out of sync a little bit.
But having the possibility to make different LEDs different colored would be great. Here is the "Pulse" or "Breath" Sketch I want to use.
    #include <FastLED.h>

    #define NUM_LEDS 37
    #define DATA_PIN 11
    #define CLK_PIN 13

    CRGB leds[NUM_LEDS];

    int fadeAmount = 5;  // Set the amount to fade I usually do 5, 10, 15, 20, 25 etc even up to 255.
    int brightness = 0;

    void setup()
    {
      FastLED.addLeds<APA102, DATA_PIN, CLK_PIN, BGR>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
      FastLED.setBrightness(50);
    }

    void loop()
    {
       for(int i = 0; i < NUM_LEDS; i++ )
       {
       leds[i].setRGB(0,255,250);  // Set Color HERE!!!
       leds[i].fadeLightBy(brightness);
      }
      FastLED.show();
      brightness = brightness + fadeAmount;
      // reverse the direction of the fading at the ends of the fade:
      if(brightness == 0 || brightness == 255)
      {
        fadeAmount = -fadeAmount ;
      }
      delay(80);  // This delay sets speed of the fade. I usually do from 5-75 but you can always go higher.
    }

The colors of the LEDs in your sketch are set in this loop:
for(int i = 0; i < NUM_LEDS; i++ )
{
    leds[i].setRGB(0,255,250);  // Set Color HERE!!!
    leds[i].fadeLightBy(brightness);
}

You loop over all LEDs and set them to a specific color and brightness. The changes will be send to the LEDs, when you call FastLED.show() afterwards. There is nobody, that prevents you from setting a different color for each LED or to only chnage the value for some of the LEDs.
For example, to light the first 5 LEDs in red, the next 10 in green and leaving the rest as they were before, you can use this code (Just exchange it with your for loop):
for(int i=0;i<5;i++){
    leds[i].setRGB(255,0,0);
    leds[i].fadeLightBy(brightness);
}
for(int i=5;i<15;i++){
    leds[i].setRGB(0,255,0);
    leds[i].fadeLightBy(brightness);
}
FastLED.show();

The principle is, that you have an array with color values. Each value consists of 3 smaller values for red, green and blue (RGB)(The color results from the distribution between red, green and blue; the brightness results from the overall level of red, green and blue). And each value of the array is bound to an LED (First value to first LED, second value to second LED,...). You can change the color values in the array as you like. And when you want the LEDs to show the current values in the array, you send them out by using FastLED.show(). This means you have to call this function everytime, that you want LEDs to change. You don't have to change every value in the array for this to work.
If you would like to build an asynchronous change of colors, you can ditch the delay(80) and use non-blocking code like in the BlinkWithoutDelay example of the Arduino IDE. There you use the millis() function as a clock (it returns the milliseconds since the Arduinos startup). You take a timestamp at the beginning and compare the difference between it and the current time:
unsigned long timestamp=0;
unsigned long interval=80; //interval of 80 milliseconds

void loop(){
    unsigned long current_time=millis();
    if(current_time - timestamp > interval){
        // do something here, like setting LED colors
        timestamp = current_time;
        // don't forget FastLED.show(), to output the colors
    }
}

You can use multiple of these timestamps with if-statements, one for each segment you want to change in a different frequency.

Hi, wow!
I am absolutely amazed how good you explained and showed all this to me!
This is great!
I will absolutely try this when i am at home from work and give feedback.
Thank you very much !

WOW this worked perfect!!
Again: Thank you very much!!!

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


text:
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:
#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() {

how are you connecting two ethernet cables to the ethernet shield?

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.


text:
How does Arduino determine whether the given condition provided to it is true or false?
I want to understand how does the microcontroller determine that the conditions provided to it in the input are true or false. eg:
if (someVariable > 50)
{
  // do something here
}

Then how does Arduino determine if the value that I put in `somevariable' is larger than 50 (as apposed to less than or equal to 50)?

It's not clear to me what you are asking.  Could you find another way to phrase it, please?  Do you want to know what machine instructions it uses to evaluate (someVariable > 50)?  Or something else?

In general terms comparisons are usually performed, at the low level of assembly language, using subtraction.
In assembly language when you perform a subtraction there are flags in the status register that may or may not get set depending on what has happened. These include the Zero flag and the Carry flag.
If you are comparing A to B then you subtract B from A and see what happened by examining the flags.
For instance, if your variable contains 30 and you compare it to 50 you subtract 50 from 30. Because the result "passes through" zero the Carry flag is set. You can then do a "Jump if Carry Set" call.
If you should have 50 in your variable and you compare it to 50 the subtraction ends up with the Zero flag set since the result is exactly zero. It is then possible to do a "Jump if Zero Set" call.
If you have 60 in your variable and compare it to 50, the subtraction results in 10, which doesn't set either flag. That is actually slightly harder to work out (depending on architecture) since you are then wanting to compare two flags (Carry and Zero) and see if neither of them are set. So it is common for the compiler to optimize it so that the condition is reversed (a > b is the same as !(a <= b) for instance).
Of course, some architectures have actual comparison instructions (often CMP) which compares two registers and sets or clears the different flags for you. For instance, the ATMega328P has the instructions:

CPSE - Compare, Skip if Equal
CP - Compare
CPC - Compare with Carry
CPI - Compare Register with Immediate

CPI would be the most logical choice in the example you give - compare the contents of a register (variable) with an "immediate" value (an "immediate" value is a constant value):
CPI $r3, 50

According to the instruction set manual the comparison is, surprise surprise, performed as a subtraction, and what happened during the subtraction sets the different flags. To make life simpler the instruction set has a number of branch instructions which look at the different flag combinations and jump to another address if they match:

BRLT - Branch if the result of the previous comparison was A < B
BRLE - Branch if the result of the previous comparison was A <= B
BRGT - Branch if the result of the previous comparison was A > B
BRGE - Branch if the result of the previous comparison was A >= B
BREQ - Branch if the result of the previous comparison was A == B
BRNE - Branch if the result of the previous comparison was A != B

There are more as well for other special comparisons.  You can read up all about them in the AVR instruction set manual.

Just to complement Majenko's answer with an example, I tried the
following:
volatile int someVariable;
void do_something_here();

void foo()
{
    if (someVariable > 50)
    {
      do_something_here();
    }
}

and the compiler generated the following assembly (comments mine):
foo:
    lds r24, someVariable      ; load variable into registers, LSB
    lds r25, someVariable + 1  ; and MSB
    sbiw r24, 51               ; subtract 51
    brlt .L1                   ; if (result < 0) goto .L1
    jmp do_something_here      ; do_something_here()
.L1:
    ret                        ; return

The sbiw instruction means "subtract immediate from word". It
subtracts a 6-bit immediate value from a 16-bit value contained in a
register pair (r25:r24 in this case). It is one of the very few 16-bit
instructions of this mostly 8-bit CPU.
As you see, the compiler did some optimization and changed the code to
something looking more like:
if (!(someVariable - 51 < 0))
{
    do_something_here();
}

It is also worth noting that the brlt instruction (branch if lower
than) tests the sign flag of the status register, which is the exclusive
OR of the negative flag (result < 0) and the overflow flag. This way the
result of the comparison is correct even if the subtraction overflows.
Note also that this is only an example. The generated assembly would be
different if you use another type than int (a wider or smaller or
unsigned integer), or an explicit constant greater than 62.


text:
What might be the errors of my codes?
I tried to imitate lagsilva's clock projects using Arduino Uno and made the circuitry, then I've tried to upload the main source code of the author but noticed that it didn't work, so I've edited the sketch and modified some of the details. When uploading it to the board, it seemed fine but there was nothing on the board and the project. Here are the codes:
Lagsilva's:
/*  4-Stroke Digital Clock With Two MAX72XX LED Matrix & RTC
              V1.1 - 02.Feb.2018
               Author: LAGSILVA */

     #include <LedControl.h>                   // Library for LED Matrix - MAX72XX
#include <Wire.h>                         // Library for DS3231 - Pins of Arduino UNO: A4 (SDA), A5 (SCL)
#include <DS3231.h>                    // Library for Real Time Clock
// Global Variables
byte hh, mm;                              // Hour, Minute
byte uH, uM, dH, dM;                      // Units Hour, Units Minute, Teens Hour, Teens Minute
byte p = 0;                               // Plot Mode (Position of Digits: Up/Down)
int RPM = 0, lastRPM = 0, pinRPM = 0;     // RPM, Last value of RPM, Analog Pin for RPM
byte seq = 1;                             // Start Fire sequence

/*
  Pin numbers do Arduino para conexao com o MAX72XX (matriz de LED com controlador MAX72XX)
  pin 7 is connected to the DataIn (DIN)
  pin 6 is connected to LOAD (CS)
  pin 5 is connected to the CLK (CLK)
*/

LedControl lc = LedControl(7, 5, 6, 2);  // LedControl(int DIN, int CLK, int CS, int numDevices)

// Array of Digits - (0 to 9) - Size 5x3

byte num[10][3] = {

  {0xF8, 0x88, 0xF8}, // 0
  {0x00, 0xF8, 0x40}, // 1
  {0xE8, 0xA8, 0xB8}, // 2
  {0xF8, 0xA8, 0x88}, // 3
  {0x78, 0x20, 0xE0}, // 4
  {0xB8, 0xA8, 0xE8}, // 5
  {0xB8, 0xA8, 0xF8}, // 6
  {0xC0, 0xB8, 0x80}, // 7
  {0xF8, 0xA8, 0xF8}, // 8
  {0xF8, 0xA0, 0xE0}, // 9

};

void setup() {

  setSyncProvider(RTC.get);    // Function to read RTC (Real Time Clock)
  //setSyncInterval(3600);                // Set the number of seconds between re-sync
  //setTime(14, 59, 00, 03, 02, 2018);    // Set the Time and Date
  //RTC.set(now());                       // Set the RTC time

  // Setup of Display "0"
  lc.shutdown(0, false);                // Wakeup Display "0"
  lc.setIntensity(0, 4);                // Set the Brightness of Display (0 to 15)
  lc.clearDisplay(0);                   // Clear Display "0"

  // Setup of Display "1"
  lc.shutdown(1, false);                // Wakeup Display "1"
  lc.setIntensity(1, 4);                // Set the Brightness of Display (0 to 15)
  lc.clearDisplay(1);                   // Clear Display "1"

}

void loop() {

  hh = (11);
  mm = (14);

  uH = hh % 10;
  dH = hh / 10;

  uM = mm % 10;
  dM = mm / 10;

  // Plot Hours

  for (byte k = 0; k < 3; k++) {

    lc.setRow(0, k + 5, num[dH][k] >> (p + 2));
    lc.setRow(0, k + 1, num[uH][k] >> (3 - p));

  }

  // Plot Minutes

  for (byte k = 0; k < 3; k++) {

    lc.setRow(1, k + 4, num[dM][k] >> (3 - p));
    lc.setRow(1, k , num[uM][k] >> (p + 2));

  }

  // Plot Fire Sequence: 1-3-4-2 (4 cyl: 1-3-4-2 or 1-2-4-3 or 1-4-3-2)

  if (seq == 1) {                               // Fire Cyl #1
    lc.setLed(0, 6, 0, true);
  }

  if (seq == 2) {                               // Fire Cyl #3
    lc.setLed(1, 5, 0, true);
  }

  if (seq == 3) {                               // Fire Cyl #4
    lc.setLed(1, 1, 0, true);
  }

  if (seq == 4) {                               // Fire Cyl #2
    lc.setLed(0, 2, 0, true);
  }

  seq = seq % 4 + 1;

  // RPM reading

  RPM = analogRead(pinRPM);                     // Potentiometer reading

  RPM = map(RPM, 0, 1023, 1, 9);

  if (RPM <= 8) {
    lc.setLed(1, 7, 8 - RPM, true);
    lc.setLed(0, 0, 8 - RPM, true);
    delay(300 / RPM);                           // Speed setup by potentiometer (100 - 800 RPM)

    if (lastRPM != RPM) {
      lc.setRow(0, 0, 0);
      lc.setRow(1, 7, 0);
      lastRPM = RPM;
    }

  }

  p = !p;                                       // Switch the position of digits (Up x Down)

}

My modification was this:
#include <Wire.h>
#include <DS3231.h>
#include <LedControl.h>
// Global Variables
byte hh, mm;                              // Hour, Minute
byte uH, uM, dH, dM;                      // Units Hour, Units Minute, Teens Hour, Teens Minute
byte p = 0;                               // Plot Mode (Position of Digits: Up/Down)
int RPM = 0, lastRPM = 0, pinRPM = 0;     // RPM, Last value of RPM, Analog Pin for RPM
byte seq = 1;                             // Start Fire sequence

LedControl lc = LedControl(7, 5, 6, 2);  // LedControl(int DIN, int CLK, int CS, int numDevices)

// Array of Digits - (0 to 9) - Size 5x3

byte num[10][3] = {

  {0xF8, 0x88, 0xF8}, // 0
  {0x00, 0xF8, 0x40}, // 1
  {0xE8, 0xA8, 0xB8}, // 2
  {0xF8, 0xA8, 0x88}, // 3
  {0x78, 0x20, 0xE0}, // 4
  {0xB8, 0xA8, 0xE8}, // 5
  {0xB8, 0xA8, 0xF8}, // 6
  {0xC0, 0xB8, 0x80}, // 7
  {0xF8, 0xA8, 0xF8}, // 8
  {0xF8, 0xA0, 0xE0}, // 9

};

void setup() {

  //setSyncInterval(3600);                // Set the number of seconds between re-sync
  //setTime(19, 07, 59, 06, 03, 2018);    // Set the Time and Date
  //DS3231.set(now());                       // Set the RTC time

  // Setup of Display "0"
  lc.shutdown(0, false);                // Wakeup Display "0"
  lc.setIntensity(0, 4);                // Set the Brightness of Display (0 to 15)
  lc.clearDisplay(0);                   // Clear Display "0"

  // Setup of Display "1"
  lc.shutdown(1, false);                // Wakeup Display "1"
  lc.setIntensity(1, 4);                // Set the Brightness of Display (0 to 15)
  lc.clearDisplay(1);                   // Clear Display "1"

}

void loop() {

  hh = (21);
  mm = (32);

  uH = hh % 10;
  dH = hh / 10;

  uM = mm % 10;
  dM = mm / 10;

  // Plot Hours

  for (byte k = 0; k < 3; k++) {

    lc.setRow(0, k + 5, num[dH][k] >> (p + 2));
    lc.setRow(0, k + 1, num[uH][k] >> (3 - p));

  }

  // Plot Minutes

  for (byte k = 0; k < 3; k++) {

    lc.setRow(1, k + 4, num[dM][k] >> (3 - p));
    lc.setRow(1, k , num[uM][k] >> (p + 2));

  }

  // Plot Fire Sequence: 1-3-4-2 (4 cyl: 1-3-4-2 or 1-2-4-3 or 1-4-3-2)

  if (seq == 1) {                               // Fire Cyl #1
    lc.setLed(0, 6, 0, true);
  }

  if (seq == 2) {                               // Fire Cyl #3
    lc.setLed(1, 5, 0, true);
  }

  if (seq == 3) {                               // Fire Cyl #4
    lc.setLed(1, 1, 0, true);
  }

  if (seq == 4) {                               // Fire Cyl #2
    lc.setLed(0, 2, 0, true);
  }

  seq = seq % 4 + 1;

  // RPM reading

  RPM = analogRead(pinRPM);                     // Potentiometer reading

  RPM = map(RPM, 0, 1023, 1, 9);

  if (RPM <= 8) {
    lc.setLed(1, 7, 8 - RPM, true);
    lc.setLed(0, 0, 8 - RPM, true);
    delay(300 / RPM);                           // Speed setup by potentiometer (100 - 800 RPM)

    if (lastRPM != RPM) {
      lc.setRow(0, 0, 0);
      lc.setRow(1, 7, 0);
      lastRPM = RPM;
    }

  }

  p = !p;                                       // Switch the position of digits (Up x Down)

}

Anyone could help me please, thank you!

Did you try first a sketch to see if actually something can be displayed at all? To rule out, the circuit is OK?

I tried both of the sketches but none worked, so I was wondering if there might be some errors on the codes. Yes, sir, the circuit (as shown) was built in line with the diagram.

If you try a default / example sketch, high likely there is a problem in your circuit. First try a/the default sketch for an 8x8 matrix separately, than the other, than you can continue with this more 'advanced' sketch.

I have doing this project for a week or so and repeatedly checked if there are errors in the circuit I might got, and based on (I think) 7-10 times of checking the schematic diagram, there are no errors on the circuit. Okay sir, I'll try. Thank you!

run the example sketch for the martix

But did you EVER see the matrix lighting up? If not, do as I and Juraj said: try the example sketch first, and work up from there to the sketch you really want to use (in your post). Double check voltages if needed (using a multimeter, analyzer or oscilloscope), check pin numbers are correct (in your code/circuit). Only if you got that working, you know at least the circuit and starting code is ok.

LedControl lc = LedControl(7, 5, 6, 2);  // LedControl(int DIN, int CLK, - your picture is not in line with this entry. Pin 7 connected to CLK on the picture, and your code say CLK line connected to pin 5. And you claim you have checked your wiring?

what is the part number on the LED matrix module?

@smajli Sir, when I saw the changes in the codes and in the diagram, I've changed immediately the wirings on my arduino board.


text:
Arduino serial plotter with independent Y axis, is it possible?
The Arduino IDE has a built in functionality that allows the user to plot a value (such as temperature) over time.
I would like to plot two variables with different ranges on the y-axis (pressure in the range of thousands and temperature which varies from 20°C to 40°C).
I could make it work to have both being plotted, but the range differences does not allow me to see small changes in one/both quantities. Is there a way to two, or more, Y axis each one with its own scale?

No. The Arduino Serial Plotter only supports one Y axis.
An alternative would be to capture the data into a file as CSV data and use some other software to plot it - you could import the data into Excel / LibreOffice, or (as I prefer for quick graphing) use something like GnuPlot (or whatever is similar for your chosen OS).
For instance, this is a GnuPlot configuration for plotting two independent axis datasets and the results:
set datafile separator ","
set terminal png enhanced size 1360,768
set output 'testCharge.png'
set ytics nomirror
set ylabel "Current (A)"
set y2label "Voltage (V)"
set y2tics nomirror
plot "testCharge.csv" using 3 smooth bezier title "Current" w l, \
     "testCharge.csv" using 4 title "Cutoff" w l dashtype 2, \
     "testCharge.csv" using 2 smooth bezier title "Voltage" w l axes x1y2

The data I use is formatted thus:
Phase,Voltage,Current,Cutoff
0,3.58,1.098,0.033
0,3.59,1.098,0.033
0,3.59,1.098,0.033
0,3.59,1.098,0.033
0,3.6,1.098,0.033
0,3.6,1.098,0.033
0,3.6,1.098,0.033
0,3.61,1.098,0.033
0,3.61,1.098,0.033
... etc ...

And the results:
Incidentally, that's me charging a Li-Ion battery and monitoring the voltage and current.

The Serial Plotter from within the Arduino IDE is quite limited. Not to mention the lack of documentation on the Arduino website. So, no the Serial Plotter cannot do what you require.
However, there is a very good selection of serial data plotter programs over at this question: Serial data plotting programs


text:
ESP8266 not able to communicate over serial connection with arduino UNO
This is the code I uploaded in Arduino UNO:
#include<SoftwareSerial.h>
SoftwareSerial ESP(2,3); // RX, TX
//ESP RX-->3(UNO) TX-->2(UNO)

void setup() {
// Open serial communications and wait for port to open:

    Serial.begin(9600);
    while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
    }

    Serial.println("Goodnight moon!");

    // set the data rate for the SoftwareSerial port
    ESP.begin(9600);

}

void loop() {
    if (ESP.available()) {
        char inData = ESP.read();
        Serial.println("Got reponse from ESP8266: ");
        Serial.write(inData);
    }

    ESP.write("AT\r\n"); //Normally ESP responds to AT command with "OK"
}

But ESP is not able to receive the AT command properly...sometimes it recieves A, sometime T. It then responds with garbage value. Though we are able to give command to ESP through Serial Monitor and it responds pretty well. But when trying to communicate through code, the communication is not OK.

Why is this question downvoted and voted to close? MCVE code is provided, sympthoms of failure are described. What is the problem?

Are you aware that you can program the ESP8266 directly from the Arduino IDE using proper Arduino C rather than AT commands.  This means that it might be possible to eliminate the need for a 32MHz Arduino and just rely on the 160MHz ESP82366 instead.
Also you need to have a look at the SO Arduino forum.

Unless you are pushing the connections on an Arduino to the limit it might be worth looking at a Webbo D1, its an ESP8266 12E with an Arduino form factor.  The biggest issue I have had porting is remembering the Pins are addressed by GPIO label not pin number.

@Matt do you mean WeMos D1? There is no Webbo D1.

@gre_gor - Yes, that's the one.  Sorry its been a long week :(

The problem is in your loop() function. On each iteration, you will receive at most one character from the SoftwareSerial, while writing the same AT command again and again. As a result, your slave device (ie. ESP8266) will overflow its UART buffers, resulting in garbage being sent and received.
You should keep receiving data from the slave for as long as it has data:
while (ESP.available()) {
    char inData = ESP.read();
    Serial.println("Got response from ESP8266: ");
    Serial.write(inData);
}

@abhimanyubishnoi Note that you can click o that "check" mark to accept my answer if it really solved your problem. That way, other people will see your problem was solved, and move on to answer unsolved questions.

Dmitry Grigoryev - i have tried u r solution, but still i am not able to get response 'OK' from ESP 01(my device)....here is the screen shot with response https://i.sstatic.net/mOklg.png....

@3bu1 Judging by your screenshot, you still have failed to replace if with while.

still the same, here is the screen shot(https://i.sstatic.net/3nAC2.png) and i have posted question on this url(https://arduino.stackexchange.com/questions/39729/not-able-to-get-response-from-esp-using-arduino-uno), kindly help me with this...thank u in advance


text:
How to track revolution of DC motor?
I am currently trying to build a line follower robot that is designed to solve maze. This maze has a loop, thus it needs to know distance it already travelling (or at least I assume so, please let me know otherwise).
I am aware of a rotary encoder motor from Polulu (for example) but it's not available in my country and shipping price is too expensive.
So I need to find way around it. Should I use Stepper motor? Is there any other way? Thanks in advance.

@yabbadabba - comments under questions are for seeking clarification about the question. Not for stating that your answer is the best one. People will vote for answers that they think are good, including yours, if they merit such votes. Your comments have been deleted.

You can Use wheel encoders. You can even make your own wheel encoders with general parts like photoTransistor and lasor or led light. you can make your encoder or print it out in paper. The use little math to calculate the distance. It will give you measurement with good level of precision.
Basic principle:

more information at
wheel Encoder
another encoder

If the OP make their own hand built encoder then how do they know how accurate it is?

@yabbadabba, if the OP makes his own hand built encoder, he will know the number of openings in the wheel. He will be able to count the number of openings and measure the distance that the wheel travels, or simply perform the math of circumference equals pi times the diameter.

@fred_dot_u I think what your saying is likely to be  true if he makes it with a CNC machine

There's a fellow on YouTube (HomoFaciens) who makes amazing constructions with ordinary tools. His encoder wheel is cut out of sheet metal or cardboard depending on the device he's building. The slots are cut with scissors or metal shears and are mildly irregular, yet provide fractional control of the device. The founding principles of the physics of the encoder wheel care not about the sophistication of the construction. One can turn a bicycle wheel into an encoder, which happens to be how bicycle speedometers work! So many answers, so few characters.

@fred_dot_u    " (HomoFaciens) who makes amazing constructions with ordinary tools"- sounds like he's got a rare talent

One of his talents is his skill at presenting material for the benefit of so many, to make this sort of thing (encoding, in this case) easier to understand and to implement in one's own projects. As an example specific to this project, the OP could use or add toy wheels with spokes and install an optical sensor to trigger on the spokes. That would qualify as a hand-built encoder and the OP could count the spokes. The diameter and circumference can be measured as well. The OP's satisfaction can be gained by implementing something from materials on-hand (purchased) rather than CNC created.

@fred_dot_u " (HomoFaciens) who makes amazing constructions with ordinary tools"-there's a video of him building a rotary encoder- doesnt seem to use a toy wheel though. There's different ways to make , hand made, the encoder-by using print out on paper as it says in this answer

Guys guys. No need to use any tools. Print the graphichs on a photocopy paper and attached it on the wheel. Like in second link. Thanks but its 3 am n i feel so sleepy.

An optical encoder would be the best solution in my opinion. The next best thing would be to use a stepper motor. You can find plenty of stepper motors in old printers - which is good if the budget is tight.
The problem with a stepper motor is that you have no feedback on where the motor actually is. You drive it forward say 100 pulses, but without any feedback you have no idea if there was any slip or overrun. This is called open loop control.
However, both of these methods are measuring/driving the rotation of the motor. What happens if the wheel doesn't have enough grip and slips and does a sort of burnout. For this reason, I have seen some maze robots use an old mouse to measure the distance the robot has actually travelled. This was not necessarily very accurate over long distances but was a cheap way of measuring distance travelled.

If they go down the route of interfacing to USB mouse directly to ATMEGA then they need a USB host solution-  this has already been done (mainly in software)-see https://courses.cit.cornell.edu/ee476/FinalProjects/s2007/blh36_cdl28_dct23/blh36_cdl28_dct23/

An old PS2 mouse is easier to interface to Arduino.  There is documentation and library at http://playground.arduino.cc/ComponentLib/Ps2mouse

Obviously that depends on if OP has ps2 mouse , USB mouse is more common. For the USB  related  link I gave the hardware part I would say are easier to get.

@sa_leinad, your suggestion is sound. The type of mouse is not as important if one is willing to dissect to a board level. I've dissected a mouse to use the spoked wheel inside which has a properly aligned optical trigger pair, along with the plastic structure to keep things in place. Counting pulses and direction over a known course, with the appropriate math would serve as a useful distance measuring device. Discarded printers also contain linear and rotary encoders with opto-pairs, but harder to use in a robot!

@fred_dot_u has brought up a good point - if you can get your hands on some of the really old mice that have the ball inside (instead of the red optical sensor) there are two quadrature encoders (slotted wheel and optical sensor, one from the x direction and the other from the y direction) that can be harvested from the mouse.

In modern mice, there is a quadrature encoder in the scroll wheel. Here are some links on how to harvest the encoders: http://www.seattlerobotics.org/encoder/200311/johnson/Mousebot.html http://www.boondog.com/tutorials/mouse/mouseHackBeforeWeb.htm

@sa_leinad, the funny thing about your reply to my comment was that I was referring to the mouse wheel and was ambiguous in my description. I have three mouse wheels harvested with the circuit board and mouse housing. By keeping the parts together, it allows easy access for wiring and mechanical placement too. The unwanted portions can be cut free, reducing the size of the bundle to be installed, while the solder pads on the circuit boards facilitate the wiring. Your link is very supportive of the OP's purpose.

You could add a rotary encoder to a motor yourself. Thought this is not as convenient as buying an all in one solution.
You can even build your own by making a disk with holes at regular intervals, and using an IR led, phototransistor pair on either side of the disk. You can even get all in one photo-interruptors. You could get them from an old computer-mouse. You might even be able to use the wheel/disk in it.
Another option is to add a magnet to the wheel, and a hall-effect sensor to the body. That way you can count the number of revolutions. (Though you probably want higher resolution than once per revolution).

how do you determine the accuracy of the hand built rotary encoder?

@yabbadabba - the ultimate accuracy mostly comes from accurately knowing the distance traveled per revolution of the wheel, for example you can measure over long distances, but you have to worry about slipping and straightness of path.  There can also be issues with regularity of spacing and eccentricity of the pattern relative to the shaft (or the wheel itself relative to the axle) but while those are serious concerns in say, a CNC machine tool, with moderate care they will probably not be problematic in a maze robot.

@ChrisStratton "probably not be problematic in a maze robot". Its not clear to me too-if it would definitely be a problem


text:
Male header pins on Arduino Uno
On my board, there are 12 (2 groups of 6, each group consistent of 3 rows of 2 pins) weird male header pins. What are these, and how would you use them?

These are the In System Programming (ISP) pins. They are used to program the microcontroller without using the bootloader.
The bootloader is a program already loaded into the flash of the microcontroller that allows the program to be loaded into the microcontroller through the Tx & Rx serial lines and hence not requiring a programming device.
Using the ISP can be useful when:

The bootloader program doesn't exist in the microcontroller such as on a new chip.
The bootloader is corrupted.
Your program is just that little bit too big and you wish to gain the couple hundred bytes (0.5KB) that is otherwise used by the bootloader.

The standard connection for the ISP is a 100 mil 6-pin header (2x3).

There are two ISP headers on the Arduino Uno because there are actually 2 microcontrollers on the board. There is the main microcontroller (aka the ATmega328P) which is used to execute the program you load into the Arduino board. The second microcontroller (ATmega16U2 or ATmega8U2) is used as a USB interface - converting the USB signals into serial data that is connected to the ATmega328P's UART (ie. Tx & Rx).

The following document details the ISP and gives descriptions of the pins used on the ISP header and how to interface them with the microcontroller etc.:
[PDF] AVR: In-System Programming - Atmel

EDIT: As Majenko correctly points out, the 2x3 ISP header closest to the ATmega328P can also be used to connect sensors and controllers that communicate using the Serial Peripheral Interface (SPI).
More information on the Serial Peripheral Interface and the SPI Library can be found at: https://www.arduino.cc/en/Reference/SPI

The 2x3 by the 328P still needs a slave select or chip select supplied by another pin.

The one by the USB connector is ICSP for the USB interface chip. The other is ICSP for the main chip and doubles as the (now standard) SPI interface for shields.

https://www.arduino.cc/en/Reference/SPI

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


text:
Comma between two values in a macro
I am working on a project involving an Aduino and screen.
As i was going through the u8glib (Arduino Monochrome Graphics Library for LCDs and OLEDs), something caught my attention:
#define U8G_ESC_DLY(x) 255, ((x) & 0x7f)
#define U8G_ESC_CS(x) 255, (0xd0 | ((x)&0x0f))

How can i interpret this macro for a given x value ?

Macro's aren't really code. They just work on the plain text. Just look at them as if they are a "find and replace" function in a text editor.

How can i interpret this macro for a given x value ?

As normal. First expand the macro, and then worry about what the comma means in context. In an expression the result is the expression on the right of the comma. In a function call it stands in for two arguments. Just look at where it's used and that's what it will mean.

U8G_ESC_DLY(10),              /* delay 10 ms */
so in a concept like this, i can omit the left side of the comma.But can you elaborate on the function call part ? How can you define a function like this in the first place ?

somefunctionthattakestwoargs(SOMEMACROWITHACOMMA)

The library uses that to create a list of commands to initialize the display. See where it is used. As you can see, they store an array of commands that have to be send to initialize. So in this case, send 255 and then send the last x (with the first bit set to zero).


text:
How to pass a string pointer to a function
I'm working on a project, where I wish to use pointers. I had a very quick overview of using pointers in C in collage, but I don't know how to use them.
I want that function uses input String (answer) as pointer.
Calling function in setup block
void setup() {
    sendCommand("AT+RST\r\n", 5000, DEBUG, "ready");
    sendCommand("AT+CWSAP_CUR=\"mega\",\"password123\",10,3\r\n", 4000, DEBUG, "OK");
}

String sendCommand(String command, const int timeout, boolean debug, String *answer)
{
    String response = "";

    Serial1.print(command); // send the read character to the esp8266

    long int time = millis();

    while ((time + timeout) > millis())
    {
        while (Serial1.available())
        {
            // The esp has data so display its output to the serial window
            char c = Serial1.read(); // read the next character.
            response += c;
        }

        //Waiting for the right answer and breaking a while loop
        if (response.indexOf(*answer) > 0)
        {
            break;
        }

    }

    if (debug)
    {
        Serial.print(response);
    }

    return response;
}

Format your code nicely. Many people simply won't bother to spend the extra time to read code if you've made it hard to read, and why should they? 2. If you don't understand well how pointers work and you want to use them as a solution to a problem, you have an XY problem that you need to fix.

Give this webpage a read, it fully explain how strings in c++ work, even down to the memory handling. https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/

What you have there are not String objects, but string literals. Their type is const char *
You should avoid using String objects if at all possible. Instead use character arrays.
To get a character array out of a function it is best to create one outside your function and pass it to the function as one of the parameters. The return value of the function can then be a status value indicating if the call worked or not.

see https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/ for more info.

If you want to use the String type, have a variable String rdy="ready"; and pass &rdy (the address of the variable). Same with "OK".
I assume you want to use a pointer to avoid copying?
As you are already using C++ techniques (String is C++, not C), you might want to consider to pass rdy (not a pointer), and to write const String &answer in the sendCommand parameter list (meaning: reference to a string, which will not be modified), and omit the * when using the parameter. Passing references is quite similar to pointers: no copying involved. The additional benefit is that you may even write sendCommand("AT+RST\r\n", 5000, DEBUG, "ready"); then... the "ready" is automagically converted into a String, and passed via reference.

This is what most people are wanting as an answer. I came here looking for examples of what could be used for various Serial LCD wrappers, the ones where control characters need to be inserted and then a passed string decomposed into bytes for individual write().

You can pass parameters to functions by reference by value or 'by pointers'.
Passing a parameter by value means that the function has a separate copy of the parameter so this is more expensive in terms of memory.  It also means that any changes you make to the parameter inside the function are not reflected outside the function, they are two separate variables after all.
Passing by reference in C/C++ is done by adding a & after the parameter's type, (int& byRef).  This means that you are using the same variable inside and outside of the function.  If you want to prevent the function changing the value then you set the parameter to be a constant reference. const int& constByRef
There is a third method which is passing a pointer.  This is very useful for parameters that are a few bytes in size, i.e. strings and structures char* ptr.  When you pass a pointer it is passed by value, you can modify the pointer or the data it points to.  Since a pointer is usually only the word size of the processor it is only as expensive as passing an int parameter.
When you pass a const char* cPtr you can not modify the value of the pointer, but you can modify the value of the data pointed to.  This type of parameter will let you pass in string literals.
To make you code cleared always write functions to accept constant parameters.  If the parameter is larger than a word pass it by reference unless its an array (including char*) in which case pass it by pointer.  If in doubt it should be a constant reference to start with.  Sometimes embedded constraints affect these rules.


text:
Neopixels with I/O expander
Because I have no pins available on my Wemos D1 mini, I want to drive my Neopixel ring from a MCP23008 I/O expander.
I'm trying to run the 'simple' example from the Adafruit_neopixel library. How do I declare the Neopixel pin number when using say pin 0 on the MCP23008 - or is this impossible?

I don't think that will be an option. The NeoPixel parts need very tight control of the timing in order to work, if the pin timing is wrong by 100 us the wrong data will get latched in.
Can you move some other functions / pins onto the IO expander and then drive the neopixels directly from the processor?

Thanks Andrew. I thought all chained rgb leds with processors were called neopixels. What I have is 10 x 'WS2812B WS2811 Mini board IC 10mm*3mm DC5V SMD 5050 RGB Leds'. My mistake. Not sure if that makes a difference. Appreciate your thoughts re moving other functions to expander though am using i2c, SPI and need RX/TX for nextion display

NeoPixel is the Adafruit marketing name for WS2812 LEDs. You only need 1 pin, exactly what you can move I can't answer without a lot more detail on your system but your best bet would be something slow, a chip select pin or something like that. If your SPI device has a select that would be the obvious choice (or if it's the only SPI device you may be able to wire the select low all the time and save a pin, some devices let you do that, some don't)

I think you will need to write your own library.  This isn't as bad as it seems.  If the library uses analog write then it won't work, because I don't think you can do PWM with that expander.
The library writes directly to pins.  You need to intercept this behaviour and tell the library to tell the MCP230008 to write to the pin.  I haven't seen the library I question, but this should be straight forward.
If you take the existing Adafruit library and find where it writes to a pin.  Rather than calling digitalWrite it needs to call expanderWrite(pin, state).  Every instance of pinMode() needs replacing with explanderPinMode(pin, mode) Then write yourself those two functions that use I2C/SPI to set the IOX's registers to implement what  you need.
The IO Expander is not going to be a good idea if the library requires critical accurate timing, because of the lag of telling the IOX to do things.  An alternative is to use another D1 as the IO expander.

look at the code for Neopixels: https://github.com/adafruit/Adafruit_NeoPixel/blob/master/Adafruit_NeoPixel.cpp Both the Adafruit Neopixel and the FASTled libraries are highly optimized for the timing specific RGB leds. Leds with a PWM signal would be no problem, there are many modules that can do PWM. Leds with a clock signal are no problem, they don't use specific timing. It's the timing specific protocol of Neopixels that is a problem.

Thanks Code Gorilla. I thought all chained rgb leds with processors were called neopixels. What I have is 10 x 'WS2812B WS2811 Mini board IC 10mm*3mm DC5V SMD 5050 RGB Leds'. My mistake. Not sure if that makes a difference re timing issue. ! don't have enough knowledge to amend the library - but many thanks for your suggestions

What library are you using to control the LEDs?

library is 'Adafruit_NeoPixel' - simple working ide sketch below:
#include <Adafruit_NeoPixel.h>
#define PIN 2       // pin used for Neopixel
#define NUMPIXELS 1 // No. of NeoPixels attached
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
void setup() {
pixels.begin(); // Initializes the NeoPixel library.
}
void loop() {
pixels.setPixelColor(0, pixels.Color(255,0,0)); pixels.show();delay(500);
pixels.setPixelColor(0, pixels.Color(0,255,0)); pixels.show();delay(500);
}

Ooops - ide looks a mess - can't see how to include file as an attachment. Can you read it?


text:
Convert my if loop code into a switch/case statement
I have made a project where in photosensors constantly read value and if laser is cut by external object, then it beeps the buzzer.
A switch case would make it easy, as suggested by some people.
I have written my short code below, can you kindly help me change it?
Converting all if loops into a switch/case statement.
 int sensorPin = A0;
 int sensorPin1 = A1;
 int sensorPin2 = A2;
 int sensorPin3 =  A3;
 int sensorValue0 = 0;
 int sensorValue1 = 0;
 int sensorValue2 = 0;
 int sensorValue3 = 0;
 const int BUZZER = 9;
 const int BUZZER1 = 7;
 const int BUZZER2 = 8;
 const int BUZZER3 = 5;

void setup() {
 Serial.begin(9600);
 pinMode(BUZZER, OUTPUT);
 pinMode(BUZZER1, OUTPUT);
 pinMode(BUZZER2, OUTPUT);
 pinMode(BUZZER3, OUTPUT);
 // put your setup code here, to run once:
}

void loop() {
  sensorValue0 = analogRead(sensorPin);
  sensorValue1 = analogRead(sensorPin1);
  sensorValue2 = analogRead(sensorPin2);
  sensorValue3 = analogRead(sensorPin3);
  Serial.println(sensorValue0);
  delay(100);

  if (sensorValue0>920)
   noTone(BUZZER);
  else
   tone(BUZZER, 500);

  if (sensorValue1>850)
   noTone(BUZZER1);
  else
   tone(BUZZER1, 300);

  if (sensorValue2>850)
   noTone(BUZZER2);
  else
   tone(BUZZER2, 700);
}

You cannot use a switch in this case , because of the > operator in the if statements and the differentn variables (sensorValue0, 1 and 2). Also, are you missing a buzzer for sensorValue3?

@SDsolar, The help center says that code reviews are on-topic. The only thing this OP did wrong was to not include the project-critique tag.

A switch can only select different discrete values from a single variable. Since you have multiple variables and aren't looking for discrete values you have to use if not switch.

A switch statement wouldn't be appropriate in this case.
You could optimise the code by adding a function that did the work for you and made the main loop look nicer.
void readValue (const int& sensorPin, const int& limit, const int& buzzerPin, const int& frequency)
{
  const int value = sensorValue0 = analogRead(sensorPin);
  if (value > limit)
  {
    noTone(buzzerPin);
  }
  else
  {
    tone(buzzerPin, frequency);
  }
}

That way you could add as many buzzer and sensors as pins allowed.

By the way, the above is total overkill I'm just trying to offer you a different way of thinking about you problem.  You could also abstract the sensor and buzzer pins away and hide them within this class, just passing an enum in and looking them up in a 2 arrays.  Again its overkill, but fun, if you're twisted :)

Actually, you cannot really rewrite this, due to the > operator instead of the == operator.
Also you are checking three different variables, and only one variable can be used to check in a switch statement.
However, what you can do is to create a function with parameters like:
void set(int sensorValue, int value, int buzzer, int frequency)
{
  if (sensorValue > value)
  {
       noTone(buzzer);
  }
  else
  {
       tone(buzzer, frequency);
  }
}

and call:
 set(sensorValue0, 920, BUZZER, 500);
 set(sensorValue1, 850, BUZZER1, 300);
 set(sensorValue2, 850, BUZZER2, 700);
 set(sensorValue3, ...); // I think you miss this one

Since your conditions looks like :
bool condition = variable > someValue;

The value of your variable (i.e. sensorValue) should therefore be continuous.
However, the switch statement is used when the value of our variable is discrete.
You can't consequently use switch statements in your code.

Just for fun, here yet another way to handle the issue: Create a C++ class. This code might seem a bit longer than your original code, but the advantage is if you want to add more functionality, you only have to modify the class.
class Sensor {
public:
    Sensor(uint8_t analog_pin, uint8_t buzzer_pin, uint16_t threshold, uint16_t tone_duration)
        : analog_pin(analog_pin), buzzer_pin(buzzer_pin), threshold(threshold), tone_duration(tone_duration)
    {
    }
    void setup() {
        pinMode(buzzer_pin, OUTPUT);
    }
    void loop() {
        sensor_value= analogRead(analog_pin);
        delay(100);
        if (sensor_value> threshold)
            noTone(buzzer_pin);
       else
           tone(buzzer_pin, tone_duration);
    }
protected:
    uint8_t analog_pin, buzzer_pin;
    uint16_t threshold, sensor_value, tone_duration;
};

Then, just create an array of Sensor objects:
Sensor sensors[] = {
    Sensor(A0, BUZZER1, 920, 500),
    Sensor(A1, BUZZER2, 850, 300),
    Sensor(A2, BUZZER3, 850, 700)
};
const uint8_t num_sensors = sizeof(sensors) / sizeof(sensors[0]);

void setup() {
    for (int i = 0; i < num_sensors; i++) {
        sensors[i].setup();
    }
}
void loop() {
    for (int i = 0; i < num_sensors; i++) {
        sensors[i].loop();
    }
}

" Switch case would make it easy, as suggested by some people."
That's a great example of why free advice can be quite expensive, :)
Unless you are doing something unique, you are better off with your current approach.
edit: with that said, I can see cases where a switch / case structure can be helpful. For example if you need to compare multiple variables through a consistent set of thresholds, one way to do it without making the code too difficult to read would be something like this:
THRESHOLD_TypeDef threshold(uint16_t val) {
  if (val < VAL1) return THRESHOLD1;
  if (val < VAL2) return THRESHOLD2;
  ...
  if (val < VALn) return THRESHOLDn;
}

where THRESHOLD_TypeDef is an enumerated type.
and in your code you can write something like this:
   switch (threshold(myval)) {
   case THRESHOLD1: do_something1(); break;
   case THRESHOLD2: do_something2(); break;
   ...

Its advantage is obviously better readability and consistency: you can apply the same function on different variables to generate a consistent set of "classification".
Its disadvantage is also obvious: for each threshold(), you can only test one set of classification. But you can always create multiple functions to be applied to different variables.


text:
connect gy512 is not visible by i2c bus
I am a newbie. Please help to make gy512 visible on i2c interface.
i did
sda - a4
scl - a5
vcc - 5v
gnd - gnd
I have used i2c sticker scatch and use PC monitor.

What is a GY512? I could only find the GY521, which seems to be a breakout board for the MPU6050. And I guess you have used the standard I2C scanner sketch. Have you tried adding pullup resistors to the I2C lines (like 4.7kOhm)?

This question is hard to solve with so much info missing. Could you please add more info and perhaps some pictures.


text:
Low cost IR sensor based finger gesture recognition controlled wheelchair
I am doing a project in which three IR sensors are used for getting three fingers's gesture to control the movements (left, right, forward, backward) of two motors.
The threshold value of IR sensor output is 450 mV for getting  signal to be passed.
I am not understanding how to design different conditions for different movements of motors
int firstanalogPin = 1;     // Infrared Sensor (Right lead) connected to analog pin 1

int val1 = 0;           // variable to store the value read

int enablePin = 1;
int LeftMotorForward = 10; // Pin 10 has Left Motor connected on Arduino boards.
int LeftMotorReverse = 9; // Pin 9 has Left Motor connected on Arduino boards.

int RightMotorForward = 12; // Pin 12 has Right Motor connected on Arduino boards.
int RightMotorReverse = 13; // Pin 13 has Right Motor connected on Arduino boards

void setup()
{
    pinMode(LeftMotorForward, OUTPUT);  // initialize the  pin as an output.
    pinMode(RightMotorForward, OUTPUT);  // initialize the  pin as an output.
    pinMode(LeftMotorReverse, OUTPUT);  // initialize the  pin as an output.
    pinMode(RightMotorReverse, OUTPUT);  // initialize the  pin as an output.
    Serial.begin(9600);          //  setup serial
}

void loop()
{
    val1 = analogRead(firstanalogPin);    // read the input pin
    Serial.println(val1);                           // debug value

    if (val1 >700) // forward
        digitalWrite(LeftMotorForward, HIGH);
    else
        digitalWrite(LeftMotorForward, LOW);   // turn the Left Motor ON
    if (val1 >700)
        digitalWrite(RightMotorForward, HIGH);// turn the Right Motor ON
    else
        digitalWrite(RightMotorForward, LOW);// turn the Right Motor ON
}

you need only one if-else block .... just turn on both motors in the first if block

What is it that you have a problem with?  You have made the motors move forward.  So if you want just 3 different exclusive motions Forward, Left, Right.
What you could do is have 1 finger control the direction, 1 finger control left and 1 control right.
   OFF       ON
F1 Forwards  Backward
F2 Left Off  Left On
F3 Right Off Right On

So to go straight forwards F2 & F3 have to be greater than 700.
To turn left F3 > 700 && F2 < 700  (Right motor on will make the chair turn left)
To reverse then you need F1 > 700.
etc.
Ensure that the conditions are if/else ifs otherwise its going to get messy.


text:
Help with arduino float
I am having trouble with this code:
#include <Wire.h>
#include <MPU6050.h>

MPU6050 mpu;

// Timers
unsigned long timer = 0;
float timeStep = 0.01;

// Pitch, Roll and Yaw values
float pitch = 0;
float roll = 0;
float yaw = 0;

int button_pin=5;
int button_state;
void setup()
{
  Serial.begin(115200);

  // Initialize MPU605
  while(mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
  {
    Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
    delay(500);
  }

  // Calibrate gyroscope. The calibration must be at rest.
  // If you don't want calibrate, comment this line.
  mpu.calibrateGyro();

  // Set threshold sensivty. Default 3.
  // If you don't want use threshold, comment this line or set 0.
  mpu.setThreshold(3);

  pinmode(button_pin,INPUT)
}

void loop()
{
  int button_state=digitalRead(button_pin)

  timer = millis();

  // Read normalized values
  Vector norm = mpu.readNormalizeGyro();

  // Calculate Pitch, Roll and Yaw
  pitch = pitch + norm.YAxis * timeStep;
  roll = roll + norm.XAxis * timeStep;
  yaw = yaw + norm.ZAxis * timeStep;

  // Output raw
  Serial.print(" Pitch = ");
  Serial.print(pitch);
  Serial.print(" Roll = ");
  Serial.print(roll);
  Serial.print(" Yaw = ");
  Serial.println(yaw);

  // Wait to full timeStep period
  delay((timeStep*1000) - (millis() - timer));
}

But when I add this code at the end:
If (pitch <=90 && pitch => 15 && button_state =(HIGH))
{
}

I keep getting this error:

error: lvalue required as left operand of assignment

I know the issue is about the pitch part of the if. I just need to know how to fix it.

The if-statement should be if not If

Could you please post the error that you are getting.

also button_state =(HIGH) should be button_state == HIGH or more simply button_state

@sa_leinad I get this error (error: lvalue required as left operand of assignment) this iş the error I am getting

The first thing I noticed was that you had a capital I in your if-statement.
Secondly, button_state =(HIGH) should be button_state == HIGH. A single = sign means that you are assigning a value to the variable on the left - in this case button_state. It is a common mistake that I have made many times.
Also, because it is a boolean comparison, you can simplify the statement by removing the == HIGH leaving just button_state.
This would then change the if-statement to the following:
if ((pitch <= 90) && (pitch => 15) && button_state)

I have added extra parentheses for clarity/readability but they're technically not needed.

In addition to what Code Gorilla has already stated in his answer and a few additional semi-colons, your code should look something like this:
#include <Wire.h>
#include <MPU6050.h>

MPU6050 mpu;

// Timers
unsigned long timer = 0;
float timeStep = 0.01;

// Pitch, Roll and Yaw values
float pitch = 0;
float roll = 0;
float yaw = 0;

const int button_pin = 5;

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

  // Initialize MPU605
  while(mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
  {
    Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
    delay(500);
  }

  // Calibrate gyroscope. The calibration must be at rest.
  // If you don't want calibrate, comment this line.
  mpu.calibrateGyro();

  // Set threshold sensivty. Default 3.
  // If you don't want use threshold, comment this line or set 0.
  mpu.setThreshold(3);

  pinmode(button_pin,INPUT);
}

void loop()
{
  int button_state = digitalRead(button_pin);

  timer = millis();

  // Read normalized values
  Vector norm = mpu.readNormalizeGyro();

  // Calculate Pitch, Roll and Yaw
  pitch = pitch + norm.YAxis * timeStep;
  roll = roll + norm.XAxis * timeStep;
  yaw = yaw + norm.ZAxis * timeStep;

  // Output raw
  Serial.print(" Pitch = ");
  Serial.print(pitch);
  Serial.print(" Roll = ");
  Serial.print(roll);
  Serial.print(" Yaw = ");
  Serial.println(yaw);

  if ((pitch <= 90) && (pitch => 15) && button_state)
  {
      // Code goes here
  }

  // Wait to full timeStep period
  delay((timeStep*1000) - (millis() - timer));
}

You have two declarations of button_state.  This won't cause a problem because the scoping rules will mean inside loop you are using the local one and everywhere else you are using the global one.  Personally I would remove the global one since you aren't using it.
As mentioned in the comments you have mistyped the If keyword (but I think this is just on here not in you code) and you have used an assignment statement rather than a equivalence (= instead of ==).
Since you have tagged it as code review here are some minor points you might want to consider.
If a value doesn't change then you could mark it as const, this doesn't make much difference to the compiler, it already knows, but it will help you when you come back to the code next week.
  So: const int button_pin = 5;
If you only use a const int value once you might be better #defining it (more than once a const value should produce smaller code).  The pre-processor (part of the compile process) will replace the defined name with the value, but you have easier to read and maintain code.
  So: #define button_pin 5
If you #define an int then always enclose the value in brackets to protect it from "arithmetic issues" (I can't think of a better way of describing it).
  So: #define button_pin (5)

thanks for your suggestions, but still you haven't told me how to fix the error

The solution to your problem was answered by sa_leinad in the comments on you post and is covered in the second paragraph of my answer.  "you have used an assignment statement rather than a equivalence".  If you tell me you IP address I'll remote into your machine and fix your code for you if you like.


text:
Having trouble with 74HC595 and Uno
Just picked up a couple of 74HC595 shift registers to use for my Arduino Uno, and I'm having trouble getting it working 100% of the time. My code is to get a value from the Serial monitor and shift it into the register. The issue is that bits 4 and 5 are always on no matter what I put into the monitor, but when I clock a 0 into the register during setup(), it works as expected, i.e. all LEDs go off
Here is the code:
int dataPin = 2;
int latchPin = 3;
int clockPin = 4;

void setup() {
    Serial.begin(9600);
    pinMode(dataPin, OUTPUT);
    pinMode(latchPin, OUTPUT);
    pinMode(clockPin, OUTPUT);

    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, 0);
    digitalWrite(latchPin, HIGH);
}

void loop() {
    if(Serial.available()) {
        digitalWrite(latchPin, LOW);
        shiftOut(dataPin, clockPin, MSBFIRST, Serial.read());
        digitalWrite(latchPin, HIGH);
    }
}

Is it the code that is wrong? Do i have a busted shift register? Or something else?
Thanks

You may have incorrect wiring. Maybe you should show it?

I would be interested if you changed your code to always set bits 4 & 5 to 0. That is, perform the serial read first, bitwise AND the result with 0xFFE7 and then shift out the value.

Serial.read() is going to give you ASCII codes.  So when you send 1 from the serial monitor the Arduino receives 49.  Note that the ASCII code for a digit is the same as the digit plus 48, so that sets bits 4 and 5 high.
You can use Serial.read() - '0' to get the actual number from the ascii code.


text:
Converting my delays to millis for smoother operation
I need help converting my code to change out the delay() command into the millis() command for smoother operation.
Currently the code only moves after the delay is up. I would like the codes to run simultaneously.
This is my codes
#define aref_voltage 3.3
#include <Servo.h>
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
Servo Servo1;
int led = 13;
int sw = 3;
int bz = 14;
int ldr = A1;
int lv = 0;
int rly = 7;
int buttonState = 0;
int servoPin = 8;
// the setup routine runs once when you press reset:
void setup()
{
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
  pinMode(sw, INPUT);
  pinMode(ldr, INPUT);
  pinMode(bz, OUTPUT);
  pinMode(rly, OUTPUT);
  digitalWrite(rly, LOW);
   Servo1.attach(servoPin);
  analogReference(EXTERNAL);
  Serial.begin(115200);

   if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3D for 128x64
   Serial.println(F("SSD1306 allocation failed"));
   for(;;);
  }
}
void loop()
  {
  lv = analogRead(ldr); // read the value off the LDR
  Serial.print("LDR Value is: ");
  Serial.println(lv);
  delay(100);

  buttonState = digitalRead(sw); // Check switch 1 or 0
  Serial.println(buttonState);   //Show the state of pushbutton on serial monitor
  delay(100);

    while ( (lv >= 150) && (buttonState == HIGH) )
{
    delay(1000);
    display.clearDisplay();
    display.setTextSize(2);
    display.setTextColor(WHITE);
    display.setCursor(0,0);
    display.println("Relay On! ");      // here the message is inside the ""
    delay(1000);
    display.display();

    digitalWrite(rly, HIGH);//relay on 1 min
    delay(6000);
    tone(bz, 1500);//buzzer on for 30 sec
    delay(3000);
    digitalWrite(led, HIGH);//led flash at 1 Hz
    delay(3000);
    digitalWrite(led, LOW);
    delay(3000);

    digitalWrite(led, HIGH); // led 2 kHz
    delay(3000);
    digitalWrite(led, LOW);
    delay(3000);
    tone(bz, 2000); //buzzer at 2 khz
    delay(3000);
    noTone(bz);

    delay(2000);
    display.clearDisplay();
    display.setTextSize(2);
    display.setTextColor(WHITE);
    display.setCursor(0,0);
    display.println("Tank 2 Filled! ");      // here the message is inside the ""
    delay(1000);
    display.display();

    digitalWrite(rly, LOW); // relay low
    digitalWrite(led, HIGH);
    delay(5000);            // led flash 4Hz
    digitalWrite(led, LOW);
    delay(5000);

   Servo1.write(45); // Make servo go to 45 degrees
   delay(1000);

   Servo1.write(135); // Make servo go to 135 degrees
   delay(1000);

   Servo1.write(0); // Make servo go to 0 degrees
   delay(1000);
    break;
}
   if (buttonState == LOW)
  {
    digitalWrite(rly, LOW); // relay off
    digitalWrite(led, LOW); // led off
    delay(500);
   Servo1.write(0);     // Make servo go to 0 degrees
   delay(1000);
    noTone(bz); // buzzer off

  }
  }

What exactly is your problem in doing that? Have you understood how the millis() function is used? Do you know, what an FSM (Finite State Machine) is? If not, you should really search for it, since that concept will be incredible helpful in implementing, what you want.

The codes only move after the delay is up, i would like the codes to run simultaneously.

Yes, thats a very general description, of what you want. But it doesn't explain, what exactly the problem is. What have you tried so far? Is there something, that you don't understand in the concept of non-blocking code like in the BlinkWithoutDelay example (thats the example explaining millis())? There is already tons of tutorials on the web about this and we need to know, how we can help you better than these.

You have posted a goal, not a question.This site is not a free coding service. You should do a Google search on "Arduino blink without delay", read one of the various tutorials that search finds, and then attempt to refactor your code yourself.

ok thanks for the info

your code is cluttered with useless comments ... for example //led flash at 1 Hz comments a section of code that does not operate at 1 Hz ... same thing with a lot of the other comments

you need to think clearly about how your code flows ... as it stands now, it is filled with silly comands (my apologies for the choice of words, but i cannot think of any other word) ... example in pseudo code: relay ON, wait 6 seconds, buzzer ON, wait 3 seconds, led ON, wait 3 seconds,  led OFF, wait 3 seconds, etc. etc.  ..... simpler code would be relay ON, buzzer ON, led ON, wait 3 seconds,  led OFF, wait 3 seconds, etc. etc

@DuncanC his goal is to get rid of delays and make the code run smoothly, I thought he explained that.

A while back I wrote an answer to another question about non-blocking programming, using "maybe-do" functions - functions that maybe do something if the conditions for doing it are met, typically a time-interval having passed. @nickgammon's excellent article (linked in his answer to this question) shows a similar structure that evaluates the condition within loop() rather than within the maybe-do/action function, as I did in my answer. Both ways work equally well.
It will be a good exercise to play with the BlinkWithoutDelay example sketch, and even write a couple of your own sketches that follow that general format. But soon you'll get tired of writing all of those if( (millis() - previousMills) >= someInterval){ expressions and the bookkeeping of the various previousMillises that goes with them - not to mention debugging the results of the inevitable typos! )-:
Once you've got the hang of:
is (current time - time when we previously acted) >= action interval{
   do the action;
   save the current time as the previous time;
}
// again, for the next action
// yet again, for each remaining action

, consider using a timer library such as SimpleTimer. Its job is to maintain all that bookkeeping for you, and to call your action functions at the right time.
You need to know a few things to use it - some of the same few things you needed to know to write code the previous way, but the more tedious parts will be done for you:

How to make a set of timers;
How to make an action function (called a 'callback function');
How to set an interval (one-time or repeating) that the action- or callback-function will get called.
How to run the timers so they can do their jobs.

How to make timers:

First, you need the library: Visit this github page and click the green "Download Code" button (it's really a down-arrow, not the word "download"). In the menu that appears, click "Download ZIP".
Open the file that you receive, "Arduino-SimpleTimer-master.zip" (how you do this depends on your computer's operating system). In the .zip file you'll find this folder structure:
Arduino-SimpleTimer-master --- SimpleTimer --- (some folders and files)
Drag the 'SimpleTimer' folder into the 'libraries' folder within your Arduino sketch folder. This library can serve every sketch you write from now on.
Add the following include file to the top of your sketch:
#include <SimpleTimer.h>
Create a global set of timers:
SimpleTimer myTimers;  // creates 10 timers and makes them available for use.

How to make a callback function - the function that runs your LED, stepper motor, or whatever other action you need taken at a certain time:

A callback function does whatever is necessary to complete the timed task, and nothing more. For example, it might toggle an LED off if it is on, or on if it is off.
An action function takes no arguments and returns no value. It must have the type:
void toggleLED(void);
Of course, you get to name your functions whatever you like.

How to set an interval. There are a number of ways, but you're likely to use these two for nearly everything - repeating, or one-time:

myTimers.setTimeout(time, toggleLED); sets a one-time timer that
will call my `toggleLED()' function once only, after "time" milliseconds. It returns the timer number that will be used. Mostly you can ignore that value for now.
myTimers.setInterval(time, toggleLED); sets a repeating timer that will keep calling my toggleLED() function every "time" milliseconds, for as long as the sketch runs. It also returns the timer number, and again, you can ignore that value for now.

How to run the timers.

The timer library needs to be called frequently for your functions to get called at fairly precise intervals. Your loop() function should call myTimers.run() each time it runs.
loop() should not do anything that takes very long, nor call any function that can take very long. Long tasks will disturb the precision of the timing with which your callback functions get called.
Your loop function should look like:

void loop(){
   myTimers.run();
   // maybe some other fast code here
}

The .run() function checks each of your timers, and for every one whose time has expired, it calls its callback function (the one you specified when you called .setInterval() or .setTimeout()). This is how the timer library does its work, and why you need to call it frequently.

Now let's look put it all together in a sample program to blink 2 LED's at different intervals using SimpleTimers:
// SimpleTimer demo program
//    Blink 2 LEDs at different rates for 15 seconds, then turn off both LEDs and stop.

#include <Arduino.h>
#include <SimpleTimer.h>

/*****< Definitions >*****/
#define LED1    13  // the on-board LED
#define LED2    12  // an external LED

/*****< External and Global Declarations >*****/
SimpleTimer myTimers;       // define a set of timers
bool doHalt = false;            // a flag to tell loop() to stop

/*****< Local Function Prototypes >*****/
void toggleLED1(void);      // function to toggle the state of LED1
void toggleLED2(void);      // function to toggle the state of LED2
void setHalt(void);         // function to set the halt flag

void setup()
{
    // Set the pin modes for our two LEDs:
   pinMode(LED1, OUTPUT);
   pinMode(LED2, OUTPUT);

   // Turn off the LEDs:
   digitalWrite(LED1, LOW);
   digitalWrite(LED2, LOW);

    // Set up the blink intervals
    myTimers.setInterval(800L, toggleLED1); // start timer to blink LED1 slowly
    myTimers.setInterval(300L, toggleLED2); // start timer to blink LED2 rapidly

    // Stop the program after 30 seconds.
    myTimers.setTimeout(15*1000L, setHalt); // start timer to halt the program
}

void loop() {
    myTimers.run();                 // keep calling the timers as often as possible

    if( doHalt ){                       // if the halt flag is set,
        // Turn off the LEDs:
       digitalWrite(LED1, LOW); //    shut off the leds,
    digitalWrite(LED2, LOW);

    // Hang here, doing nothing
        while(1)                            //    and hang here forever.
            ;
    }
}

// Toggle the state of LED1
void toggleLED1(void){
    bool isOn = digitalRead(LED1);

    digitalWrite(LED1, !isOn);
}

// Toggle the state of LED2
void toggleLED2(void){
    bool isOn = digitalRead(LED2);

    digitalWrite(LED2, !isOn);
}

// Set the halt flag to stop 'loop()'
void setHalt(void){
    doHalt = true;
}

/***  end  ***/

This program does everything BlinkWithoutDelay does, but without the bookkeeping and the mechanics of calling your action functions. Those are all taken care of by the SimpleTimer library, leaving you free to concentrate on what your program is meant to do.

Your delays are making the program jerky, so you have to get rid of them. :)
I have a lengthy discussion about this on my own web site, but basically you need to restructure so that you use a "state machine" and instead of delaying, make a note of the current time (using millis() function) and then do the next step when the time is up.
Just as an example, when you bake a cake you don't stop what you are doing for an hour and stare at the oven while it cooks, do you? You make a note of the time, and come back when the time is up.
One of the Arduino tutorials Blink without delay has an example of doing that.
The example code is (initial comments removed):
// constants won't change. Used here to set a pin number:
const int ledPin =  LED_BUILTIN;// the number of the LED pin

// Variables will change:
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change:
const long interval = 1000;           // interval at which to blink (milliseconds)

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop() {
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the difference
  // between the current time and last time you blinked the LED is bigger than
  // the interval at which you want to blink the LED.
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

This won't be a one-line change. You have to re-think how you go about handling time delays.