message:
Writing to a SPI memory

Recently I salvaged a BIOS chip (EN25QH16) which has 2 Megabytes of memory (8192 pages, 256 bytes/page). I followed this [instructables](http://www.instructables.com/id/How-to-Design-with-Discrete-SPI-Flash-Memory/) and it works. I double checked the opcodes because the code is for a `Winbond` chip, mine is `Eon` and of course, they're the same (standards?). All commands worked as it should. I modified the code that writes `Hello World` string to a page. I tried the command but it returns (from the memory) `Hello Worlb`. This is the snap of the serial monitor:

[![serialmonitor][1]][1]
  [1]: https://i.stack.imgur.com/YAXLX.png

I erased the chip just to make sure and ran the command `test_write` (which I added). It wrote `48 65 6c 6c 6f 20 57 6f 72 6c 00 62 03 0b 00 0b 00` which is in ASCII `Hello Worlb` and I don't know why that happened. Btw this is the modified code:

    /*
        windbond_serial_debug.cpp
        A simple program for the Arduino IDE to help familiarize you with
        using WinBond flash memory; can also be used to download the entire
        contents of a flash chip to a file via a serial port interface.

        Important bits of the code: the low-level flash functions (which
        implement the timing diagrams in the datasheet), and a simple
        serial-port command interface that allows you to talk to your
        UNO with any generic terminal application (even the command line).

        Copyright 2014, Peter J. Torelli

        This program is free software: you can redistribute it and/or modify
        it under the terms of the GNU General Public License as published by
        the Free Software Foundation, either version 3 of the License, or
        (at your option) any later version.

        This program is distributed in the hope that it will be useful,
        but WITHOUT ANY WARRANTY; without even the implied warranty of
        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
        GNU General Public License for more details.

        You should have received a copy of the GNU General Public License
        along with this program.  If not, see <http://www.gnu.org/licenses/>

    Revisions:
        rev 2 - 21-SEP-2014.
        User 'fiaskow' pointed out that driving the WEL instruction after
        program and erase w/o waiting for the op to finish may be corrupting
        execution. Removed this code (also not needed b/c the WEL is already
        cleared after page write or chip erase).
    */

    #include <SPI.h>
    // SS:   pin 10
    // MOSI: pin 11
    // MISO: pin 12
    // SCK:  pin 13

    // WinBond flash commands
    #define WB_WRITE_ENABLE       0x06
    #define WB_WRITE_DISABLE      0x04
    #define WB_CHIP_ERASE         0xc7
    #define WB_READ_STATUS_REG_1  0x05
    #define WB_READ_DATA          0x03
    #define WB_PAGE_PROGRAM       0x02
    #define WB_JEDEC_ID           0x9f

    /*
     * These global variables enable assembly of the user serial
     * input command.
     */
    boolean g_command_ready(false);
    String g_command;

    /*
     * print_page_bytes() is a simple helperf function that formats 256
     * bytes of data into an easier to read grid.
     */
    void print_page_bytes(byte *page_buffer) {
      char buf[10];
      for (int i = 0; i < 16; ++i) {
        for (int j = 0; j < 16; ++j) {
          sprintf(buf, "x", page_buffer[i * 16 + j]);
          Serial.print(buf);
        }
        Serial.println();
      }
    }

    /*
    ================================================================================
    User Interface Routines
    The functions below map to user commands. They wrap the low-level calls with
    print/debug statements for readability.
    ================================================================================
    */

    /*
     * The JEDEC ID is fairly generic, I use this function to verify the setup
     * is working properly.
     */
    void get_jedec_id(void) {
      Serial.println("command: get_jedec_id");
      byte b1, b2, b3;
      _get_jedec_id(&b1, &b2, &b3);
      char buf[128];
      sprintf(buf, "Manufacturer ID: xh\nMemory Type: xh\nCapacity: xh",
        b1, b2, b3);
      Serial.println(buf);
      Serial.println("Ready");
    }

    void chip_erase(void) {
      Serial.println("command: chip_erase");
      _chip_erase();
      Serial.println("Ready");
    }

    void read_page(unsigned int page_number) {
      char buf[80];
      sprintf(buf, "command: read_page(xh)", page_number);
      Serial.println(buf);
      byte page_buffer[256];
      _read_page(page_number, page_buffer);
      print_page_bytes(page_buffer);
      Serial.println("Ready");
    }

    void delayed_read_all_pages(void) {
      delay(5000);
      read_all_pages();
      }

    void read_all_pages(void) {
      Serial.println("command: read_all_pages");
      byte page_buffer[256];
      for (int i = 0; i < 4096; ++i) {
        _read_page(i, page_buffer);
        print_page_bytes(page_buffer);
      }
      Serial.println("Ready");
    }

    void write_byte(word page, byte offset, byte databyte) {
      char buf[80];
      sprintf(buf, "command: write_byte(xh, xh, xh)", page, offset, databyte);
      Serial.println(buf);
      byte page_data[256];
      _read_page(page, page_data);
      page_data[offset] = databyte;
      _write_page(page, page_data);
      Serial.println("Ready");
    }

    /*
    ================================================================================
    Low-Level Device Routines
    The functions below perform the lowest-level interactions with the flash device.
    They match the timing diagrams of the datahsheet. They are called by wrapper
    functions which provide a little more feedback to the user. I made them stand-
    alone functions so they can be re-used. Each function corresponds to a flash
    instruction opcode.
    ================================================================================
    */

    /*
     * See the timing diagram in section 9.2.35 of the
     * data sheet, "Read JEDEC ID (9Fh)".
     */
    void _get_jedec_id(byte *b1, byte *b2, byte *b3) {
      digitalWrite(SS, HIGH);
      digitalWrite(SS, LOW);
      SPI.transfer(WB_JEDEC_ID);
      *b1 = SPI.transfer(0); // manufacturer id
      *b2 = SPI.transfer(0); // memory type
      *b3 = SPI.transfer(0); // capacity
      digitalWrite(SS, HIGH);
      not_busy();
    }

    /*
     * See the timing diagram in section 9.2.26 of the
     * data sheet, "Chip Erase (C7h / 06h)". (Note:
     * either opcode works.)
     */
    void _chip_erase(void) {
      digitalWrite(SS, HIGH);
      digitalWrite(SS, LOW);
      SPI.transfer(WB_WRITE_ENABLE);
      digitalWrite(SS, HIGH);
      digitalWrite(SS, LOW);
      SPI.transfer(WB_CHIP_ERASE);
      digitalWrite(SS, HIGH);
      /* See notes on rev 2
      digitalWrite(SS, LOW);
      SPI.transfer(WB_WRITE_DISABLE);
      digitalWrite(SS, HIGH);
      */
      not_busy();
    }
    void _write_test(void) {
      String sampleText = "Hello World";
      byte data[sampleText.length()];
      sampleText.getBytes(data, sizeof(data));
      _write_page(0,data);
      }
    /*
     * See the timing diagram in section 9.2.10 of the
     * data sheet, "Read Data (03h)".
     */
    void _read_page(word page_number, byte *page_buffer) {
      digitalWrite(SS, HIGH);
      digitalWrite(SS, LOW);
      SPI.transfer(WB_READ_DATA);
      // Construct the 24-bit address from the 16-bit page
      // number and 0x00, since we will read 256 bytes (one
      // page).
      SPI.transfer((page_number >> 8) & 0xFF);
      SPI.transfer((page_number >> 0) & 0xFF);
      SPI.transfer(0);
      for (int i = 0; i < 256; ++i) {
        page_buffer[i] = SPI.transfer(0);
      }
      digitalWrite(SS, HIGH);
      not_busy();
    }

    /*
     * See the timing diagram in section 9.2.21 of the
     * data sheet, "Page Program (02h)".
     */
    void _write_page(word page_number, byte *page_buffer) {
      digitalWrite(SS, HIGH);
      digitalWrite(SS, LOW);
      SPI.transfer(WB_WRITE_ENABLE);
      digitalWrite(SS, HIGH);
      digitalWrite(SS, LOW);
      SPI.transfer(WB_PAGE_PROGRAM);
      SPI.transfer((page_number >>  8) & 0xFF);
      SPI.transfer((page_number >>  0) & 0xFF);
      SPI.transfer(0);
      for (int i = 0; i < 256; ++i) {
        SPI.transfer(page_buffer[i]);
      }
      digitalWrite(SS, HIGH);
      /* See notes on rev 2
      digitalWrite(SS, LOW);
      SPI.transfer(WB_WRITE_DISABLE);
      digitalWrite(SS, HIGH);
      */
      not_busy();
    }

    /*
     * not_busy() polls the status bit of the device until it
     * completes the current operation. Most operations finish
     * in a few hundred microseconds or less, but chip erase
     * may take 500+ms. Finish all operations with this poll.
     *
     * See section 9.2.8 of the datasheet
     */
    void not_busy(void) {
      digitalWrite(SS, HIGH);
      digitalWrite(SS, LOW);
      SPI.transfer(WB_READ_STATUS_REG_1);
      while (SPI.transfer(0) & 1) {};
      digitalWrite(SS, HIGH);
    }

    /*
     * This handy built-in callback function alerts the UNO
     * whenever a serial event occurs. In our case, we check
     * for available input data and concatenate a command
     * string, setting a boolean used by the loop() routine
     * as a dispatch trigger.
     */
    void serialEvent() {
      char c;
      while (Serial.available()) {
        c = (char)Serial.read();
        if (c == ';') {
          g_command_ready = true;
        }
        else {
          g_command += c;
        }
      }
    }

    void setup(void) {
      SPI.begin();
      SPI.setDataMode(0);
      SPI.setBitOrder(MSBFIRST);
      Serial.begin(9600);
      Serial.println("");
      Serial.println("Ready");
    }

    /*
     * loop() dispatches the commands compiled by the serialEvent
     * parser callback. Some commands take multiple arguments, so
     * I have to split up the strings with some messy manipulation.
     */
    void loop(void) {
      if (g_command_ready) {
        if (g_command == "get_jedec_id") {
          get_jedec_id();
        }
        else if (g_command == "test_write") {
          Serial.println("Custom command: test_write");
          _write_test();
          }
        else if (g_command == "chip_erase") {
          chip_erase();
        }
        else if (g_command == "read_all_pages") {
          read_all_pages();
        }
        else if (g_command == "delayed_read_all_pages") {
          Serial.println("Custom command: delayed_read_all_pages");
          delayed_read_all_pages();
          }
        // A one-parameter command...
        else if (g_command.startsWith("read_page")) {
          int pos = g_command.indexOf(" ");
          if (pos == -1) {
            Serial.println("Error: Command 'read_page' expects an int operand");
          } else {
            word page = (word)g_command.substring(pos).toInt();
            read_page(page);
          }
        }
        // A three-parameter command..
        else if (g_command.startsWith("write_byte")) {
          word pageno;
          byte offset;
          byte data;

          String args[3];
          for (int i = 0; i < 3; ++i) {
            int pos = g_command.indexOf(" ");
            if (pos == -1) {
              Serial.println("Syntax error in write_byte");
              goto done;
            }
            args[i] = g_command.substring(pos + 1);
            g_command = args[i];
          }
          pageno = (word)args[0].toInt();
          offset = (byte)args[1].toInt();
          data = (byte)args[2].toInt();
          write_byte(pageno, offset, data);
        }
        else {
          Serial.print("Invalid command sent: ");
          Serial.println(g_command);
          g_command = "";
        }
    done:
        g_command = "";
        g_command_ready = false;
      }
    }

body:
Strings in C are terminated with a null byte - so the string "A" is in fact two bytes: the 'A' followed by a null.

Your `_write_test()` function counts only the characters in the string, and hence allocates one byte too few.  It should be:

    void _write_test(void) {
      String sampleText = "Hello World";
      byte data[sampleText.length()+1];
      sampleText.getBytes(data, sizeof(data));
      // See text below before calling write_page()
    }

But then we hit the issue of how much data `write_page()` will write.  It doesn't have any way of knowing how much data you are passing in - it just gets a pointer.  Looking at its implementation we can see that it writes exactly 256 bytes, so we need to pass in a buffer of 256 bytes.

    void _write_test(void) {
      String sampleText = "Hello World";
      byte data[256];
      sampleText.getBytes(data, sizeof(data));
      _write_page(0,data);
      }

(If we pass in a smaller buffer we're leaving it up to chance what will happen.  The Arduino doesn't have much protection so probably you'll just write garbage, but maybe, just maybe, you'll get unlucky and some weird crash will happen.)


sender: user

message:
Confusion in the use of byte variable

A byte stores an 8-bit unsigned number, from 0 to 255.

I can understand the following line:

    byte b = B10010;  // "B" is the binary formatter (B10010 = 18 decimal)

But I also saw a use such as:

    volatile byte state = LOW;

What does the last line mean here? Is that special for Arduino?
I mean LOW is not a 8 bit unsigned number. LOW is not a number here.

sender: assistant

body:
There is probably somewhere else, like this:

    #define LOW 0

Which means the pre-processor turns your line from this:

    volatile byte state = LOW;

into this:

    volatile byte state = 0;

There is nothing arduino-specific here, just the use of standard C/C++ features.


body:
In the same way that you can do

    int blarb = 12;
    #define wibble 73

you can do

    int FOO = 73;
    #define BINKY 99

or even

    int LOW = 0;
    #define HIGH 1

So in the line

    volatile byte state = LOW;

someone has created some sort of numerical constant with the name `LOW`.

You can read all about various constants provided for you [here][1].

  [1]: https://www.arduino.cc/en/Reference/Constants


body:
It is common practise in C/C++ to define certain much-used constants at the beginning of the code.

    #define true 1

this means that every time you write true in your code, the compiler will see it as 1.

The arduino IDE comes with a few constants predefined:

 - true = 1
 - false = 0
 - HIGH = 1
 - LOW = 0
 - ...


message:
Multiple if statements - stuck

I have a robot that uses two motors to skid steer. The robot gets input from three ultrasonic sensors (left, middle, and right) and a passive infrared sensor. If the robot detects a person in front of it, then it follows.

The sensors seem to work as they are intended. The infrared sensor sees a person and the ultrasonic sensors see that the person is between 65cm and 150cm and it follows. If the left ultrasonic sensor has the person in range, it turns left, and if the right ultrasonic sensor has the person in range, it turns right.

The problem is that the robot gets stuck turning left or turning right depending on which sensor it checks first in the code. It's like it's stuck in a while loop even though I'm not using a while loop.

I have adapted [NewPing][1] and library. The code in question is at the bottom in the last function. The rest is part of NewPing to read the ultrasonic sensors.

If anybody has any suggestions, it would be greatly appreciated.

    #include <NewPing.h>

    #define SONAR_NUM     3 // Number of sensors.
    #define MAX_DISTANCE 170 // Maximum distance (in cm) to ping.
    #define PING_INTERVAL 35 // Milliseconds between sensor pings (29ms is about the min to avoid cross-sensor echo).

    unsigned long pingTimer[SONAR_NUM]; // Holds the times when the next ping should happen for each sensor.
    unsigned int cm[SONAR_NUM];         // Where the ping distances are stored.
    uint8_t currentSensor = 0;          // Keeps track of which sensor is active.

    NewPing sonar[SONAR_NUM] = {     // Sensor object array.
      NewPing(11, 4, MAX_DISTANCE), //Left -- Each sensor's trigger pin, echo pin, and max distance to ping.
      NewPing(8, 3, MAX_DISTANCE),  //Center
      NewPing(7, 9, MAX_DISTANCE),  //Right
    };

    int ledR = 13;
    int ledG = 2;
    int ledB = A0;
    int motorPinL = 5;
    int motorPinR = 6;
    int ePIR = 10;
    boolean epirVal;

    void setup() {
      Serial.begin(115200);
      pingTimer[0] = millis() + 75;           // First ping starts at 75ms, gives time for the Arduino to chill before starting.
      for (uint8_t i = 1; i < SONAR_NUM; i++) // Set the starting time for each sensor.
        pingTimer[i] = pingTimer[i - 1] + PING_INTERVAL;
      pinMode (ledR, OUTPUT);
      pinMode (ledG, OUTPUT);
      pinMode (ledB, OUTPUT);
      pinMode (motorPinL, OUTPUT);
      pinMode (motorPinR, OUTPUT);
      pinMode (ePIR, INPUT);
    }

    void loop() {
      for (uint8_t i = 0; i < SONAR_NUM; i++) { // Loop through all the sensors.
        if (millis() >= pingTimer[i]) {         // Is it this sensor's time to ping?
          pingTimer[i] += PING_INTERVAL * SONAR_NUM;  // Set next time this sensor will be pinged.
          if (i == 0 && currentSensor == SONAR_NUM - 1)
            oneSensorCycle();                             // Sensor ping cycle complete, do something with the results.
          sonar[currentSensor].timer_stop();          // Make sure previous timer is canceled before starting a new ping (insurance).
          currentSensor = i;                          // Sensor being accessed.
          cm[currentSensor] = 155;                      // Make distance 155 in case there's no ping echo for this sensor. changed from zero
          sonar[currentSensor].ping_timer(echoCheck); // Do the ping (processing continues, interrupt will call echoCheck to look for echo).
        }
      }
      // Other code that *DOESN'T* analyze ping results can go here.
    }

    void echoCheck() { // If ping received, set the sensor distance to array.
      if (sonar[currentSensor].check_timer())
        cm[currentSensor] = sonar[currentSensor].ping_result / US_ROUNDTRIP_CM;
    }

    void allStop () {
      analogWrite (motorPinL, 0);
      analogWrite (motorPinR, 0);
      digitalWrite (ledG, LOW);    //LED corresponding to right ultrasonic sensor
      digitalWrite (ledR, LOW);    //LED corresponding to left ultrasonic sensor
      digitalWrite (ledB, LOW);    //LED corresponding to center ultrasonic sensor
    }

  [1]: http://playground.arduino.cc/Code/NewPing

body:
Your logic is flawed. Translating your loop in pseudocode gives
something like this:

    if (PIR does not detect OR ANY sonar is out of range) {  // cond. 1
        stop
    } else if (PIR does detect AND right sonar is in range) {  // cond. 2
        turn right
    } else if (PIR does detect AND left sonar is in range) {  // cond. 3
        turn left
    } else if (PIR does detect AND center sonar is in range) {  // cond. 4
        go straight
    }

Notice that, if condition 1 is false, then that means that the PIR does
detect AND ALL of the sonars are in range. Which implies that condition
2 is necessarily true. Which implies that the following elses have no
effect. Your code can then be optimized (and the compiler probably did
optimize it) into

    if (ANY sonar is out of range OR PIR does not detect) {  // cond. 1
        stop
    } else {  // cond. 2 is true if cond 1. is false
        turn right
    }

You should rethink your problem asking yourself the following questions:

* under what conditions should the robot turn right?
* under what conditions should the robot turn left?
* under what conditions should the robot go straight?
* under what conditions should the robot stop?

Make sure that in any circumstance EXACTLY one of the above conditions
holds true. In other words, the conditions should be mutually exclusive
and cover every possibility. One you have the answers, the coding should
be straightforward.

------------------------------------------------------------------------

**Edit**: Your updated code still contains logic flaws. For example, if
the PIR senses the person and BOTH the left and right sonars are in
range, then you are asking the robot to BOTH turn left and turn right.
Unless it's a quantum robot evolving in an Everett's multiverse, it
won't be able to comply. To the risk of repeating myself, you must
decide on one and only one action for every possible situation.

If you are struggling with that concept, I suggest you start by filling
the truth table below. On each of the 16 lines of the table you should
fill the last column with one (and only one) action among: `allStop`,
`turnRight`, `turnLeft` and `straight`. Yes, I know it's tedious to
consider all the possible situations one by one, but you _must_ do that
before starting to write the code. Otherwise you end up with completely
broken logic.

    +--------+----------+----------+----------+-----------+
    | PIR    | sonar 0  | sonar 1  | sonar 2  |  robot    |
    | senses | in range | in range | in range |  action   |
    +--------+----------+----------+----------+-----------+
    |  no    |   no     |   no     |   no     |           |
    |  no    |   no     |   no     |   yes    |           |
    |  no    |   no     |   yes    |   no     |           |
    |  no    |   no     |   yes    |   yes    |           |
    |  no    |   yes    |   no     |   no     |           |
    |  no    |   yes    |   no     |   yes    |           |
    |  no    |   yes    |   yes    |   no     |           |
    |  no    |   yes    |   yes    |   yes    |           |
    |  yes   |   no     |   no     |   no     |           |
    |  yes   |   no     |   no     |   yes    |           |
    |  yes   |   no     |   yes    |   no     |           |
    |  yes   |   no     |   yes    |   yes    |           |
    |  yes   |   yes    |   no     |   no     |           |
    |  yes   |   yes    |   no     |   yes    |           |
    |  yes   |   yes    |   yes    |   no     |           |
    |  yes   |   yes    |   yes    |   yes    |           |
    +--------+----------+----------+----------+-----------+


message:
5V 1A vs 5V 5A power supply for 6 LED + Arduino

If I want to power up 6 normal 3mm LED with the appropriate series limiting resistor, do I need the 5V with **1A** or **5A** power supply? Same goes to the Arduino, if I want to power it externally, do I go for the **1A** or **5A**?

body:
Depending on your led, it will draw 10 to 20mA for a standard led. Thats 0.010 to 0.020A. Multiply this by 6 and you see that a 1A power supply will be enough.

Your arduino, when driving those leds, will also use a few mA. So you can power everything with a 1A power supply.


body:
Both will work, but **go with 1A!!!**

It is more forgiving if a short happens.

A 5A short circuit will make sparks that might be dangerous.


message:
Weird formatting behavior with sprintf function

I don't know why but since yesterday, my Arduino sketch returns weird data. I've check eaches inputs and the returns values are ok.

But that line:

    sprintf(read, "%d;%d;%d;%d;%d;%d;%d;%d\r", x, analogRead(HD), analogRead(HG), analogRead(CD), analogRead(CG), 0, 0, analogRead(ECG));

returns something like this:

    3000;0;110;291;263;230;0;0 (It's like the analog reads are shift from 1 position to the right)

It's suppose to return something like this:

    3000;110;291;263;230;0;0;245

Here is my sketch:

    int HD = A0;
    int HG = A1;
    int CD = A2;
    int CG = A3;
    int ECG = A5;

    volatile boolean interruptFlag = 0;
    char read[45];
    char signal[2048];
    volatile int count = 0;
    volatile long x = 0;

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

      noInterrupts(); // Stop interrupts.

      TCCR1A = 0; // Set entire TCCR1A register to 0.
      TCCR1B = 0; // Same for TCCR1B.
      TCNT1  = 0; // Initialize counter value to 0.

      // Set compare match register for 50Hz increments.
      OCR1A = 39999; // = 16000000 / (8 * 50) - 1 (must be <65536)

      // Turn on CTC mode.
      TCCR1B |= (1 << WGM12);
      // Set CS12, CS11 and CS10 bits for 64 prescaler.
      TCCR1B |= (0 << CS12) | (1 << CS11) | (1 << CS10);
      // Enable timer compare interrupt.
      TIMSK1 |= (1 << OCIE1A);

      interrupts(); // Allow interrupts.
    }

    ISR(TIMER1_COMPA_vect){
      if (!interruptFlag){
        interruptFlag = 1;
      }
    }

    void loop() {
      if (interruptFlag){
        writeAnalogSignals();
        count++;
        interruptFlag = 0;
      }
    }

    void writeAnalogSignals() {
      if (strlen(read) == 0) {
        sprintf(read, "%d;%d;%d;%d;%d;%d;%d;%d\r", x, analogRead(HD), analogRead(HG), analogRead(CD), analogRead(CG), 0, 0, analogRead(ECG));
      } else {
        sprintf(read, "|%d;%d;%d;%d;%d;%d;%d;%d\r", x, analogRead(HD), analogRead(HG), analogRead(CD), analogRead(CG), 0, 0, analogRead(ECG));
      }
      strcat(signal, read);

      x += 2;

      if (count >= 50) {
        Serial.print(signal);
        signal[0] = 0;
        count = 0;
      }
    }

body:
Sometimes the sprintf can be used instead of 20 lines of code. In this case an array with integers and a loop with Serial.print would be better as Majenko already wrote.

When you do use the sprintf, a shift in the data means that one of the parameters has too many or too little bytes. The sprintf does not know the size of the parameter and the parameter will not be converted to a different type. When you use "%d", you have to put two bytes on the stack. Since your 'x' is 4 bytes, all those 4 bytes will be put onto the stack. The first "%d" reads two bytes of 'x' and the second "%d" read the other two bytes of 'x'. That is why it is shifted.

For a data rate of 50Hz, I suggest to raise the baudrate to 115200.

Using millis() for the 50Hz will result into the same timing accuracy as you have now. You don't need the timer and you don't need the interrupt.
See the [BlinkWithouDelay][1] example and use 20ms as an interval.

  [1]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay


message:
Make Arduino Executable File

On a Pi, to execute a C++ code, you'll need a Makefile.

Is there an equivalent with the Arduino? Where I have some valid C++ files to upload without the IDE's help, but instead with an executable?

body:
Whether you compile manually with a Makefile (or Arduino-Builder) or in the IDE, the end result is a HEX file.  This is a text file describing the data to load into the flash memory.

You then use avrdude to install it into the Arduino - either from the IDE or by running it manually (or specifying it in your Makefile, etc).

A Makefile doesn't produce an executable. A Makefile is merely a recipe - a set of instructions - telling the `make` program which programs to run (gcc, avr-gcc, etc) and in what order (and with what flags) to compile your code.

There are many Arduino Makefile projects out there that do it all for you.


body: Take a look at platformio.org. It Provides a simple CLI environment to compile, upload and monitor.


message:
Can't upload new sketch

Recently I have unsoldered most connector pins there are on the arduino uno board.
However, when I now attempt to upload a new sketch (works when I upload it to another model) it gives me the following error:

    > avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xfa
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xfa
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xfa
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xfa
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xfa
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xfa
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xfa
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xfa
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xfa
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xfa

I would like you take a look at my arduino board to see whether I have unsoldered important pins which might have to be connected.

Also when I try to upload a new sketch the 'L'-LED doesn't flash but the RX one.

(BTW: Yes I've set the settings to the correct board, port etc...)

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

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

Thanks for any solution attempts!

body: Pin 0(RX) and 1(TX) and the RESET pins are important to upload a sketch. Can you check those carefully with a magnifier ? Perhaps there is some solder that shortcuts to something else, or perhaps you damaged a copper trace.


body: Checking the schematic, the TX/RX leds are driven directly by the atmega16u and are not connected to the TX/RX lines of the 328p.  That would seem to indicate the 16u has a problem so it's a good place to double check. The lines that run to the TX/RX of the 328p run from pins 8 - 9 of the 16u. I assume that this ran previous to the fatal 'surgery'? I don't suppose you loaded something simple, like the led flash program before surgery?  Just curious, are you hard wiring it to something?


body:
Removing there pin headers should not cause any sketch upload issue. I have done it many times.

You did try uploading BEFORE unsoldering the headers right ?

However looking at the desoldering job you did, my guess is that you applied too much heat or cut a trace on the PCB while doing it.

Can you upload a high resolution of the back side of the board?

What I would try is to take a known good 328p chip and replace the one on this board with it and try uploading again.


body:
Try to unplug the IC and the plug it again.

I think that you have removed the IC off of the board. If it doesn't work then buy a new ATmega328P IC and replace it with the old one and then try again.


message:
'content' is not captured

I try to make a variable that can be modified from the server, using and ESP8266.

    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>
    #include <ESP8266mDNS.h>

    const char* ssid = "********";
    const char* password = "*********";

    ESP8266WebServer server(80);

    const int led = 13;

    void handleRoot() {
        digitalWrite(led, 1);
        server.send(200, "text/plain", "hello from esp8266!");
        digitalWrite(led, 0);
    }

    void handleNotFound() {
        digitalWrite(led, 1);
        String message = "File Not Found\n\n";
        message += "URI: ";
        message += server.uri();
        message += "\nMethod: ";
        message += (server.method() == HTTP_GET)?"GET":"POST";
        message += "\nArguments: ";
        message += server.args();
        message += "\n";

        for (uint8_t i=0; i<server.args(); i++){
            message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
        }

        server.send(404, "text/plain", message);
            digitalWrite(led, 0);
        }
    }

    void setup(void) {
        pinMode(led, OUTPUT);
        digitalWrite(led, 0);
        Serial.begin(115200);
        WiFi.begin(ssid, password);
        Serial.println("");

        // Wait for connection
        while (WiFi.status() != WL_CONNECTED) {
            delay(500);
            Serial.print(".");
        }

        Serial.println("");
        Serial.print("Connected to ");
        Serial.println(ssid);
        Serial.print("IP address: ");
        Serial.println(WiFi.localIP());

        if (MDNS.begin("esp8266")) {
            Serial.println("MDNS responder started");
        }

        String content = "Basic";
        content += "<form action='action_page.php' method='POST'>
";
        content += "User:<input type='text' name='USERNAME' placeholder='user name'>
";
        content += "<input type='submit' name='SUBMIT' value='Submit'></form>
";

        server.on("/led", [](){
            server.send(200, "text/html", content);
            Serial.println(USERNAME);
        }

        server.on("/", handleRoot);

        server.on("/inline", [](){
            server.send(200, "text/plain", "this works as well");
        });

        server.onNotFound(handleNotFound);
        server.begin();
        Serial.println("HTTP server started");
    }

    void loop(void){
        server.handleClient();
    }

When I compile it, it says

> 'content' is not captured

I thought it may be from the input, and I tried to name it "Basic" for the start, but it still failed.

body: Are you looking at the last compiler error ? The first one is the most most important one. In the preferences, the compiler output can be turned on to show more. Then scroll up to see the first compiler error. The compiler has troubles with the `` at the very end of your sketch.


body:
Let's look at a simpler example:

    void setup ()
    {
      String content = "Basic";

      attachInterrupt (digitalPinToInterrupt (2),
                       []()
      {
        Serial.println(content);
      },

      FALLING );

    }  // end of setup

    void loop () { }

This gives the error:

    /tmp/arduino_modified_sketch_182173/sketch_jan25a.ino: In lambda function:
    sketch_jan25a:8: error: 'content' is not captured
         Serial.println(content);

Why? Because you are using a local variable `content` in a lambda function which runs at global scope. That is, `content` is not available to it, because it is inside `setup`.

To capture it, you can put it in the capture list:

      attachInterrupt (digitalPinToInterrupt (2),
                       [content]()  // capture content

However I found that my example doesn't compile even then.

---

I think the reason for that can be found here: [Lambda Functions in C++11 - the Definitive Guide](http://www.cprogramming.com/c++11/c++11-lambda-closures.html)

> **How are Lambda Closures Implemented?**
>
>So how does the magic of variable capture really work? It turns out that the way lambdas are implemented is by creating a small class; this class overloads the operator(), so that it acts just like a function. A lambda function is an instance of this class; when the class is constructed, any variables in the surrounding enviroment are passed into the constructor of the lambda function class and saved as member variables.

You can't pass an instance of a class to `attachInterrupt` because there is a hidden `*this` variable that needs to be passed to class instances, and ISRs don't do that.

Now your example isn't an ISR, but probably the same remarks apply.

---

I don't think there is an enormous amount of point of using lambda functions here. If you must, move `content` inside the lambda, since that is where you are using it.

Or failing that, make it global scope.

---

The closest I could get to something that compiled was:

    void setup ()
    {
      const int content = 42;

      attachInterrupt (digitalPinToInterrupt (2),
                       [=]()
      {
        Serial.println(content);
      },

      FALLING );

    }  // end of setup

    void loop () { }

Honestly though, I think using lambda functions here just makes your code obscure.


message:
Error: "invalid use of non-static member function" while calling a function from my own class-method

I'm having a bad time trying to call a correctly-working expression (`ultra[currentSensor].ping_timer(echoCheck)`) from an own class method (`myclass::run`) instead of from `void loop()`.

I'm getting the following compiler error:
**"invalid use of non-static member function"**.

If I call `ultra[currentSensor].ping_timer(echoCheck)` directly from `void loop()` it gives me no error, so I may be missing something.

Here's the (shortened) piece of code which is generating the error:

    #include <NewPing.h>

    #define ULTRA_NUM      3
    #define MAX_DISTANCE 200

    class myclass {
      public:

        void run();
        void echoCheck();

        unsigned int distance[ULTRA_NUM];
        uint8_t currentSensor = 0;
    };

    NewPing ultra[ULTRA_NUM] = {
      NewPing(4, 5, MAX_DISTANCE),
      NewPing(6, 7, MAX_DISTANCE),
      NewPing(8, 9, MAX_DISTANCE)
    };

    void myclass::run() {
    // ....
          ultra[currentSensor].ping_timer(echoCheck);  // Compiler error
      }

    void myclass::echoCheck() {
      if (ultra[currentSensor].check_timer())
        distance[currentSensor] = ultra[currentSensor].ping_result
    }

`ping_timer()` is defined as it follows:

    void NewPing::ping_timer(void (*userFunc)(void), unsigned int max_cm_distance) {
     if (max_cm_distance > 0) set_max_distance(max_cm_distance);

     if (!ping_trigger()) return;
     timer_us(ECHO_TIMER_FREQ, userFunc);
    }

I hope any of you can help me!

Thanks in advance,

Eduardo

-------
**Edit**:
What I am trying to do is to adapt [this example][1] (from NewPing Arduino Library) so that the sonar ping (`sonar[currentSensor].ping_timer(echoCheck)`) is done from a class method, and not from `void loop()`.

  [1]: https://bitbucket.org/teckel12/arduino-new-ping/wiki/Help with 15 Sensors Example Sketch

body:
The problem is that `echo_check` isn't `void echo_check()` but `void echo_check(myclass *this)` because it's a member function of a class.

You can make the whole thing static (along with `run()`) by:

    class myclass {
        public:
            static void run();
            static void echo_check();
    };

    static void myclass::run() {
        ....
    }

    void myclass::echo_check() {
        ....
    }

And then you call:

    myclass::run();

instead of instantiating an object.


body:
Solved:

I moved the event handler out of the class, and made it static void.

Then the code compiled properly

D


message:
Moving average sticks in fictitious zeroes for the first readings. This delays accuracy

My 9/10 Moving Average inserts zeroes for the first 9 readings. For example, if the first voltage reading is 100, the first moving average given is 10. That is the average of 9 zeroes and one 100. How can I get the moving average to only use actual readings from the adc? Or how can I get the moving average to wait until at least 10 readings are finished before starting its calculations?

    #include <SPI.h>
    #include <SoftwareSerial.h>
    #include <math.h>
    #include <ads1262.h>

    #define PGA 1 // Programmable Gain = 1
    #define VREF 2.50 // Internal reference of 2.048V
    #define VFSR VREF/PGA
    #define FSR (((long int)1<<23)-1)

    ads1262 PC_ADS1262; // class

    float volt_V=0;
    float volt_mV=0;
    float MovingAverage=0;
    volatile int i;
    volatile char SPI_RX_Buff[10];
    volatile long ads1262_rx_Data[10];
    volatile static int SPI_RX_Buff_Count = 0;
    volatile char *SPI_RX_Buff_Ptr;
    volatile int Responsebyte = false;
    volatile signed long sads1262Count = 0;
    volatile signed long uads1262Count=0;
    double resolution;

    void setup() {
      // initalize the  data ready and chip select pins:
      pinMode(ADS1262_DRDY_PIN, INPUT); //data ready input line
      pinMode(ADS1262_CS_PIN, OUTPUT); //chip enable output line
      pinMode(ADS1262_START_PIN, OUTPUT);  // start
      pinMode(ADS1262_PWDN_PIN, OUTPUT); // Power down output
      Serial.begin(9600);
      //initalize ADS1292 slave
      PC_ADS1262.ads1262_Init(); // initialise ads1262
      Serial.println("ads1262 Initialised successfully....");
    }

    void loop() {
      volatile int i, data;
      if((digitalRead(ADS1262_DRDY_PIN)) == LOW) {
        // monitor Data   ready(DRDY pin)
        SPI_RX_Buff_Ptr = PC_ADS1262.ads1262_Read_Data();
        // read 6 bytes conversion register
        Responsebyte = true;
      }
      if(Responsebyte == true) {
        for(i = 0; i <5; i++) {
          SPI_RX_Buff[SPI_RX_Buff_Count++] = *(SPI_RX_Buff_Ptr + i);
        }
        Responsebyte = false;
      }
      if(SPI_RX_Buff_Count >= 5) {
        ads1262_rx_Data[0]= (unsigned char)SPI_RX_Buff[1];
        // read 4 bytes adc count
        ads1262_rx_Data[1]= (unsigned char)SPI_RX_Buff[2];
        ads1262_rx_Data[2]= (unsigned char)SPI_RX_Buff[3];
        ads1262_rx_Data[3]= (unsigned char)SPI_RX_Buff[4];
        uads1262Count = (signed long) (((unsigned long)ads1262_rx_Data[0]<<24)| ((unsigned long)ads1262_rx_Data[1]<<16)|(ads1262_rx_Data[2]<<8)|        ads1262_rx_Data[3]);
        //get the raw 32-bit adc count out by shifting
        sads1262Count = (signed long) (uads1262Count);
        // get signed value
        resolution = (double)((double)VREF/pow(2,31));
        //resolution=  Vref/(2^n-1) , Vref=2.5, n=no of bits
        volt_V = (resolution)*(float)sads1262Count;
        // voltage = resolution * adc count
        MovingAverage = (9*MovingAverage + volt_V)/10;
        Serial.print(MovingAverage,8);
      }
      SPI_RX_Buff_Count = 0;
    }

    float mapfloat(float x, float in_min, float in_max, float out_min, float out_max) {
      return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
    }

body:
Perhaps the easiest way to take in at least 10 readings before beginning to output results is to set a counter to 10 and count it down, as illustrated in following code.

    byte startup=10;
    void loop() {
      stuff_to_await_DRDY_and_compute_volt_V();
      MovingAverage = (9*MovingAverage + volt_V)/10;
      if (startup)
        --startup;  // Don't use MovingAverage during startup cycles
      else {        // Now we are done with startup...
        Serial.print(MovingAverage,8);
        other_stuff_with_new_data();
      }
    }

As hinted at in a comment to the question, declaring all your variables `volatile` isn't necessary.  You should declare variables that are shared between threads, or between an ISR and `loop()`, `volatile`, but to declare other variables as `volatile` is in general a coding-style error that will confuse whoever maintains the code.  Spurious `volatile` declarations also may increase code size slightly, as it prevents one-time evaluation of expressions that are used exactly the same way multiple times, and it prevents code motion like moving constant expressions out of loops.

The following code rewrites severak parts of your sketch.  It uses some pointer arithmetic to avoid the tedious assignments and shifting found in your code.  It removes several extraneous casts because many of the type promotions and conversions coerced by your casts happen automatically anyway.  This code has not been tested; if it has problems, please point them out and I'll edit accordingly.

    #include <SPI.h>
    #include <SoftwareSerial.h>
    #include <math.h>
    #include <ads1262.h>
    #define PGA 1 // Programmable Gain = 1
    #define VREF 2.50 // Internal reference of 2.048V
    #define VFSR VREF/PGA
    #define FSR (((long int)1<<23)-1)
    ads1262 PC_ADS1262; // class
    float volt_V=0;
    float volt_mV=0;
    float MovingAverage=0;
    byte SPI_RX_Buff[10];
    byte SPI_RX_Buff_Count = 0;
    char *SPI_RX_Buff_Ptr;
    void setup() {
      // initalize the  data ready and chip select pins:
      pinMode(ADS1262_DRDY_PIN, INPUT); //data ready input line
      pinMode(ADS1262_CS_PIN, OUTPUT); //chip enable output line
      pinMode(ADS1262_START_PIN, OUTPUT);  // start
      pinMode(ADS1262_PWDN_PIN, OUTPUT); // Power down output
      Serial.begin(9600);
      //initalize ADS1292 slave
      PC_ADS1262.ads1262_Init(); // initialise ads1262
      Serial.println("ads1262 Initialised successfully....");
    }

    byte startup=10;
    void loop() {
      double resolution;
      long *ads1262Count;
      if((digitalRead(ADS1262_DRDY_PIN)) == LOW) { // Is data ready?
        resolution = (double)VREF/pow(2,31);  // Vref/(2^n-1), Vref=2.5
        // Get address of 6-byte conversion-data buffer
        SPI_RX_Buff_Ptr = PC_ADS1262.ads1262_Read_Data();
        // Copy address of SPI_RX_Buff_Ptr[1] to ads1262Count
        ads1262Count = SPI_RX_Buff_Ptr+1;
        // Dereference ads1262Count pointer to get 4-byte signed value
        volt_V = *ads1262Count * resolution;
        MovingAverage = (9*MovingAverage + volt_V)/10;
        if (startup)
          --startup; // Don't use MovingAverage during startup cycles
        else {       // Now we are done with startup...
          Serial.print(MovingAverage,8);
          other_stuff_with_new_data();
        }
      }
      SPI_RX_Buff_Count = 0;
    }


body:
There are essentially two ways of initializing a low pass filter. The
first is to let it initialize itself “naturally” by feeding it data
until it reaches its steady state. This is the approach of jwpat7's
answer, and it works really well with [FIR filters][], like a plain
moving average.

Your exponentially-weighted moving average, however, is an
[IIR filter][]. Given constant input, it converges _asymptotically_ to its
steady state. After feeding it 10 values, it will only have reached 65%
of the steady state (exactly 1 − 0.910), thus you
may want to feed it significantly more than 10 points. E.g., you should
give it 22 points if you want it to be 90% initialized.

The other approach is to provision a specific initialization procedure
that sets the internal state of the filter to what it would have been
had it processed an infinite stream of constant values. This is actually
really easy to do with this particular filter, as we only have to set
the output equal to its first input. Here is the self-initializing
filter written as a function (this keeps the code cleaner):

    static float movingAverage(float x)
    {
      static bool initialized;
      static float output;

      // Initialize the filter as if this input had been on forever.
      if (!initialized) {
        output = x;
        initialized = true;
      }

      output += 0.1 * (x - output);
      return output;
    }

You loose the benefit of the averaging on the very first data points,
but in return you have a simple to use self-initializing filter.

Unrelated to your question, I looked at your code and fond so many
confusing and useless statements that I felt compelled to remove all
that cruft. I did not test the simplified version though:

    #include <ads1262.h>

    const float VREF = 2.50;  // Internal reference

    ads1262 PC_ADS1262;  // ADC object

    void setup() {
      // initialize the  data ready and chip select pins:
      pinMode(ADS1262_DRDY_PIN,  INPUT);   // data ready input line
      pinMode(ADS1262_CS_PIN,    OUTPUT);  // chip enable output line
      pinMode(ADS1262_START_PIN, OUTPUT);  // start
      pinMode(ADS1262_PWDN_PIN,  OUTPUT);  // power down output
      Serial.begin(9600);

      // initialize ADS1292 slave
      PC_ADS1262.ads1262_Init();
      Serial.println("ads1262 Initialised successfully....");
    }

    static float movingAverage(float x) { ... }  // as before

    void loop() {
      // Nothing to do unless data ready is asserted.
      if (digitalRead(ADS1262_DRDY_PIN) == HIGH) return;

      // Get a reading and convert to voltage.
      uint8_t *buffer = (uint8_t *) PC_ADS1262.ads1262_Read_Data();
      signed long reading = (uint32_t) buffer[1] << 24
                          | (uint32_t) buffer[2] << 16
                          | (uint32_t) buffer[3] <<  8
                          | (uint32_t) buffer[4] <<  0;
      float voltage = VREF / (1UL<<31) * reading;

      // Report a smoothed-out reading.
      Serial.println(movingAverage(voltage), 8);
    }

[FIR filters]: https://en.wikipedia.org/wiki/Finite_impulse_response
[IIR filter]: https://en.wikipedia.org/wiki/Infinite_impulse_response


body:
The simplest method is just to go "I have only taken one reading, therefore I only need to look at one reading".  I.e., after your first reading you have 100/1. After your second reading you have (100+100)/2. After your 3726482374th reading you have (100+100+100+100+100+100+100+100+100+100)/10.

I have a fully templated library that works in exactly that way - it returns the rolling average (amongst other things) of only the samples you have actually fed it.

* https://github.com/MajenkoLibraries/Average


message:
I can send AT Commands, but cannot upload sketch to ESP8266 via Generic ESP Module

I can send AT commands to the ESP8266 - 01 but I am not able to upload the sketch.

I have connected TX-RX of module to TX-RX of Arduino, GND to GND, CH_PD, RST and VCC to 3.3V.

Here is the code I'm trying to upload -

    #include <ESP8266WiFi.h>

    const char* ssid = "ssid";
    const char* password = "password";

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

      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.println(".");
        Serial.println("Connected to ");
        Serial.println(ssid);
      }
    }

    void loop() {
      Serial.println("Hello, Internet");
      delay(1000);
      Serial.println("IP Address");
      Serial.println(WiFi.localIP());
      delay(2000);
    }

Here is the error I am getting.

    Arduino: 1.8.1 (Windows 8.1), Board: "Generic ESP8266 Module, 80 MHz, 40MHz, DIO, 115200, 512K (64K SPIFFS), ck, Disabled, None"

    Sketch uses 225921 bytes (52%) of program storage space. Maximum is 434160 bytes.
    Global variables use 31864 bytes (38%) of dynamic memory, leaving 50056 bytes for local variables. Maximum is 81920 bytes.
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    warning: espcomm_sync failed
    error: espcomm_open failed
    error: espcomm_upload_mem failed
    error: espcomm_upload_mem failed

Please suggest something.

body:
In order to put the ESP into programming mode, you need to connect GPIO0 to ground as you power it up.

(I have a push button attached to my proto board for this purpose.)


body: Every implementation that I've seen connects TX->RX & RX->TX when going between devices. :)


message:
Can't able to detect Square wave from 74HC14

In my recent project, I want square wave which length vary according our timing. And this square wave is take reference as a another square wave.

For that, I made Square wave with help of Arduino.

Here, it's code.

    int kPinSqrOut = 13;

    void setup()
    {
       pinMode(kPinSqrOut, OUTPUT);
    }

    void loop()
    {
      digitalWrite(kPinSqrOut, HIGH);
      delay(1000);
      digitalWrite(kPinSqrOut, LOW);
      delay(2000);
   }

This is just simple HIGH and LOW one pin of arduino and we get Square wave.

Oscilloscope output :
[![Square wave][1]][1]

Now based on this, I'm getting Square wave which length can be able to vary.

Here, it's code.

    const uint8_t button_pin = 2;
    const uint8_t kPin = 3;

    void setup()
    {
       pinMode(button_pin, INPUT_PULLUP);
       pinMode(kPin, OUTPUT);
       Serial.begin(9600);
    }

    void loop()
    {
       static int last_button_state = LOW;
       static unsigned int push_count;
       static unsigned long last_press_time;
       int button_state = digitalRead(button_pin);
       unsigned long now = millis();

      // Record when the button is pressed.
      if(last_button_state == LOW && button_state == HIGH)
      {
        push_count++;
        last_press_time = now;

        digitalWrite(kPin, HIGH);
        delay(20);
        digitalWrite(kPin, LOW);
      }

      // Report when the button is released.
      if(last_button_state == HIGH && button_state == LOW)
      {
        unsigned long push_duration = now - last_press_time;
        if (push_duration < 10)   // discard bounce
        {
            push_count--;
        }
        else
        {
           Serial.print(F("pushes: "));
           Serial.print(push_count);
           Serial.print(F(", duration: "));
           Serial.print(push_duration);
           Serial.println(F(" ms"));
        }
      }

      last_button_state = button_state;
    }

And Serial Monitor output :

    pushes: 1,    duration: 1001
    pushes: 2,    duration: 1000
    pushes: 3,    duration: 1001
    pushes: 4,    duration: 1002
    pushes: 5,    duration: 1001
ve
So, basically what I'm try to do. One Arduino generate Square wave and another Arduino take this Square wave as Input and calculate it's length and also generate another Square wave based on first one.

Here, I just detect HIGH state of Square wave and according that generate another Square wave which length vary.

Oscilloscope output :

[![Square waves][2]][2]

Ideally, all this things work fine. Now, when I apply this things in real implement then not working.

Here, it my square wave(upper one) from 74HC14. But not getting another square wave based on that.

[![74HC14 Square Wave][3]][3]

So, give me some suggestion.

  [1]: https://i.stack.imgur.com/Ls3Rz.jpg
  [2]: https://i.stack.imgur.com/1m2ik.jpg
  [3]: https://i.stack.imgur.com/f4PHR.jpg

body:
The only issue in your code is due to the delay in the pin control. You can solve it this way:

    void loop()
    {
     static int last_button_state = LOW;
     static unsigned int push_count;
     static unsigned long last_press_time;
     static bool kPinPressed = false;
     int button_state = digitalRead(button_pin);
     unsigned long now = millis();

     // Record when the button is pressed.
     if(last_button_state == LOW && button_state == HIGH)
     {
      push_count++;
      last_press_time = now;

      digitalWrite(kPin, HIGH);
      kPinPressed = true;
     }

     if ((kPinPressed) && ((now - last_press_time) >= 20))
     {
      digitalWrite(kPin, LOW);
      kPinPressed = false;
     }

     ...
    }

So you turn on the output, then after 20ms you turn it off.

There are just a couple of things not clear for me. What is the last picture? What are the yellow and pink traces? Why is it not behaving correctly? What are the readings on the serial interface?

And most important... What is the time scale? Is it really 10ms/div?


body:
Your code. Is designed to work with slow inputs and you are feeding it a much faster input than it can handle.

Solution 1. Use interrupts.
Solution 2. Speed up the main loop execution if you insist on polling.


message:
Confusion on array definition at Arduino website

See the below explanation about [Arrays][1] from Arduino's official site:

> **Creating (Declaring) an Array**
>
> All of the methods below are valid ways to create (declare) an array.
>
>       int myInts[6];
>       int myPins[] = {2, 4, 8, 3, 6};
>       int mySensVals[6] = {2, 4, -8, 3, 2};
>       char message[6] = "hello";
>
> You can declare an array without initializing it as in myInts.
>
> In myPins we declare an array without explicitly choosing a size. The
> compiler counts the elements and creates an array of the appropriate
> size.
>
> Finally you can both initialize and size your array, as in mySensVals.
> Note that when declaring an array of type char, one more element than
> your initialization is required, to hold the required null character.

I have the following problems to understand:

1. Isn't `int mySensVals[6] = {2, 4, -8, 3, 2};` wrong? I count 5 elements.

2. Isn't `char message[6] = "hello";` is wrong as well? I count 5 elements.

  [1]: https://www.arduino.cc/en/Reference/Array

body:
> 1-) Isn't int mySensVals[6] = {2, 4, -8, 3, 2}; wrong? I count 5 elements.

No, not wrong at all. There are 6 elements (as the definition says), and the first five are set to 2, 4, -8, 3 and 2. The sixth is undefined.

> 2-) Isn't char message[6] = "hello"; is wrong as well? I count 5 elements.

No. There are 6 there. To quote your quote:

> **Note that when declaring an array of type char, one more element than your initialization is required, to hold the required null character.**

So "hello" is actually "hello\0".


message:
Run 2 loops side by side

Let's say I have 2 loops `LED()` and `IR()` with a print statement in my Arduino `loop()` function. Basically I want my `IR()` loop to be always running so that at any point in time I provide a signal to the receiver, it will print something. I currently can only run `LED()` first and then once `LED()` is finished, only then the `IR()` will run. So if I send a signal let's say while `LED()` is running, nothing is showing up. Thanks!

EDIT: **Updated with code**

    void loop() {
      single_Check(); // delay of 500ms
      if (irrecv.decode(&results)) {   //IR code
         Serial.println(results.value, HEX);
         irrecv.resume();
      }
    }

The `single_check()` function basically turns on 6 LED one by one and check the voltage of the LED and prints them out. However, this code takes time to finish because I put in `delay(500)`. So only after 500ms, the IR code will run.

body:
Your outer loop needs to only decide whether the IR or the LED needs service. If/when one of them does, call a function that services that device. The service functions should be brief and without delay() calls.

If a service function needs to do something/delay/do something else, it should do it by parts; only do the first something and let the main loop decide when it is time to do the something-else.

If this is all you are doing - two devices and their service routines, you may not need anything more. If you need to extending this to n-devices with n or more service routines, and the servicing is time-based (such as the LED probably is), look the SimpleTimer library. Then your outer loop would only call the timers' .run() function frequently, and the timers routine would take care of calling each service routine when necessary.

You'll probably end up with something like:

    SimpleTimer Timers;  // set of timers

    void setup(){
       // some set-up stuff here
       Timers.setInterval(long 10L, LedService);  // call LedService 100x/sec
    }

    void loop(){
       Timers.run();
       if( IRTest() )
          IRService();
    }

    void LedService(void){
       // manage LED here
    }

    bool IRTest(void){
       // return true if IR needs service
       // or false otherwise
    }

    void IRService(void){
       // manage IR sensor here
    }


body:
Arduino and like Arduino hardware run only a sequential Flow, Because they usually have only one core.
For running 2 loops side-by-side you have some solutions.

- A flow to test flags and execute specific code.
- Use a timer
- Use a RealTime OS, like [FreeRTOS][1]

try never use delay

  [1]: http://www.freertos.org/


body:
On Arduino (and on most other micro controllers for what it matters) you **CANNOT** do two things at the exact same time, so forget about _running two loops_ in principle.

What you can do is: run two separate piece of code one after the other, fast enough that they _look_ to be running in parallel or run one continuously and run the other when an _event_ occurs.

In your case the first option is not applicable, so you have to revert to the second option and you are lucky because the event we are talking about is actually handled by the Arduino MCU pretty well: it is called an interrupt.

Arduino Uno (actually the MCU at its core, the ATMega328) is capable of handling interrupts on pins 2 and 3 (so you can have 2 interrupt routines attached at the same time).

Using interrupts you can have a piece of code (the IR related part) being enabled only when pin 2 goes LOW (or HIGH).
BEWARE though and use interrupts in the proper way: `millis()` does *NOT* work within an interrupt routine and also nothing else will be enabled while executing the interrupt routing, including counting time (that's the reason `millis()` does not work).

The latter part practically means you should limit your interrupt routine to capture the IR code and return, having the printing being done within the `loop()` function whenever the IR has been decoded.

Hoping all that makes sense to you, here are some references:

[interrupts()][1]
[Interrupts][2]
[attachInterrupt()][3]

  [1]: https://www.arduino.cc/en/Reference/Interrupts
  [2]: http://playground.arduino.cc/Code/Interrupts
  [3]: https://www.arduino.cc/en/Reference/attachInterrupt


message:
How to explain the need/advantage for volatile in terms of microcontroller instruction flow

I know there are already many questions why **volatile** is used when it comes to interrupts.

But explanations like this doesn't help to picture what really happens:

> Specifically, it directs the compiler to load the variable from RAM
> and not from a storage register, which is a temporary memory location
> where program variables are stored and manipulated. Under certain
> conditions, the value for a variable stored in registers can be
> inaccurate.

Above is from the official Arduino [website][1]:

And below is the basic Atmega328 architecture:

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

*Is it possible to explain the use/advantage of volatile by comparing it to the usual declaration way considering the above architecture?*

I mean such way: If **volatile int x** is used, the CPU fetches this from this  by this way ect. And if instead **int x** is used the instruction flow works like this so forth and so on.

Unfortunately I have difficulty to understand from plain two sentence explanations.

As you see my question is about after the compilation what do we observe as a benefit inside the hardware during the instruction flow.

  [1]: https://www.arduino.cc/en/Reference/Volatile
  [2]: https://i.stack.imgur.com/svHbz.png

body:
volatile varaibles are used in Shared variables, because the flow can change whit compiler otimizations.
It's important to when you use timer's interrupt in sample.


body:
Short answer: **no**, `volatile` cannot be explained in terms of the
figure you show in your question.

Longer answer: there is no direct link between the meaning of `volatile`
and the architecture depicted in the figure. If you insist in linking
them together, it is possible to find a very _weak_ and _indirect_ link
as follows:

1. Volatile is all about preventing the compiler from doing some
optimizations when translating your program to assembly. Looking at the
generated assembly **can** help understanding the effect of `volatile`.

2. When learning the assembly language, the figure you show is helpful
in understanding the assembly instructions themselves.

As you see, the link is indirect, mostly because we are talking about
different abstraction levels. Also, the link is weak because the figure
describes specifically the AVR architecture, whereas `volatile` applies
to any architectures for which there is a C compiler.

To illustrate the first point above, here is an example program which
shows the effect of `volatile`:

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

    volatile bool volatile_flag;
    bool plain_flag;

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

    void loop()
    {
        Serial.print("Waiting for volatile flag... ");
        while (!volatile_flag) ; /* wait */
        Serial.println("done.");

        Serial.print("Waiting for plain flag... ");
        while (!plain_flag) ; /* wait */
        Serial.println("done.");
    }

As such, the program is not very interesting, it will just hang on the
first loop. But you can imagine there being some ISR that can set the
flags when some external event happens. Then the wait loops would start
to make sense, as they wait for the external event.

Here is the disassembly of the `loop()` function:

        Serial.print("Waiting for volatile flag... ");
      ce:   60 e0           ldi r22, 0x00   ; 0
      d0:   71 e0           ldi r23, 0x01   ; 1
      d2:   82 e5           ldi r24, 0x52   ; 82
      d4:   91 e0           ldi r25, 0x01   ; 1
      d6:   0e 94 b3 02     call    0x566   ; 0x566 <Print::print(char const*)>
        while (!volatile_flag) ; /* wait */
      da:   80 91 51 01     lds r24, 0x0151
      de:   88 23           and r24, r24
      e0:   e1 f3           breq    .-8         ; 0xda <loop+0xc>
        Serial.println("done.");
      e2:   6e e1           ldi r22, 0x1E   ; 30
      e4:   71 e0           ldi r23, 0x01   ; 1
      e6:   82 e5           ldi r24, 0x52   ; 82
      e8:   91 e0           ldi r25, 0x01   ; 1
      ea:   0e 94 d0 02     call    0x5a0   ; 0x5a0 <Print::println(char const*)>
        Serial.print("Waiting for plain flag... ");
      ee:   64 e2           ldi r22, 0x24   ; 36
      f0:   71 e0           ldi r23, 0x01   ; 1
      f2:   82 e5           ldi r24, 0x52   ; 82
      f4:   91 e0           ldi r25, 0x01   ; 1
      f6:   0e 94 b3 02     call    0x566   ; 0x566 <Print::print(char const*)>
        while (!plain_flag) ; /* wait */
      fa:   80 91 50 01     lds r24, 0x0150
      fe:   81 11           cpse    r24, r1
     100:   01 c0           rjmp    .+2         ; 0x104 <loop+0x36>
     102:   ff cf           rjmp    .-2         ; 0x102 <loop+0x34>
        Serial.println("done.");
     104:   6e e1           ldi r22, 0x1E   ; 30
     106:   71 e0           ldi r23, 0x01   ; 1
     108:   82 e5           ldi r24, 0x52   ; 82
     10a:   91 e0           ldi r25, 0x01   ; 1
     10c:   0c 94 d0 02     jmp 0x5a0   ; 0x5a0 <Print::println(char const*)>

The important thing to notice is how the compiler implemented the
waiting loops. The first one is essentially

    0:  lds r24, volatile_flag  ; load the flag from RAM
        tst r24                 ; test it
        breq 0b                 ; if zero, loop back

whereas the second loop is:

        lds r24, plain_flag     ; load the flag from RAM
        cpse r24, r1            ; if zero, skip the following jump
        rjmp 1f                 ; jump over the next loop
    0:  rjmp 0b                 ; infinite loop
    1:

You may appreciate the first loop has been translated to assembly in a
very literal way, whereas in the second loop the compiler optimized away
all but the first read of the variable. That could be translated back to
C as

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

    if (!plain_flag) {
        for (;;) ;  // hang in an infinite loop
    }

The compiler assumed the flag cannot be changed by some external event,
so there is no point in reading it repeatedly. The `volatile` keyword
prevents the compiler from making such assumption.

And how is all this related to your figure you may ask? Well, if you
happened to not understand the assembly code above, you could check the
[AVR Instruction Set Manual][manual] to see what each instruction does,
and **that's** when the figure becomes helpful.

[manual]: http://www.atmel.com/images/Atmel-0856-AVR-Instruction-Set-Manual.pdf


body:
Let me explain it like this. Modern compilers **optimize**. They do this to make things run faster. People would complain if they didn't, or switch to another compile that does optimize.

Here's an analogy. Let's say you are wondering how many cats your brother has. You call him up on the phone, and he says "two".

A week later your friend asks how many cats your brother has. You say "I'll call him up and ask him.".

Your friend says "Didn't you do that last week? How many did he have then?"

You reply, "Yeah, that's right. He must still have two cats, right? I've just saved the expense of a phone call!"

Not making the phone call is an **optimization** - you save time and money by not doing it. However what if your brother now has another cat? Or he gave one away? The information about the number of cats is out of date.

If your brother is a cat dealer, or frequently changes his cat configuration you might say "the number of cats my brother has is **volatile** - I'll have to call him up again to make sure of the number."

So, if something happens *behind your back* (like in your brother's house - or in a computer program in an ISR) then you need to check again each time. However if you are sure that things haven't changed (eg. in your house you would know if you got a new cat) then you can optimize by not checking each time.

I agree with Gerben's comment on this page. This is nothing to do with the compiler architecture - any more than the number of cats you have depends on the way the house is built.


message:
Setting the sampling rate for timer interrupt

I had performance problems with the data acquisition and after some reading on the web, someone told to define a timer with the frequency I need (50hz):

    // TIMER 1 for interrupt frequency 50 Hz:
    cli(); // Stop interrupts.

    TCCR1A = 0; // Set entire TCCR1A register to 0.
    TCCR1B = 0; // Same for TCCR1B.
    TCNT1  = 0; // Initialize counter value to 0.

    // Set compare match register for 50 Hz increments.
    OCR1A = 39999; // = 16000000 / (8 * 50) - 1 (must be <65536)
    // Turn on CTC mode.
    TCCR1B |= (1 << WGM12);
    // Set CS12, CS11 and CS10 bits for 64 prescaler.
    TCCR1B |= (0 << CS12) | (1 << CS11) | (1 << CS10);
    // Enable timer compare interrupt.
    TIMSK1 |= (1 << OCIE1A);

    sei(); // Allow interrupts.

But with that, I was unable to achieve good performance; I was expecting 50 reading / seconds. Luckily, I've changed for 8 bits prescaler instead of 64 and I've start to get better performance:

    // Set CS12, CS11 and CS10 bits for 8 prescaler.
    TCCR1B |= (0 << CS12) | (1 << CS11) | (0 << CS10);

But, honestly, I'm a newbie and I don't understand why!

body:
`// = 16000000 / (8 * 50) - 1 (must be <65536)` that `8` in the formula refers to the prescaler. So this formula expect you to have a /8 prescaler. But four lines below you used a /64 prescaler. So your timer runs 6.25 Hz.

When you changed it to /8, you got the correct frequency.


message:
My servo is misbehaving

I have been trying to get my 9g tower pro servo to work and no matter what i do nothing happens. I connected the servo to the arduino with the red wire to 5v, brown to ground and orange to pin 6.

    #include <Servo.h>
    Servo myServo;

    void setup(){
    myServo.attach(6);
    }

    void loop() {
    myServo.write(0);
    delay(1000);
    myServo.write(60);
    }

I have been using this code to test it.
Another weird occurrence is when i disconnect the servo it sometimes start moving very slowly even though it has now power. I dont think the Uno is broken as other projects work fine on there, are my servos fried?

body:
My guess is your drawing too much current from the Arduino 5v rail.

Try connecting the servo to it's own 5v source with of course a common ground with the Arduino.


body:
I found your problem. There is no delay at the end of the loop. So it runs `myServo.write(0)` then pauses for one second then runs `myServo.write(60)` immediately afterwards it starts the loop over and runs `myServo.write(0)` this happens before the servo has time to move.

To fix this add a delay at the end of the loop.

Try:

    #include <Servo.h>
    Servo myServo;

    void setup(){
    myServo.attach(6);
    }

    void loop() {
    myServo.write(0);
    delay(1000);
    myServo.write(60);
    delay(1000);
    }


message:
If-statement gets ignored?

I'm kind of stuck with strange behaviour of my code and I really hope, someone could help me..

**Objective**
I'm trying to build a (multiple) magnetic stirring device with which I can either control the speed via potentiometer or via serial commands from a python script from pc (usb).
When the speed is set via serial, it shouldn't be possible to interfere with the potentiometer unless a button is pressed to unlock it.

**Code**

    // Constants

    const int FanPin[7] = {2,3,5,6,7,8,9}; // PWM Pins 2,3,5,6,7,8,9 for fan
    const int PotiPin[7] = {A0,A1,A2,A3,A4,A5,A6}; // Analoge Pins 0,1,2,3,4,5,6 for potentiometers
    const int SwitchPin[7] = {30,31,32,33,34,35,36}; // Digital Pins 30, 31, 32, 33, 34, 35, 36 for switches

    // Variables
    boolean ManualLock = false; // will be true if locked by serial input
    int Fan[7][2] = { // [x][] for number of fan, [][0] for fan speed, [][1] for ManualLock
      {0, ManualLock},
      {1, ManualLock},
      {2, ManualLock},
      {3, ManualLock},
      {4, ManualLock},
      {5, ManualLock},
      {6, ManualLock}
    };
    int temp = 0; // Variable for temporary data
    int FanSpeed[7] = {0,0,0,0,0,0,0}; // Variable fan speed
    int PotiVar[7] = {0,0,0,0,0,0,0} ; // Variable for saving poti-input
    byte bfr[2] = {7,7}; // Buffer for serial data

    void setup() {

    TCCR2B = TCCR2B & 0b11111000 | 0x01; // Timer2 (Pin 9, 10) @ 31000Hz
    TCCR3B = TCCR3B & 0b11111000 | 0x01; // Timer3 (Pin 2, 3 und 5) @ 31000Hz
    TCCR4B = TCCR4B & 0b11111000 | 0x01; // Timer4 (Pin 6, 7 und 8) @ 31000Hz

    Serial.begin(9600);
    delay(100);

    // Declaration of Pin Modes
    for (int i = 0; i < 7; i++){
      pinMode(FanPin[i], OUTPUT);
      pinMode(PotiPin[i], INPUT);
      pinMode(SwitchPin[i], INPUT);
      }
    }

    void loop() {
    for (int i = 0; i < 7; i++){
      // ManualLock not active -> manual mode
      if (!Fan[i][1]){
        //Serial.print(i);
        //Serial.println(" ManualLock not active");
        PotiVar[i] = analogRead(PotiPin[i]);
        Fan[i][0] = map(PotiVar[i], 51, 1023, 60, 255);
        //Serial.println(Fan[i][0]);
      }
      //ManualLock active -> unlock by pressing button
      if (Fan[i][1]){
        temp = digitalRead(SwitchPin[i]);
        if (temp == HIGH){
          Serial.print(i);
          Serial.println(" ManualLock will be deactivated");
          Fan[i][1] = false;
          Serial.print("Fan[i][1]: ");
          Serial.println(Fan[i][1]);
        }
      }

      // fan off @ low poti setting
      if (PotiVar[i] < 50){
        Fan[i][0] = 0;
      }
    }

    // look for serial data

    if (Serial.available()){
      Serial.println("Something's there!");
      Serial.readBytes(bfr, 2);
      delay(1000);
      Serial.print("Serial data: ");
      Serial.println(bfr[0]);
    //  Serial.flush();
    }

    //Serial.print("before loop bfr[0]: ");
    //Serial.println(bfr[0]);

    for (int i = 0; i < 7; i++){
      if (i == int(bfr[0])){
        Serial.print("i: ");
        Serial.println(i);
        Fan[i][0] = int(bfr[1]); //set fan speed variable
        Fan[i][1] = true; // activate ManualLock variable
        byte bfr[2] = {7,7}; // clear buffer
        Serial.print("bfr[0]: ");
        Serial.println(int(bfr[0]));
      }
    }

    for (int i = 0; i < 7; i++){
      analogWrite(FanPin[i], Fan[i][0]); // write fan speed
      }
    }

**Error(s)**

When I send a command via my python script, the speed is set correctly and I get the following output:

    Something's there!
    Serial data: 0
    i: 0
    bfr[0]: 7
    i: 0
    bfr[0]: 7
    ...and again and again and again...

Which means, although i "reset" my buffer variable to something that should prevent entering the if-statement, it will somehow fulfill the "if (i == int(bfr[0]))" condition.. but why?
If any further information is needed, i'll happily provide that.

body:
This (inside your `for` loop) does not do what I think you think it does:

    byte bfr[2] = {7,7}; // clear buffer

You think it sets the contents of the `bfr` array you declared at the top to `{7,7}` but what it actually does is declare a new byte array in that scope, containing the values `{7,7}`. It's not used and is immediately thrown away again.

I would expect the compiler to warn about it -- does it?  (If so, take it as a lesson not to ignore compiler warnings!)

I think you want to replace it with

    bfr[0] = 7;
    bfr[1] = 7;

or something equivalent.


message:
Comparing two char array

I modified a code which replies `BAR` when I send `FOO`. The problem is the `if else` statement always lands on `else` which prints `Wrong command`. I tried comparing it to string `FOO`(??) and also comparing it to `char` `FOO` with the same buffer size but no joy. This is the code:

    #include <ESP8266WiFi.h>
    #include <WiFiUdp.h>

    const char* ssid = "##########";
    const char* password = "##########";

    WiFiUDP Udp;
    unsigned int localUdpPort = 9999;  // local port to listen on
    char incomingPacket[255];  // buffer for incoming packets
    char command_1[255] = "FOO"; //Tried same buffer size... no luck
    char replay_1[] = "BAR";
    char wrong[] = "Wrong command";

    void setup()
    {
      Serial.begin(74880);
      Serial.println();
      Serial.printf("Connecting to %s ", ssid);
      WiFi.begin(ssid, password);
      while (WiFi.status() != WL_CONNECTED)
      {
        delay(500);
        Serial.print(".");
      }
      Serial.println(" connected");
      Udp.begin(localUdpPort);
    }

    void loop()
    {
      int packetSize = Udp.parsePacket();
      if (packetSize)
      {
        int len = Udp.read(incomingPacket, 255);
        if (len > 0)
        {
          incomingPacket[len] = 0;
        }
        Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
        Udp.write(incomingPacket); // Prints the same as from icoming packet which is FOO (Debbuging)
        if (incomingPacket == command_1) { //Tried comparing to same buffer size "FOO" and string "FOO"... no luck
          Udp.write(replay_1);
        }
        else {
          Udp.write(wrong);
        }
        Udp.endPacket();
      }
    }

body:
    > if (incomingPacket == command_1)

that statement is testing if pointer incomingPacket is pointing to the same address as pointer command_1.

to compare strings, you can either use a ready-canned function (if your compiler supports it), or to define your definition of "string equality" and execute it. most likely that requires comparing size first, and the individual characters in the string until a mismatch is found, or you have exhausted one of the strings.


body:
You are comparing a `char*` to a `char*`. Array's are contiguous memory locations and the variable name for an array in this case `command_1` and `incomingPacket` point to the first element in the array. Since they are two different array's, the location of the first element in `command_1` is different than the location of the first element in `incomingPacket` so `command_1` will never equal `incomingPacket`.

In order to check if the incoming packet equals "Foo" try

    if(strcmp(incomingPacket, "Foo") == 0)

This utilizes the `strcmp()` compares two null terminated character arrays and returns 0 if they are equal.

Just ensure that the `incomingPacket` is null terminated I have never worked with this library before.


message:
Subtraction with doubles returning zero erroneously

I have a function that takes as parameter some doubles and does a subtraction operation on it. However I'm getting a result of 0 when one of the parameter is 0 for some reason.

    int calcPID(double current, double desired, double k){
      double diff;
      diff = desired - current;
      Serial.print("desired = ");
      Serial.print(desired);
      Serial.print(", current = ");
      Serial.print(current);
      Serial.print(", diff = ");
      Serial.println(diff);
      int r = (int)diff;
      return r;
    }

Output

    desired = 250.00, current = 1.69, diff = 248.31
    desired = 250.00, current = 0.00, diff = 0.00

When the current is 0.00 the result (diff) is also 0.00, when it should be 250. Can someone tell me what's going on?

body:
You are not providing the input values in the correct type:

    calcPID(0.00, 250, 0.0);

will return 0, while

    calcPID(0.00, 250.0, 0.0);

will return 250

**UPDATE**

[Here you can get a working test case][1]: it's running on a different processor, so don't expect to behave exactly as the 8bit MCU at Arduino's core.

  [1]: http://www.tutorialspoint.com/compile_c_online.php?PID=0Bw_CjBb95KQMQjc0QlhMQ1g5d0E


body:
I can't reproduce that.

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

    int calcPID(double current, double desired, double k) {
      double diff;
      diff = desired - current;
      Serial.print("desired = ");
      Serial.print(desired);
      Serial.print(", current = ");
      Serial.print(current);
      Serial.print(", diff = ");
      Serial.println(diff);
      int r = (int)diff;
      return r;
    }

    void setup ()
    {
      Serial.begin (115200);
      Serial.println ();
      calcPID (1.69, 250, 42);
      calcPID (0, 250, 42);
    }  // end of setup

    void loop ()
    {
    }  // end of loop

That gives expected output of:

<!-- language: lang-none -->

    desired = 250.00, current = 1.69, diff = 248.31
    desired = 250.00, current = 0.00, diff = 250.00

I strongly suspect you are passing NaN (not a number) or Inf (infinity) instead of zero. If you add another test line like this:

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

     calcPID (1.0 / 0, 250, 42);

Then you get the result:

<!-- language: lang-none -->

    desired = 250.00, current = inf, diff = inf

Now I know you reported getting zero, but earlier versions of the IDE printed 0 for NaN or Inf. I suggested a change to the way the libraries handle that which has been implemented in more recent versions.

[Here](https://github.com/arduino/Arduino/issues/961), for example.

---

If this doesn't answer your question, please post a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) - like I did above.


body:
@Roberto Lo Giacco The difference is, that on Arduino (IDE) are headers for *.ino done before standard C++ compilation

    #include <stdio.h> // on *.ino it is done in IDE hidden way
    int calcPID(double current, double desired, double k) ; // forward definition, for *.ino it is done in Arduino IDE hidden way
    int main()
    {
        calcPID (1.69, 250, 42);
        calcPID (0, 250, 42);
        calcPID (0.0, 250.0, 42);
        return 0;
    }

    int calcPID(double current, double desired, double k) {
      double diff;
      diff = desired - current;
      printf("desired = %5.2f, current = %5.2f, diff = %5.2f, true = %i\n", desired, current, diff, diff > 0);
      int r = (int)diff;
      printf("desired = %5.2f, current = %5.2f, diff = %i, true = %i\n", desired, current, r, r > 0);
      return r;
    }

This compiles and executes on your machine well a gives correct result same as @Nick Gammon have.

Without the definition `int calcPID(double current, double desired, double k) ;` standard C assumes definition with `ints` and makes different conversions, which leads to your "incorrect" result. So the result depends on forward definition, which Arduino does behind scene. But for *.cpp and *.h it may be different, so it would be interesting, how `bakalolo` organized his code.


message:
I2C communication, wrong response

With reference from http://www.gammon.com.au/i2c I tried the example there. However I am getting the wrong response and readings. At startup the Master will request for slave address. I should get a reading of "8" but I don't get it. Subsequently, A0 on the slave is connected to a miniature solar panel, that I have tested and it is working, however I keep getting a value -1 from it. No doubt I did modify a little bit to suit my inputs not sure if what I did affected the program.

This is the master code:

        #include <Wire.h>

    const int slaveAddressA = 8;

    enum {
      cmd_slaveAddress = 1,
      cmd_read_A0 = 2,
      cmd_read_A1 = 3
    };

    void sendCommand_toSlaveA (const byte cmd, const int responseSize)
    {
      Wire.beginTransmission(slaveAddressA);
      Wire.write(cmd);
      Wire.endTransmission();

      Wire.requestFrom(slaveAddressA, responseSize);
    }

    void setup() {

      Wire.begin();
      Serial.begin(9600);

      sendCommand_toSlaveA(cmd_slaveAddress, 1);

      if(Wire.available())
        {
         Serial.print ("Slave address is: ");
         Serial.println (Wire.read (), DEC);
        }
      else
        {
         Serial.println ("No response to slave address request");
        }

    }

    void startupTest() {
      Wire.beginTransmission(slaveAddressA);

    }

    void loop() {

      int val;

      sendCommand_toSlaveA(cmd_read_A0, 2);
      val = Wire.read();
      val <<= 8;
      val |= Wire.read();
      Serial.print("Value of A0: ");
      Serial.println(val, DEC);

      delay(500);

    }

This is the slave code:

    #include <Wire.h>

    const byte my_address = 8;

    enum{
      cmd_address = 1,
      cmd_read_A0 = 2,
      cmd_read_A1 = 3
    };

    char command;

    void setup() {

      command = 0;

      pinMode (A0, INPUT);
      digitalWrite (A0, LOW);  // disable pull-up
      pinMode (A1, INPUT);
      digitalWrite (A1, LOW);  // disable pull-up

      Serial.begin(9600);

      Wire.begin (my_address);
      Wire.onReceive (receiveEvent);  // interrupt handler for incoming messages
      Wire.onRequest (requestEvent);  // interrupt handler for when data is wanted
    }

    void loop(){
      //everything is done using interrupts
    }

    void receiveEvent(int howMany)
    {
      command = Wire.read();
    }

    void sendSensor (const byte which)
    {
      int val = analogRead (which);
      byte buf [2];

        buf [0] = val >> 8;
        buf [1] = val & 0xFF;
        Wire.write (buf, 2);
    }

    void requestEvent ()
    {
      switch (command)
      {
        case cmd_address: Wire.write(0x55); break;   // send slave address
        case cmd_read_A0: sendSensor(A0);   break;   // send A0 value
        case cmd_read_A1: sendSensor(A1);   break;   // send A1 value

       }

    }

Also I'm wondering if I have to add a "Wire.begin(8);" at the slave program setup. ---------------------------**I would like to know what did I do wrongly?**

**UPDATE**: The 2 boards are now communicating with one another. However, requested address gives a '85' instead of an '8'. As for input A0, for example it should show '700' with a little bit of variant, but now it shows a repeated pattern of e.g '0 0 0 400 500 800 1040 1040 1040 800 500 400 0 0 0'

body:
When you send 'buf', how do you know that buf[0] is transmitted first and buf[1] is transmitted second ? Not long ago a bug in Wire library was fixed and it is now allowed to use multiple Wire.send() in the requestEvent() function. I suggest to send two bytes in sendSensor() in the Slave without using the 'buf'.

When you request the Slave addres, you send 0x55. That is not the Slave address. Do you receive 0x55 ?

It is not needed to remove pullup resistors from the analog input pins. It is also not needed to set the pinMode for those pins. You can use analogRead() without something else.

Did you connect the GNDs ? And did you connect SDA to SDA and also SCL to SCL. Which Arduino boards do you use ? Do you know that you can start the Arduino IDE twice, each connected to a board and each with its own serial monitor. That way you can work on both sketches at the same time.
As soon as the Slave is running with Wire.begin(8), the Master can run a i2c_scanner and it should find I2C address 8. That is the first test to verify that the I2C bus is working.


message:
Understanding Soil Moisture Sensor Values

I have soil Moisture sensor inserted into the pot soil, wet in state. (not too damp) and soil moisture sensor is connected to Arduino Mega 2560.

This is the soil moisture sensor I am using:

[![Analog Soil Moisture Sensor][1]][1]

Soil Moisture Sensor VCC is fed by 4.95 coming from Mega's 5 volt power out and soil moisture signal is connected to A0.

below are the readings

    +---------------------+-------------------+-----------------------+
    | timeStamp           | pot1_soilMoisture | pot1_avg_soilMoisture |
    +---------------------+-------------------+-----------------------+
    | 2017-01-26 14:31:19 |               825 |                    80 |
    | 2017-01-26 14:32:19 |               816 |                    80 |
    | 2017-01-26 14:33:20 |               828 |                    83 |
    | 2017-01-26 14:34:20 |               826 |                    82 |
    | 2017-01-26 14:35:20 |               820 |                    79 |
    | 2017-01-26 14:36:20 |               833 |                    83 |
    | 2017-01-26 14:37:20 |               463 |                    46 |
    | 2017-01-26 14:38:21 |               546 |                    32 |
    | 2017-01-26 14:39:21 |               156 |                    26 |
    | 2017-01-26 14:40:21 |               157 |                    22 |
    | 2017-01-26 14:41:21 |               509 |                    23 |
    | 2017-01-26 14:42:22 |               204 |                    25 |
    | 2017-01-26 14:43:21 |               226 |                    26 |
    | 2017-01-26 14:44:21 |               190 |                    30 |
    | 2017-01-26 14:45:22 |              1023 |                    84 |
    | 2017-01-26 14:46:22 |               604 |                    83 |
    | 2017-01-26 14:47:22 |               773 |                    79 |
    | 2017-01-26 14:48:22 |              1023 |                    80 |
    | 2017-01-26 14:49:23 |               599 |                    77 |
    | 2017-01-26 14:50:23 |               766 |                    82 |
    | 2017-01-26 14:51:23 |               579 |                    81 |
    | 2017-01-26 14:52:23 |               729 |                    74 |
    | 2017-01-26 14:53:24 |              1023 |                    82 |
    | 2017-01-26 14:54:24 |               795 |                    80 |
    | 2017-01-26 14:55:24 |               651 |                    77 |
    | 2017-01-26 14:56:24 |               765 |                    83 |
    | 2017-01-26 14:57:25 |              1023 |                    81 |
    | 2017-01-26 14:58:25 |                 0 |                    60 |
    | 2017-01-26 14:59:25 |               921 |                    30 |
    +---------------------+-------------------+-----------------------+
    1439 rows in set (0.02 sec)

I got three kind of readings of the sensor:

- `pot1_soilMoisture` reading from 825 to 833 is when the sensor was dipped in water.
- `pot1_soilMoisture` reading from 463 to 190-1023 is when soil moisture sensor was in air.
- `pot1_soilMoisture` reading from 604 to last 921 is when soil moisture sensor is in soil. The soil is moist/wet.

I don't understand how to be definitive state of soil with such values?

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

body:
I had this same problem when I began experimenting with soil moisture readings. I noticed that the readings from the sensor can vary widely when not hooked up correctly, or when other nearby objects are somehow interfering.

For instance when I put a SparkFun breakout similar to yours in dry soil and continuously take readings every 50ms, the signal oscillates from 0 to 50, and simply touching the soil with my finger can affect the signal due to the electricity in my body. If you have a metal pot on a metal table, that could be affecting your readings. There's a lot to consider!

However, once I water the soil and let it soak in, the reading generally becomes much more stable. Below I included a real-time plot using a plant I watered about 24 hours ago. [Here's how I set up my soil moisture sensor, including code.][2] The readings are taken every 60s and the plotter repeats the old reading until a new one is taken. There's very little deviation when all connections are secure and the soil moisture is evenly distributed.

[![Arduino IDE Serial Plotter output showing a consistent reading between 875 and 877][1]][1]

In general, the specs for the sensor will inform you on what kind of signal to expect. Based on your sample data I suspect yours is a 10-bit signal from 0-1023, so 800 range means the soil is quite moist. If you *just* watered the plant, then the water content around the sensor will change as it seeps through the soil, leading to fluctuations when measuring. Give the soil a few hours to absorb the moisture and try measuring again.

  [1]: https://i.stack.imgur.com/YLHC9.png
  [2]: https://chrisruppel.com/blog/arduino-soil-moisture-sensor/


message:
how does a bluetooth on android works and what are the best alternative in saving data receive from bluetooth?

Can anyone confirm this for me although I have tested it myself but when I send a string of data from my android app and send it to arduino say for example `data = bluetoothPort.read();` inside an if statement then when I try to use the `data` in another if statement for example `Serial.print(data);` inside another if statement it will only show a blank line which let me believe that none of the data are saved. also when a receiving a string of data for example a string of abcde and send it to arduino for example `data = bluetoothport.read()` and then `Serial.print(data)` the serial monitor shows abcde as expected but what really happens is data has the value of a then prints then replace by b then print then replace by c then print then replace by d then print then replace by e. Am I wrong or somehow right? are there any work around or parts I need that will make me store data as a whole so that I can use it for other thread or a better code to store string of data?

    #include <IRremote.h>
    #include <SoftwareSerial.h>

    SoftwareSerial bluetoothPort(4,5);
    const int RECV_PIN = 12;
    const int SEND_PIN = 13;

    IRsend irsend;
    IRrecv irrecv(RECV_PIN);

    decode_results results;
    char data;

    void setup()
    {
       bluetoothPort.begin(9600);
       Serial.begin(9600);
       irrecv.enableIRIn();
    }

    void loop()
    {
       if (bluetoothPort.available() > 0)
       {
           data = bluetoothPort.read(); //received bluetooth data from android
       }

       if(irrecv.decode(&results))
       {
           irreceived(); //received IR code from a remote then sends it to my android
           irsend.sendNEC(data, 32)
       }
     }

     void irreceived()
     {
         Serial.println(results.value, HEX);   //receive value of 489010
         bluetoothPort.println(results.value, HEX); //send value to android
         irrecv.resume();
     }

so the above is a simple sketch that receive data from a remote controller then send it to my android app then when I resend it back to my arduino I would like the data to be able to receive all the data instead of saving it per letter/number and also be able to store it for other statement to use.

body:
Serial communications *only consist of one character*. That is what serial is - the sending of one character at a time.

How you then deal with those characters, combining them into strings, interpreting them as numbers, whatever, is completely up to you to program.

There is no such thing as a string in serial communications. There is only the character.

The Arduino API has a few (badly implemented IMHO) helper functions that can get a whole string (kinda), but it is much better (both from a learning perspective and an implementation perspective) to do it yourself.

I have a little tutorial [here](https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/) that may help you get to grips with it.


message:
Is there a way to keep a program on the Arduino after uploading new sketches?

I am looking for a way to keep a program on my Arduino Nano 3.0, after uploading new sketches on it. I would like to have a program on it that will control th screen and buttons at it. The user will choose one of the programs displayed on the screen and execute/pause/stop them. These programs will be uploaded on the Arduino, while the previous programmes stay.

If you are familliar with the Lego Mindsdorm microcontroller, you probably know waht I am looking for.

Is there a way to do that.

body:
I'm not familiar with Lego Mindstorm, but I think I understand what you want and I am certain there is a way to do it, but I don't think it will be easy or even practical and I can't tell you exactly how to do it.

I'm pretty certain there will be a way to load a 'module' into memory and then make the program call that address.  I haven't got a clue how you would do it though, sorry.  GCC doesn't have a concept of DLLs like window does, but it does have shared libraries.  Or you might look at just reading a block of memory in.

Other approaches might be to have all the 'programs' as functions within you main program and call them depending on the user's input.  You can only do this if the 'programs' are small enough.

If you can refactor your 'programs' to extract the common code into functions and then have a data file (which could be read at runtime) that called the functions for each of your programming.  Basically  invent your own higher level programming language.  This wouldn't work if your code was very different and you could factor it down to a small enough number of functions.

Would it be possible to just have a number of hex files (compiled programs?) all of which have the common screen/button handler in and then have the special code for the appropriate program.  These could all be stored on an SD card and then loaded into memory by a second Arduino (sounds plausible to me, I'm sure someone will tell me whats wrong with that idea.)

An alternative based on the inverse of the above solution would be to have one Arduino to control the screen/buttons and it programs a second Arduino with the specialist code that is connected to the rest of your kit.


body:
The Arduino paradigm uses two programs on the target.  The boot loader and the application.  The processor is agnostic WRT this differentiation and runs the entire code set as one large application.

To put a 2nd application on an embedded processor is feasible. However, you would have to be intimately knowledgeable about how Arduino SDK works as well as the boot loader as you would have to create new features to relocate code normally found at fixed locations.  A rather involved task.

Instead, consider simply adding your utility code to your application code in the Arduino SDK and replace the utility code already on the processor with the new image.


body:
You want something like this using the serial monitor:

    if((homeMenuActivated) == true)
    {
      Serial.println ("Program Number 1");
    }

I am kind of glad you asked this, as I am working on a similar program with arduinos that can do the same thing you want.