message:
Should I use a loop instead of an If statement?

I have a simple sketch that tests input from 2 touch sensors and outputs to 2 relays (if a sensor is touched, trigger the respective momentary relay).  It has been a bit quirky to say the least.  perhaps I need to adjust delays or adjust sensitivity of the touch sensors, but I feel that maybe the coding could be more efficient.  Would using a WHILE or DOWHILE loop work better than an IF statement for this?  It seems like there is a timing issue between the relay and the sensor.  When I hit the sensor, the relay triggers immediately, but then it doesn't shut off right away.  Also if both sensors are made at the same time, I am seeing only 1 relay trigger or neither.  I am trying to eliminate the code as my failure point. I have the code printing to the serial monitor to show "Sensor 1 touched" or "Sensor 2 touched", and sometimes that triggers once and sometimes it will print multiple times.

    int touchPin1 = 2; //Touch sensor 1
    int touchPin2 = 4; //Touch sensor 2
    int val_1 = 0;
    int val_2 = 0;
    int relayPin1 = 8; //Relay 1
    int relayPin2 = 9; //Relay 2

    void setup()
    {
      Serial.begin(9600);
      pinMode(touchPin1, INPUT);
      pinMode(touchPin2, INPUT);
      pinMode(relayPin1, OUTPUT);
      pinMode(relayPin2, OUTPUT);

    }

    void loop() {
      digitalWrite(relayPin1, LOW);
      digitalWrite(relayPin2, LOW);
      val_1 = digitalRead(touchPin1);
      val_2 = digitalRead(touchPin2);
      if(val_1 ==1)
      {
      Serial.println("Pad 1 Touched");
      digitalWrite(relayPin1, HIGH);
      }
      if(val_2 ==1)
      {
      Serial.println("Pad 2 Touched");
      digitalWrite(relayPin2, HIGH);
      }
      delay(100);
      //Serial.println();
    }
  Basically I am asking if there is a more efficient way to code this.

Touch Sensors: [Adafruit Standalone Momentary Capacitive Touch Sensor Breakout Adafruit Part Number: 1374][1]

Relays: [SunFounder Relay Module for Arduino and Raspberry Pi 5V DC Trigger by HIGHLO (HIGH Trigger)][2]

  [1]: https://www.amazon.com/gp/product/B00QSJ1FW4/ref=oh_aui_detailpage_o09_s00?ie=UTF8&psc=1
  [2]: https://www.amazon.com/gp/product/B0151F3A9Q/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1

body:
What you are lacking is the `else` concept:

* If a touch pad is pressed, then
  * Turn the relay on
* **else**
  * Turn the relay off

Rather than turn the relay off *every iteration*, you only turn it off *if the touch pad is **not** pressed*.

That can be written as:

    val_1 = digitalRead(touchPin1);

    if(val_1 ==1)
    {
      Serial.println("Pad 1 Touched");
      digitalWrite(relayPin1, HIGH);
    } else {
      digitalWrite(relayPin1, LOW);
    }

If you want your messages to be more meaningful and not spam, then you can remember the previous state and only do things if the state changes:

    static uint8_t oldVal1 = LOW;

    uint8_t val1 = digitaRead(touchPin1);

    if (val1 != oldVal1) {
        oldVal1 = val1;
        if (val1 == HIGH) {
            Serial.println("Pad 1 Touched");
            digitalWrite(relayPin1, HIGH);
        } else {
            Serial.println("Pad 1 Released");
            digitalWrite(relayPin1, LOW);
        }
    }


sender: user

message:
3 digit 7 segment display

I have 3 digit 7 segment display with 10 pins [![I found this image pinout][1]][1]

I found this image pinout but it not working for me I need to know the pin out of this display

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

sender: assistant

body:
you are supposed to multiplex this display. Put a current limiting resistor between pins 10, 8 and 6 and the arduino and all the rest can be connected directly.

First pull pin 10 low and use pins 7,9,2,3,4,1 and 5 to set the segments of the first digit.

Then put 10 high and 8 low and again use pins 7,9,2,3,4,1 and 5 to set the segments of the second digit.

repeat with pin 6 pulled low.

You can test the display with a battery and resistor. Connect them in series and put positive on the lower left pin and negative on the upper left pin. That should light up the top left vertical segment on the left most digit. You may need to turn the display around.


message:
Right PIN to activate a wireless relay with ESP8266 ESP-01

I'm trying to program an ESP8266 ESP-01 module to let it connect to my personal wifi network and activate a [wireless relay][1] that I've bought.

No problems with Wifi connection so I've omitted the code about it, my problem is to find what is the right PIN to set to LOW/HIGH to control my relay.
Setting relayPin to 1 as shown in this code works and with it I can see the embedded LED turning on and off.

    const int relayPin = 1;

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

    void loop() {
        Serial.println("Close Relay for 100 ms and then Open");
        digitalWrite(relayPin, LOW);
        delay(100);
        digitalWrite(relayPin, HIGH);
        delay(200);
    }

Surfing the web I've found the following diagram about the ESP8266 ESP-01 module:

[![ESP8266 ESP-01 module][2]][2]

I've tried to set relayPin to 0 or to 2 but the relay doesn't activate/deactivate.

So, what is the right PIN number to set in my relayPin constant to control the GPIO0 port?

The relay works succesfully if I give him +3.3V on GPIO0 with an external power.

Thanks in advance

  [1]: https://aliexpress.com/item/ESP8266-5V-WiFi-relay-module-Things-smart-home-remote-control-switch-phone-APP-ESP-01/32821697306.html
  [2]: https://i.stack.imgur.com/KVtEM.jpg

body:
Looking at [better pictures of the PCB on ALIExpress](https://m.es.aliexpress.com/item/32842108327.html) it looks like GPIO0 is used to switch the relay.

What that pin maps to, though, depends on what board you have selected in the IDE.


body:
*most* GPIO pins on the ESP8266 "boot" up in **INPUT** mode

You'll need to

    const int relayPin = 0; // or 2

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

The reason GPIO1 works is because GPIO1 is serial TxD - so, it's set to output


body:
1 solution I did is to use rx [GPIO 3] to drive relay. For this,

 1. Need to short the GPIO 0 and GPIO 3(Rx) pin on the relay board.
 2. While inserting the ESP-01, either bend the GPIO 0 or completely remove it from ESP-01 board. Be careful, on removing you wil find difficult to program the ESP-01 module again because GPIO 0 should go low at boot time to enable program mode. And this is the reason why GPIO 0 is HIGH on boot.

If you want, you can try this product
[Smart Switch. Android Based ESP01 Relay Module][1]

  [1]: https://www.amazon.in/dp/B07KTZZK34?m=A3HAGIAPX2OISQ


body:
I had this exact same problem. Solution was to put 5 volts on the relay.
There is a regulator on the wireless relay that gives 3v to the ESP-01 and not 5v. But 5v is required for the relay to work.


message:
Compiling with -flto and -nostartfiles results in no program at all

Towards developing my own bootloader I've stumbled over an issue with `avr-gcc`. I am trying to compile my code with the compiler flags

    -flto          #to enable link time optimization
    -nostartfiles  #to omit the interrupt vector table

My bootloader consists of multiple files which are used depending of compile flags. All the sources are being compiled and linked while the code path only leads to some portions of them. So I wanted to get rid of the dead code and `-flto` (being a newer development) creates a much smaller machine code size than `-ffunction-sections -fdata-sections` with `-Wl,--gc-sections -Wl,--print-gc-sections`.

But when it comes to further reducing the machine code size by removing the interrupt vector table using `-nostartfiles`, the complete code gets optimized away leaving me with a zero byte output.

Has anyone experienced the same issue with that compiler flag combination?

body:
As @MaximilanGerhardt wrote in his comment. LTO was optimizing away too much of the code. Usual programs start with the interrupt vector table that in case of a regular reset or startup point to the `main` function. That is why the compiler knows that `main` has an entry point and is used. The actual program starts at the table.

Removing  the interrupt vector table with `-nostartfiles` causes the compiler not to know that `main` is used at all and optimizes it away.

To give the compiler a hint `__attribute__((used))` has to be placed at all methods that have to stay and there is no code path leading to them otherwise.


message:
comparison in a time sequence

in an Arduino sketch a user is invited to input a number representing a time in the format HH:MM,  this number is to be added at the end of an ordered and limited sequence of times

--the first input (lower limit) can be any time within the 24 hours,

--the upper limit is calculated as lower_limit+period; with period being 1,2,3,4,6,8,12 or 24 hours,

--and to be accepted, the input must verify that it is chronologically after the previous element, and that it's within the given period;

for example if first element is 20:00 and the period is 8, the upper limit will be 20+8=28 wich is 04:00; both 21:00 and 03:00 are accepted, where'is 19:00, 05:00, 09:00, 17:00, ... are rejected.

without any information on the 'day', i did not find any suitable algorithm, and none of the available Arduino libraries is useful in this case.

any link, or tip,...

body:
Here is the basic idea and a sample implementation for solving the problem:

The problem is: Given a start time `time1` and a period `period`, each described by a pair of `(hour,minute)`, how can we check whether another time `time2` is within `time1` to `time1 + period`?

First we can see that we given a `(hour, minute)` pair we can compute the total number of minutes as `totalMinutes = 60*hour + minute`.

Then we can observe that there two distinct cases that we must check:

* the entire "time check period", that is, `time1` to `time1 + period` is within `00:00` to `24:00` without overflowing past `24:00` when we simply add the times. then, we can use a simple bounds check worded as "`time2` must be greater than `time1` and less or equal to `time1 + period` when comparing total minnutes.
* `time1 + period` overflows past `24:00`. We consider an example of  `time1= 20:00` and `period = 8:00`. Thus all valid times are from `20:00` to `04:00` with an implicit "wrap around" at 24:00 to 00:00. We can see that there are now two time-intervals we must check: Everything from `20:01` to `24:00` and from `00:00` to `04:00` is valid. Thus we can derive the the bounds in minutes again. We can obtain the `04:00` by computing `20:00 + 08:00 modulo 24:00`. The C operator `%` is used to compute the residue of the division by a certain number. I.e. `28 % 24 = 4` because `28 / 24 = 1 residue 4`. This is  called modulo-arithmetic.

The following C++ program demonstrates the solution:

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

    #include <cstdio>

    /* returns whether time2 defined by hour2:minute2 is within the period time1 = hour1:minute1 to time1 + period. */
    bool is_time_within_period(
     int hour1, int minute1,
     int hour2, int minute2,
     int periodHour, int periodMinute) {

      //Reject garbage input
      if(hour1 > 24 || hour2 > 24
       || minute1 > 60 || minute2 > 60
       || periodHour > 24 || periodMinute > 60) {
        //TODO throw error message
        return false;
      }

      //Convert hours and minutes into absolute minutes. One hour is 60 minutes.
      int time1Minutes = 60 * hour1  + minute1;
      int periodMinutes = 60 * periodHour + periodMinute;
      int time2Minutes  = 60 * hour2 + minute2;

      int periodEnd = time1Minutes + periodMinutes;

      //If the start time plus the period time is over 24:00 there is a wrap-around the we need to consider.
      bool wrapAround = false;
      if( periodEnd > (24 * 60)) {
       wrapAround = true;
      }

      bool result = false;

      //printf("Wrap: %d Period end %d\n", wrapAround, periodEnd);

      if(!wrapAround) {
       //if there is no wrap-around we can just compare the total minutes against each other
       //time1 must be after time2 but before (time1 + period).
       result = time2Minutes <= (time1Minutes + periodMinutes) && time2Minutes > time1Minutes;
      } else {
       //There was a wrap around, i.e. start time + period was beyond 24:00.
       //We need to make two comparisons: is it in the time period from time1Minutes to 24:00?
       result = time1Minutes < time2Minutes && time2Minutes <= (24 * 60);

       //the result can also be okay if it from the time from 00:00 to the remaining period
       //use the module operator here. This transforms e.g. 28:00 would be reduced to 04:00. (modulo 24 hours calculated in minutes)
       int upper = (periodEnd % (24 * 60));
       //printf("Upper: %d (d:d)\n", upper, (upper / 60), upper % 60);
       result |= time2Minutes >= 0 && time2Minutes <= upper;
      }

      return result;
    }

    int main() {

     const int hourStart = 20;
     const int minuteStart = 0;

     const int periodHours = 8;
     const int periodMinutes = 0;

     //play around with these values
     const int compareTimeHour  = 4;
     const int compareTimeMinute = 0;

     printf("Start: d:d\n", hourStart, minuteStart);
     printf("Period: d:d\n", periodHours, periodMinutes);
     printf("Check time: d:d\n", compareTimeHour, compareTimeMinute);

     bool res = is_time_within_period(hourStart, minuteStart, compareTimeHour, compareTimeMinute, periodHours, periodMinutes);

     if(res) {
      printf("Time is within bounds\n");
     } else {
      printf("Time is not within bounds\n");
     }

     printf("Hello\n");

     return 0;
    }

The function `is_time_within_period` has no dependencies and can thus be copy-pasted into any Arduino sketch.

Let the start time be `20:00` and the period `04:00`. Then feeding the program different times to compare against lets us see that it indeed works.

    Start: 20:00
    Period: 08:00
    Check time: 20:00
    Time is not within bounds

    Start: 20:00
    Period: 08:00
    Check time: 20:01
    Time is within bounds

    Start: 20:00
    Period: 08:00
    Check time: 04:00
    Time is within bounds

    Start: 20:00
    Period: 08:00
    Check time: 04:01
    Time is not within bounds


message:
Android phone can't get ESP8266WebServer page if Content-Length > 1460

I uploaded the following sketch to my ESP8266:

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

    ESP8266WebServer server(80);
    String toServe;

    void serveShortString() {
        server.send(200, "text/plain", "short string!");
    }

    void serveLongString() {
        server.send(200, "text/plain", toServe);
    }

    void setup() {
        WiFi.softAP("test");

        // fill string to serve:
        toServe.reserve(3000);
        for(int i=0; i<150; i++) toServe += "1234567890123456789\n";

        server.on("/long", serveLongString);
        server.on("/short", serveShortString);
        server.begin();
    }

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

It serves a short message on `/short` and a long message (3000 chars) on `/long`.

The `/short` page works everywhere: Windows, Desktop Linux (Fedora) and Android.
The `/long` page, on the other hand, only works on Windows and most of the time on desktop Linux. It *never* works on Android. I tried two phones.

I captured the network traffic on my Android phone using tPacketCapture. This is the result:
[![enter image description here][1]][1]

When trying to get `/short`, everything works fine. When trying to get `/long`, only the header comes through but the content never arrives. As I said, everything works fine on Windows and (most of the time) on Desktop Linux. Any idea what's going wrong?

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

body:
The solution is to add the following line to `platformio.ini`:

    build_flags = -D PIO_FRAMEWORK_ARDUINO_LWIP2_LOW_MEMORY

----

I noticed that the same sketch works without a problem when building with the Arduino IDE, so I checked the differences in building with platformio and the Arduino IDE.

Turns out the relevant difference is that the Arduino IDE uses lwIP 2 by default, while platformio uses 1.4, which seems to have this bug (the same bug appears when using the Arduino IDE with lwIP 1.4).

The build flag above tells platformio to use lwIP v2.


message:
ESP.deepSleep() - over and over?

Important note: the esp.deepsleep function uses microseconds, not milliseconds.

I posted another question [here][1] asking for clarification on how an RTC can be used to put a NodeMCU 12 to sleep for a long time (~24hrs or more).

This question concerns the use of ESP.deepSleep([microseconds]) with the NodeMCU 12 board.  There is a discussion [here][2] and I have followed the advice but have been unable to successfully implement the ESP.deepSleep() function using the Arduino IDE and a NodeMCU 12 board.

Initial findings:

-Connecting gpio16 (D0) to the RST pin causes a reset immediately upon entering sleep.  The entire boot process and loop are repeated over and over again.

-Simply using the ESP.deepSleep() function without gpio16-to-RST generates gibberish on the serial monitor and illuminates the red led on the board.

My code is here (I just drop "deepsleep();" where I want the sleep process to begin):

    void deepsleep() {
      Serial.println("sleeping hr 1");
      ESP.deepSleep(3600000); //1hr
      delay(100);
      Serial.println("sleeping hr 2");
      ESP.deepSleep(3600000); //2hr
      delay(100);
      Serial.println("sleeping hr 3");
      ESP.deepSleep(3600000); //3hr
      delay(100);
      Serial.println("sleeping hr 4");
      ESP.deepSleep(3600000); //4hr
      delay(100);
      Serial.println("sleeping hr 5");
      ESP.deepSleep(3600000); //5hr
      delay(100);
      Serial.println("sleeping hr 6");
      ESP.deepSleep(3600000); //6hr
      delay(100);
      Serial.println("sleeping hr 7");
      ESP.deepSleep(3600000); //7hr
      delay(100);
      Serial.println("sleeping hr 8");
      ESP.deepSleep(3600000, WAKE_RF_DEFAULT);  //8hr
    }

What is wrong with this approach and why am I (apparently) causing an error?

  [1]: https://arduino.stackexchange.com/questions/52263/using-rtc-to-sleep-for-24hrs?noredirect=1#comment108100_52263
  [2]: https://community.blynk.cc/t/esp-deep-sleep/5622/8

body:
Use a resistor between GPIO16 and RST. I usually use a 470 Ohm resistor. Shorting the pins with a wire does not work.

[https://www.esp8266.com/viewtopic.php?t=14350#p64510](https://www.esp8266.com/viewtopic.php?t=14350#p64510)

Maximum deep sleep is about 71 minutes. 3600000 microseconds = 3.6 seconds, not 1 hour. 1 hour in microseconds is 3600000000UL.

As mentioned in the comments, waking from deep sleep on the ESP8266 is a hardware reset so execution begins at the start of the setup function.


message:
Arduino Due & Spec gas sensor - how to choose specific information from a stream of incoming bytes to store

I'm trying to build an air pollution sensor for a college project, with an Arduino Due and a series of Spec Sensors digital gas detectors. However, I'm having a little trouble getting the first one of them (Carbon Monoxide, [https://www.spec-sensors.com/product/digital-co-sensor/][1]) to behave, before I can run multiple. As they're all the same sensor setup but for different gasses, once I get the first one working, the rest should follow easily.

The code's very simple, as it uses Spec's own command system - sending the letter "c" to the sensor forces it to take one reading per second for as long as the sensor is powered, and then the serial monitor displays whatever comes back:

        void setup() {
          // sensor running via Serial1
          Serial.begin(9600);
          Serial1.begin(9600);
          Serial1.print("c");
        }

        void loop() {
          if(Serial1.available()!=0)
          {
            Serial.write(Serial1.read());
          }
        }

My problem comes with the data that's being returned. The gas reading is present, but so is a lot of superfluous information that I don't need. According to the sensor's tech document, the information returned is: serial number, reading (ppb), temperature, humidity, raw voltages, and amount of time the sensor has been running for. In the serial monitor, it looks like this:

[![output in serial monitor][2]][2]

Right now, all I want is the reading in ppb (the second value), either as the only data coming through or being stored, so that it can then be used in calculations like averages per hour. The trouble I have is that this information appears to be coming through as a stream of individual bytes, and in this format I'm having difficulty working out an effective way to specify which information I want to store, and which I want to ignore.  I've been trying, for example, to come up with a way to specify that the first 14 bytes (serial number, comma, space - as this will always be the same length) should be ignored, and then the next series (up until the next comma - as this reading could be 4-6 digits) be stored as an int, or something, but I just can't seem to get anywhere no matter what I try. Does anyone have any suggestions?

  [1]: https://www.spec-sensors.com/product/digital-co-sensor/
  [2]: https://i.stack.imgur.com/CXfLk.png

body:
Since the length of each data varies, you should extract data using spererator like comma in the stream.

**First**, get one data line from sensor. Read the string until the "Line feed(LF)" character or "Carriage Return(CR)" character appears. located at the end of line(EOL), these two characters seperates each string by changing line. Without these two characters, the monitor shows the stream like this(no line change).

> 102617010933, 8486, 22, 35, 13464, 25716, 21962, 00, 00, 20, 06102617010933, 87216, 22, 35, 13576, 25223, 21442, 00, 00, 20, 07

So you can see there are CR, LF characters at the EOL. Utilize CR or LF as a terminator of ReadStringUntil() function.
https://www.arduino.cc/en/Serial/ReadStringUntil

**Second**, parsing process. This process is extracting data you want from `strtok()` function. strtok() is from C language. It divides string by seperator characters.
https://stackoverflow.com/questions/3889992/how-does-strtok-split-the-string-into-tokens-in-c?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

**Lastly**, utilize the data and repeat whenever sensor sends the data.

I'm not expert at coding. I haven't tested the code below. But this code would be helpful.

    int data[12];
    int isDataReceived = false;

    void setup(){
      Serial.begin(9600);
      Serial1.begin(9600);
      Serial1.write('c');
    }

    void loop(){
      while(Serial1.available()>0) {
        String inString = Serial1.readStringUntil('\n');
        char * pch = strtok(inString, ","); //Serial number would be ignored
        for(int i=0; pch != NULL; i++) {    //following data are stored in data[12] string
          pch = strtok(NULL, ",");
          data[i] = atoi(pch);
        }
        isDataReceived=true;
      }
      if(isDataReceived) {
        Serial.print("Data:");
        Serial.println(data[0]); //just example code. You may see ppb on the serial monitor.
        isDataReceived=false;
      }

    }


message:
when i compile this code it always 'sendCommand' was not declare in this scope..plzz help

#include <SoftwareSerial.h>
    #define DEBUG true

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

    void setup() { // Open serial communications and wait for port to open:
      Serial.begin(9600); //for monitoring purposes

      sendCommand("AT+CIFS+RST\r\n", 2000, DEBUG); // reset module
      sendCommand("AT+IPR=115200\r\n", 1000, DEBUG);
      sendCommand("AT+CWMODE=1\r\n", 1000, DEBUG); // configure as access point
      sendCommand("AT+CWJAP=\"ABCDEFG\",\"12345678\"\r\n", 3000, DEBUG); //connect to a network with name ABCDEFG with password 12345678
      delay(1000);
      sendCommand("AT+CIFSR\r\n", 1000, DEBUG); // get ip address
      sendCommand("AT+CIPSTA=\"192.168.43.16\"\r\n", 1000, DEBUG);
      sendCommand("AT+CIPMUX=1\r\n", 1000, DEBUG); // configure for multiple connections
      sendCommand("AT+CIPSERVER=1,6625\r\n", 1000, DEBUG); // turn on server on port 6625
      Serial.println("Server Ready");

    }

    void loop() { // run over and over
      if (esp8266.available()) {
        if (esp8266.find("+IPD,0,")) {
          delay(10);
          esp8266.find(":");
          delay(10);
          char letter = esp8266.read();
          Serial.print(letter); //for monitoring purposes
          //Gets the value/char from android app
        }

    String sendCommand(String command, const int timeout, boolean debug) {
      String response = "";
      esp8266.print(command); // send the read character to the esp8266
      long int time = millis();
      while ((time + timeout) > millis()) {
        while (esp8266.available()) {
          // The esp has data so display its output to the serial window
          char c = esp8266.read(); // read the next character.
          response += c;
        }
      }

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

body:
In `loop` you have three opening braces and one closing brace. This won't end well:

    void loop() { // run over and over
      if (esp8266.available()) {
        if (esp8266.find("+IPD,0,")) {
          delay(10);
          esp8266.find(":");
          delay(10);
          char letter = esp8266.read();
          Serial.print(letter); //for monitoring purposes
          //Gets the value/char from android app
        }

Two more closing braces would fix it.


message:
making a LCD dice for catan

when I go to upload the code, I get

     Arduino: 1.8.5 (Windows Store 1.8.10.0) (Windows 10), Board: "Arduino/Genuino Uno"
    C:\Users\taran\Documents\Arduino\dice in progress\dice in progress1\diceinprogress\diceinprogress.ino:1:25: fatal error: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\cores\arduino/"DFRkeypad.h": Invalid argument
    #include <"DFRkeypad.h">
                         ^
    compilation terminated.
    exit status 1 Error compiling for board Arduino/Genuino Uno.

and the code is

    #include <"DFRkeypad.h">
    #include <LiquidCrystal.h>
    LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
    const char* DFRkeypad::sKEY[]=                          { "---",       "Right",   "Up", "Down", "Left", "Select", "???" };
    const int DFRkeypad::iARV_VALUES[DFRkeypad::eNUM_KEYS]= { 1023,        0,         143,  328,    504,     740,      -1   };
    int btnSELECT;

    void setup() {
      lcd.begin(16, 2);
      lcd.setCursor(1, 0);
      lcd.print("Roll the dice!");
    }

    void loop() {
    while (btnSELECT == 0){

      delay (50);
      buttonState = analogRead(btnSELECT);
    }

     case btnSELECT:
         {
         lcd.print("Rolling dice");
           diceOne = random(1, 7);
           diceTwo = random(1, 7);
         break;
        }
    }

body:
In C/C++ you either use the `#include` pre-processor statement in the form of

    #include "someFile.h"

or

    #include <someFile.h>

The form

    #include <"someFile.h">

is not legal. You must correct it to one of the two forms above.

The difference between those forms is explained in https://stackoverflow.com/a/77092/5296568.


message:
i uploaded the code but when i open the serial monitor, but the 'sendCommand' isn't working in serial monitor...plzz help

#include <SoftwareSerial.h>
    #define DEBUG true

    SoftwareSerial esp8266(2, 3); // RX, TX

    void setup() { // Open serial communications and wait for port to open:
    Serial.begin(9600); //for monitoring purposes
    esp8266.begin(9600);

      sendCommand("AT+CIFS+RST\r\n", 2000, DEBUG); // reset module
      sendCommand("AT+IPR=115200\r\n", 1000, DEBUG);
      sendCommand("AT+CWMODE=1\r\n", 1000, DEBUG); // configure as access point
      sendCommand("AT+CWJAP=\"ABCDEFG\",\"12345678\"\r\n", 3000, DEBUG);//connect to a network with name ABCDEFG with password 12345678
      delay(1000);
      sendCommand("AT+CIFSR\r\n", 1000, DEBUG); // get ip address
      sendCommand("AT+CIPSTA=\"192.168.43.16\"\r\n", 1000, DEBUG);
      sendCommand("AT+CIPMUX=1\r\n", 1000, DEBUG); // configure for multiple connections
      sendCommand("AT+CIPSERVER=1,6625\r\n", 1000, DEBUG); // turn on server on port 6625
      Serial.println("Server Ready");

      }

      void loop() { // run over and over
      if (esp8266.available()) {
      if (esp8266.find("+IPD,0,")) {
      delay(10);
      esp8266.find(":");
      delay(10);
      char letter = esp8266.read();
      Serial.print(letter); //for monitoring purposes
      //Gets the value/char from android app
       }
      }}

      String sendCommand(String command, const int timeout, boolean debug) {
      String response = "";
      esp8266.print(command); // send the read character to the esp8266
      long int time = millis();
      while ((time + timeout) > millis()) {
      while (esp8266.available()) {
      // The esp has data so display its output to the serial window
      char c = esp8266.read(); // read the next character.
      response += c;
      }
      }

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

body:
I don't know where you found (or how you came up with) this bit of code:

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

But it's horrible.

Not only is your time calculation completely wrong and will suffer a nasty death when millis() rollover occurs, but the whole concept of what you are doing there is bad.

The ESP8266 (assuming it's working, which hasn't been confirmed) sends a response that is terminated by a line-feed ("\n") character.  You are ignoring that and just reading for a pre-defined amount of time (badly).

Instead you should be reading up until you get that "\n" character, or breaking if your timeout has been exceeded.

For instance:

    String sendCommand(String command, const int timeout, boolean debug) {
        String response = ""; // ugh... strings... yuck
        esp8266.println(command);
        uint32_t ts = millis();
        while (millis() - ts < timeout) {
            if (esp8266.available()) {
                char c = esp8266.read();
                if (c == '\n') {
                    #ifdef DEBUG
                        Serial.println(response);
                    #endif
                    return response;
                } else {
                    response += c;
                }
            }
        }
        return String("timeout");
    }

Better that that though is to ditch those nasty String objects. Instead pass a char* buffer to collect the response in:

    int sendCommand(const char *command, uint32_t timeout, char *response, uint32_t rlen) {
        esp8266.println(command);
        response[0] = 0;
        uint32_t rpos = 0;
        uint32_t ts = millis();
        while (millis() - ts < timeout) {
            if (esp8266.available()) {
                char c = esp8266.read();
                if (c == '\n') {
                    if (debug) Serial.println(response);
                    return rpos;
                } else {
                    if (rpos < rlen - 2) {
                        response[rpos++] = c;
                        response[rpos] = 0;
                    }
                }
            }
        }
        return -1;
    }

Then you use that like this:

    char response[80];

    if (sendCommand("AT+CIFS+RST", 1000, response, 80) == -1) {
        Serial.println("CIFS Timed out!");
    }
    if (sendCommand("AT+IPR=115200", 1000, response, 80) == -1) {
        Serial.println("IPR Timed out!");
    }

And so on.

By the way - that `AT+IPR=115200` is a bit of a stupid thing to do. You create a software serial port at 9600 baud (fine), then almost immediately instruct the ESP8266 to switch to 115200 baud instead. You don't then start communicating at 115200 baud, but stay at 9600 baud, so communication can never continue from that point on.  Not only that, but SoftwareSerial is highly unstable at 115200 baud and is not recommended. Stick to 9600 baud.


message:
Multiple node network communication over I²C

I am working on a project where I want to send data from and to different Arduinos on a network. At the moment I²C seems the best option for my needs since I can specify where to send the data. But using this method I have a bit of an issue I can't seem to find a solution for :(.

I will try to explain my problem using the following image:

[![Enter image description here][1]][1]

In the backend all the nodes are connected like in the first image (above the example network). But the nodes may be connected in a different sequence by a user. See the example network.

In this example network, the node with ID 1 needs to send data to ID 10 and not to any other node on the network. Node ID 12 also needs to send data to node ID 10, but no other nodes. Etc. Etc. Etc. But the node that needs to send data to the next node doesn't know the id of the node it needs to send to.

So at first the nodes need to find out what nodes they are connected to and where they need to send their data.

I thought of doing this by connecting a wire between each node (blue wire in possible solution) and when a node gets added to the network the nodes send a high signal over the blue wire and sends its ID to all nodes on the network and then all nodes on the network check if they receive a high signal and an ID.

If this is true they will send its id to the node that has been added. This works fine if you add a node one by one to the network. But it fails when you replace a node in the middle of the network or disconnect power from the network.

What would be the best way to do this (I am also open to use different data transfer protocols)?

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

body:
It sounds (after discussion) like what you are after is actually a *mesh* of multiple *peer to peer* devices.  That is, lots of devices, each one has multiple dedicated communication links each directly going to another device.

If you had enough UART ports you could create individual UART links between nodes. The bets Arduinos only have a handful of those, and the UNO only one.  So that's not really practical.

You could possibly do it with SPI if you wanted to put a lot of work in to developing a decent control protocol to go along with it.  Something along the lines of BUSRQ/BUSACK signalling:

    BUSRQ: Signalling line pulled HIGH by resistor. All nodes INPUT.
    BUSACK: Signalling line pulled HIGH by resistor. All nodes OPEN-DRAIN & LOW.
    SS: Direct 1:1 GPIO links between nodes - all pulled HIGH. All nodes INPUT.

    Node 1                   Node 2                  Node X
    RELEASE BUSACK
    DRIVE BUSRQ (OD Low)     Sees BUSRQ fall         Sees BUSRQ fall
                             RELEASE BUSACK          (could be busy...)
                                                     RELEASE BUSACK
    Sees BUSACK rise
    DRIVE BUSACK
    SS Node 2 LOW            Sees SS go LOW
    Send SPI data            Receives SPI data
    SS Node 2 INPUT          Sees SS go HIGH
    RELEASE BUSRQ                                    Sees BUSRQ rise
                             Sees BUSRQ rise         Drive BUSACK
                             Drive BUSACK

Only once all nodes have released BUSACK will the requesting node be able to send any data, and once a node has released BUSACK it knows that it must never send any data.  The requesting node has basically locked the bus from other nodes accessing it.

It's not perfect, and doesn't handle multiple devices requesting the bus at the same moment, but it does prevent one device trying to send while another is actively sending.


message:
Decimal numbers sent over Serial get split and sent over multiple ticks

Here is my Arduino sketch:

    #include <HX711.h>
    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    HX711 hx(9, 10, 128, 0.002229);
    LiquidCrystal_I2C lcd(0x27,16,2);

    void setup() {

      Serial.begin(9600);
      hx.set_offset(-9635);
      lcd.init();                      // initialize the lcd
      lcd.backlight();
      lcd.begin(16,2);

    }
    void loop() {
      if(digitalRead(0) == LOW){
        lcd.clear();
        lcd.setCursor(2,0);
        lcd.print("tare recieved");
        hx.tare();
      }

      double sum = 0;
      for (int i = 0; i < 10; i++) {
        sum += hx.bias_read();
        if(sum < 0) {
          sum = 0.00;
        }

      }
      sum = sum/10;
      lcd.clear();
      lcd.setCursor(4,0);
      lcd.print("Weight");
      lcd.setCursor(5, 1);
      lcd.print(sum);
      lcd.print("g");
      Serial.println(sum);
      delay(10);
     }

Here is an example output as seen on the Arduino Serial Monitor:

    150.34
    150.39
    150.40
    150.37
    150.38

The Problem is when the data reaches node-serialport the value is split up on multiple lines.

     comport.on("data", function (data) {
        console.log(data.toString());
     }

When i log the data... it comes back like this:

    1
    50.4
    5
    150.
    49
    15
    0.47
    150.
    48
    15
    0.45

Is there anyway to have Arduino only send the data if it is the full value and not the split up values?

body:
As explained in Majenko’s comment, the serial link is not packetized: it
transmits individual bytes and nothing else. If you need to convey a
notion of “data packet”, or “full message”, you will have to devise a
way to signal the message boundaries. This is called message “framing”.

Your Arduino is sending ASCII data. In this case, the most common way to
frame messages is linewise: each message is a single line, and each line
is terminated by an “end of line” sequence. The standard end of line
sequences are CR (carriage return, i.e. `0x0d` or `'\r'`), LF (line
feed, i.e. `0x0a` or `'\n'`), and the pair CRLF (CR followed by LF, or
`"\r\n"`).

Actually you are already doing that: you are using `Serial.println()`,
and this method automatically appends CRLF at the end of whatever it
prints. So now you just have to _parse_ that at the other end: you put
all the incoming characters into a buffer until you see that incoming
CRLF. Then you know you have a full line, which you can report as an
entire message.

This procedure is very common and there is a standard Node.js module for
it. It once was part of the serialport module, but it seems to have
split into a separate module. It is called _parser-readline_, and you
would use it like this:

<!-- language: lang-js -->

    const Readline = require("parser-readline"),
          parser = comport.pipe(new Readline({ delimiter: "\r\n" }));

    parser.on("data", data => console.log(data.toString()));

C.f. the [documentation of
ReadLineParser](https://node-serialport.github.io/parsers/ReadLineParser.html).


message:
Combining two sketches that both work on their own, but don't work when combined

I've got a program for a password protected doorlock, which I got working.

I'm trying to add to the code, to add functionality where I can toggle an LED on/off with a button.

Both codes function on their own and serve their desired purpose, but when I try to combine them into the same sketch, the LED button works but the rest of my design stops working. I can no longer input a password to activate the motor.

How can I combine the two codes and have them both work?

Here is the working keypad/lock code

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

    #define Password_Length 5

    int signalPin = 10;
    int greenLedPin = 11;
    int redLedPin = 12;
    char Data[Password_Length] = "4";
    char Master[Password_Length] = "1234";
    byte data_count = 0, master_count = 0;
    bool Pass_is_good;
    char customKey;

    const byte ROWS = 4;
    const byte COLS = 3;
    bool ledState = 0;

    char hexaKeys[ROWS][COLS] = {
      {'1', '2', '3'},
      {'4', '5', '6'},
      {'7', '8', '9'},
      {'*', '0', '#'}
    };

    byte rowPins[ROWS] = {9, 8, 7, 6};
    byte colPins[COLS] = {5, 4, 3};

    Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS,     COLS);

    LiquidCrystal_I2C lcd(0x3f, 16, 2);

    void setup()
    {
      lcd.init();
      lcd.backlight();
      Serial.begin(9600);
      lcd.clear();

      pinMode(redLedPin, OUTPUT);
      pinMode(greenLedPin, OUTPUT);
      digitalWrite(redLedPin, LOW);
      digitalWrite(greenLedPin, LOW);
    }

    void loop()
    {
      lcd.setCursor(0,0);
      lcd.print("Enter Password:");

      customKey = customKeypad.getKey();
      if (customKey){
        Data[data_count] = customKey;
        lcd.setCursor(data_count,1);
        lcd.print(Data[data_count]);
        data_count++;
        }

    if(data_count == Password_Length-1){
        lcd.clear();

        if(!strcmp(Data, Master)){
          lcd.print("Correct");
          pinMode(signalPin, OUTPUT);
          digitalWrite(signalPin, LOW); //turns on motor
          digitalWrite(greenLedPin, HIGH); //turns on led
          delay(2000);
          digitalWrite(signalPin, HIGH); //turns off motor
          digitalWrite(greenLedPin, LOW); //turns off led
          }
        else{
          lcd.print("Incorrect");
          digitalWrite(redLedPin, HIGH); //turns on led
          delay(2000);
          digitalWrite(redLedPin, LOW); //turns off led
          }

        lcd.clear();
        clearData();
      }
    }

    void clearData(){
      while(data_count !=0){
        Data[data_count--] = 0;
      }
      return;
    }

and here is the code I'm using for the LED on/off toggle button

    int button = 2;
    int led = 13;
    int status = false;

    void setup(){
    pinMode(led, OUTPUT);
    pinMode(button, INPUT_PULLUP); // set the internal pull up resistor,
    unpressed button is HIGH
    }

    void loop()
    {
    //a) if the button is not pressed the false status is reversed by !status
    and the LED turns on
    //b) if the button is pressed the true status is reversed by !status and
    the LED turns off

    if (digitalRead(button) == true) {
    status = !status;
    digitalWrite(led, status);
    } while(digitalRead(button) == true);
    delay(50); // keeps a small delay
    }

body:
Let's step back from the Arduino for a minute and ask: assuming you know how to cook some bacon, and also how to boil some eggs, how would you simultaneously cook bacon **and** eggs?

Basically you would have to interleave any process (such as waiting for the water to boil) with some other process (such as waiting for the bacon to cook).

Once you have this concept in your head you can just take the two pieces of code, and wherever you are planning to wait for something to happen, see if the other thing is able to be done.

I have done a post about this: http://www.gammon.com.au/blink

> I just figured out that the original password code will still function, but only if i keep the LED toggle button held down.

Well, you need to remove any *blocking* loops from either part of the code.

Your code here blocks:

    if (digitalRead(button) == true) {
    status = !status;
    digitalWrite(led, status);
    } while(digitalRead(button) == true);

That's like (in my analogy) of thinking "oh the water is boiling, I'll have to stare at the eggs until they are cooked". Instead you could check the bacon, check the eggs, check the bacon again, and so on.

I'm giving you these analogies to help you solve the general problem, not this particular bit of coding.

---

> i understand that the code blocks, but that code also makes the LED toggle on and off like i need, so how do i integrate that in a way that it doesnt block the rest?

Replace the LED code with something like this (not compiled or tested):

    void loop ()
      {
      static int oldReading = LOW;
      int newReading = digitalRead (button);
      if (newReading != oldReading)  // it changed!
        {
        oldReading = newReading;  // remember new reading state
        if (newReading == HIGH)
          {
          status = !status;
          digitalWrite(led, status);
          }  // end of a HIGH reading
        }  // end of changed state

       // password stuff here

       }  // end of loop

Now, whatever you do with the button, the code doesn't stop (block) so the password stuff is still executed.


message:
Problem while connecting two arduino with NRF24L01

I am a beginner in Arduino programming so that program is also little bit lengthy sorry for inconvenience.
I have make a program for wire less controlling of a servo motor and LED(7 Nos.) using ARDUINO UNO, Funduino Joy stick shield V1.A and NRF24L01.First i have prepare the program (using Array) only for controlling the LEDs and its become success as that LEDs working as per program.Than i added Servo motor also in circuit and make some  changes in existing LED program. Unfortunately the result is erratic out put.joy stick input signal interrupting the led signal and some time servo motor respond led input .Transmitting code and Reciever code  given below.

I came to know that this problem will solve using "struct" command in existing program . Please help me to modify the program with "struct".Because i have no thorough knowledge in C,C++

TRANSMITTER

        #include <SPI.h>
        #include <RF24.h>
        #include <nRF24L01.h

    >

    #define xAxis A0
    RF24 radio(9,10);
    const uint64_t pipe = 0xF0F0F0F0D2L;

    int msg[1];
    int buttonPin1 = 2;
    int buttonPin2 = 3;
    int buttonPin3 = 4;
    int buttonPin4 = 5;
    int buttonPin5 = 6;
    int buttonPin6 = 7;
    int buttonPin7 = 8;
    int buttonState1 = 0;
    int buttonState2 = 0;
    int buttonState3 = 0;
    int buttonState4 = 0;
    int buttonState5 = 0;
    int buttonState6 = 0;
    int buttonState7 = 0;

    void setup(void)
    {
      radio.begin();
      radio.openWritingPipe(pipe);
      pinMode(buttonPin1, INPUT_PULLUP);
      pinMode(buttonPin2, INPUT_PULLUP);
      pinMode(buttonPin3, INPUT_PULLUP);
      pinMode(buttonPin4, INPUT_PULLUP);
      pinMode(buttonPin5, INPUT_PULLUP);
      pinMode(buttonPin6, INPUT_PULLUP);
      pinMode(buttonPin7, INPUT_PULLUP);
    }

    void loop(void)
    {
      int potValue = analogRead(A0);                              //  INPUT FOR SERVO MOTOR
      int angleValue = map(potValue, 0, 1023, 0, 180); // INPUT FOR SERVO MOTOR
      radio.write(&angleValue, sizeof(angleValue));         // INPUT FOR SERVO MOTOR

      buttonState1 = digitalRead(buttonPin1);
      buttonState2 = digitalRead(buttonPin2);
      buttonState3 = digitalRead(buttonPin3);
      buttonState4 = digitalRead(buttonPin4);
      buttonState5 = digitalRead(buttonPin5);
      buttonState6 = digitalRead(buttonPin6);
      buttonState7 = digitalRead(buttonPin7);

     if (buttonState1 == LOW){
        msg[0] = 111;
        radio.write(msg, 1);               // INPUT FOR LED1
       }
     if (buttonState2 == LOW){
        msg[0] = 222;
        radio.write(msg, 1);               // INPUT FOR LED2
       }
     if (buttonState3 == LOW){
        msg[0] = 212;
        radio.write(msg, 1);               // INPUT FOR LED3
       }
     if (buttonState4 == LOW){
        msg[0] = 216;
        radio.write(msg, 1);                 // INPUT FOR LED4
       }
     if (buttonState5 == LOW){
        msg[0] = 218;
        radio.write(msg, 1);                // INPUT FOR LED5
       }
     if (buttonState6 == LOW){
        msg[0] = 220;
        radio.write(msg, 1);                 // INPUT FOR LED6
       }
        if (buttonState7 == LOW){
        msg[0] = 224;
        radio.write(msg, 1);
       }                                              // INPUT FOR LED7

      }

RECIEVER

     #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>
    #include <Servo.h>  // SERVO LIBRARY INCLUDED

    Servo myServo;
    RF24 radio(9,10);
    const uint64_t pipe = 0xF0F0F0F0D2L;

    int led1 = 2;
    int led2 = A2;
    int led3 = 4;
    int led4 = 5;
    int led5 = 6;
    int led6 = 7;
    int led7 = 8;
    int msg[1];
    int angleValue ;

    void setup(void)
    {
      Serial.begin(9600);
      radio.begin();
      radio.openReadingPipe(1, pipe);
      radio.startListening();
      myServo.attach(3);                  // SERVO CONNECTED TO PIN 3
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);
      pinMode(led4, OUTPUT);
      pinMode(led5, OUTPUT);
      pinMode(led6, OUTPUT);
      pinMode(led7, OUTPUT);
    }
    void loop(void)
    {
       // Receiving code for LED 1 TO LED 7

      if(radio.available()){
        bool done = false;
        while (!done) {
        done = radio.read(msg, 1);
        Serial.println(msg[0]);

        if (msg[0] == 111) {
          digitalWrite(led1, HIGH);
          digitalWrite(led7, LOW);
          }
        if(msg[0] == 222){
            digitalWrite(led1, LOW);
            digitalWrite(led2, HIGH);
            digitalWrite(led7, LOW);
            }
         else if (msg[0] == 111){
              digitalWrite(led2, LOW);
            }
         else if(msg[0] == 212){

              digitalWrite(led3, HIGH);
            }
        else if(msg[0] == 216){
              digitalWrite(led4, HIGH);
            }
        else if(msg[0] == 218){
              digitalWrite(led5, HIGH);
            }
        else if(msg[0] == 220){
              digitalWrite(led6, HIGH);
            }
        else if(msg[0] == 224){
              digitalWrite(led7, HIGH);
              digitalWrite(led1, LOW);
              digitalWrite(led2, LOW);
            delay(10);
            }
          }
       }

    //Recieving code for servo motor

        if(radio.available()){
          bool done = false;
          while (!done) {
          done = radio.read(&angleValue,sizeof (angleValue) );
          myServo.write(angleValue);}
          delay(10);
         }
                      //Receiving code for LEDs
          else {
          digitalWrite(led3, LOW);
          digitalWrite(led4, LOW);
          digitalWrite(led5, LOW);
          digitalWrite(led6, LOW);

          }
     }

---

  I have tried to make a program using "struct" for 6 button state and one angle input signal  to control using 6 LEDs and one Servo and its working fine(Program mentioned below.)
But problem is that when i add two more input signal that time output become erratic and output is not getting as per program.Please help to modify the program.
transmitter

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <printf.h>
    #include <RF24.h>
    #include <RF24_config.h>
    #define CE_PIN   9
    #define CSN_PIN 10
    const uint64_t pipe = 0xE8E8F0F0E1LL;
    RF24 radio(CE_PIN, CSN_PIN);
    int upbut = 2;
    int rightbut = 3;
    int downbut = 4;
    int leftbut = 5;
    int nuetral = 6;
    int starte = 7;
    int stope = 8;
    struct data {
        uint8_t leds;
        uint8_t angle;
    };
    struct data packet;
    void setup()   /****** SETUP: RUNS ONCE ******/
    {
      Serial.begin(9600);
      radio.begin();
      radio.openWritingPipe(pipe);
      pinMode(upbut,INPUT_PULLUP);
      digitalWrite(upbut,LOW);
      pinMode(rightbut,INPUT_PULLUP);
      digitalWrite(rightbut,LOW);
       pinMode(downbut,INPUT_PULLUP);
      digitalWrite(downbut,LOW);
      pinMode(leftbut,INPUT_PULLUP);
      digitalWrite(leftbut,LOW);
      pinMode(nuetral,INPUT_PULLUP);
      digitalWrite(nuetral,LOW);
      pinMode(starte,INPUT_PULLUP);
      digitalWrite(starte,LOW);
      pinMode(stope,INPUT_PULLUP);
      digitalWrite(stope,LOW);
      //end pinMode and digitalWrite
    }//--(end setup )---
    void loop(){
    int potValue = analogRead(A0);
    packet.angle = map(potValue, 0, 1023, 0, 180);

    packet.leds = 0;
    packet.leds = digitalRead(upbut) ? 0x00 : 0x01;
    packet.leds |= digitalRead(rightbut) ? 0x00 : 0x02;
    packet.leds |= digitalRead(downbut) ? 0x00 : 0x04;
    packet.leds |= digitalRead(leftbut) ? 0x00 : 0x08;
    packet.leds |= digitalRead(nuetral) ? 0x00 : 0x10;
    packet.leds |= digitalRead(starte) ? 0x00 : 0x20;
    /*packet.leds |= digitalRead(starte) ? 0x00 : 0x30;*/

    radio.write((uint8_t *)&packet, sizeof(struct data));
    }
receiver

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <printf.h>
    #include <RF24.h>
    #include <RF24_config.h>

    #include <Servo.h>
    #define CE_PIN 6
    #define CSN_PIN 7
    const uint64_t pipe = 0xE8E8F0F0E1LL;
    RF24 radio(CE_PIN, CSN_PIN);
    const int servo1 = 9;
    int servoVal;
    Servo myservo1;
    struct data {
        uint8_t leds;
        uint8_t angle;
    };
    struct data packet;
    int led1 = 2; // digital out put
    int led2 = 3; // digital out put
    int led3 = 4; // digital out put
    int led4 = 5; // digital out put
    int led5 = 8; // digital out put
    int led6 = A0; // digital out put
    int led7 = A1; // digital out put
    void setup()   /****** SETUP: RUNS ONCE ******/
    {
      Serial.begin(9600);
      myservo1.attach(servo1); // attaches the servo1 /analog output

      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);
      pinMode(led4, OUTPUT);
      pinMode(led5, OUTPUT);
      pinMode(led6, OUTPUT);
      pinMode(led7, OUTPUT);
      Serial.println("Nrf24L01 Receiver Starting");
      radio.begin();
      radio.openReadingPipe(1,pipe);
      radio.startListening();;
    }                             //--(end setup )---

    void loop(){

    if (radio.available()) {
        radio.read((uint8_t *)&packet, sizeof(struct data));
        myservo1.write(packet.angle);
       if (packet.leds ==0x01){
        digitalWrite(led1, packet.leds & 0x01);
        digitalWrite(led2, packet.leds & 0x00);
        digitalWrite(led6, packet.leds & 0x00);
        }
       else if (packet.leds ==0x02){
        digitalWrite(led2, packet.leds & 0x02);
        digitalWrite(led1, packet.leds & 0x00);
        digitalWrite(led6, packet.leds & 0x00);
        }
        else if (packet.leds ==0x20){
        digitalWrite(led6, packet.leds & 0x20);
        digitalWrite(led1, packet.leds & 0x00);
        digitalWrite(led2, packet.leds & 0x00);
        }
        digitalWrite(led3, packet.leds & 0x04);
        digitalWrite(led4, packet.leds & 0x08);
        digitalWrite(led5, packet.leds & 0x10);

       /*digitalWrite(led7, packet.leds & 0x30);*/
    }
    }

body:
Your whole method is completely wrong.

Instead of sending bytes with some unknown meaning at random times you need a far more structured approach to sending your data.

You need to either:

* Send the meaning of the byte(s) along with the byte(s), or
* Send all the information every time at pre-defined periods.

Of the two options I'd favour the latter, using a `struct`:

    struct data {
        uint8_t leds;
        uint8_t angle;
    };

And then:

    struct data packet;

    int potValue = analogRead(A0);
    packet.angle = map(potValue, 0, 1023, 0, 180);

    packet.leds = 0;
    packet.led |= digitalRead(buttonPin1) ? 0x00 : 0x01;
    packet.led |= digitalRead(buttonPin2) ? 0x00 : 0x02;
    packet.led |= digitalRead(buttonPin3) ? 0x00 : 0x04;
    packet.led |= digitalRead(buttonPin4) ? 0x00 : 0x08;
    packet.led |= digitalRead(buttonPin5) ? 0x00 : 0x10;
    packet.led |= digitalRead(buttonPin6) ? 0x00 : 0x20;

    radio.write((uint8_t *)&packet, sizeof(struct data));

Then when reading you do the exact opposite:

    struct data packet;

    if (radio.available()) {
        radio.read((uint8_t *)&packet, sizeof(struct data));
        myServo.write(packet.angle);
        digitalWrite(led1, packet.leds & 0x01);
        digitalWrite(led2, packet.leds & 0x02);
        digitalWrite(led3, packet.leds & 0x04);
        digitalWrite(led4, packet.leds & 0x08);
        digitalWrite(led5, packet.leds & 0x10);
        digitalWrite(led6, packet.leds & 0x20);
    }

The `struct` combines a number of variables together into one single block of data giving you easy access by name to the different portions.  One, the `leds` variable, is then used as a *bitmap* of whether each LED is on (1) or off (0). That way you can send the current state of up to 8 LEDs in just a single byte.  If you want to expand that to send different combinations of LEDs then just change which bits of the byte are set.

If you want to "toggle" the LEDs then it will be necessary to keep a record at the sender of the states and send that instead of the raw button data.


message:
Disable the Amplifier during the flashing ESP8266

I use ESP-12 and [Adafruit Mono Amplifier](https://www.adafruit.com/product/2130) for playing audio. It works but It has one big issue. My circuit uses RxD to transfer audio (A+ connect to RxD), also ESP uses for flashing the chip. This causes horrible noise when it is programming the ESP8266 from the speaker. The good thing about this module is it has SD pin which can be used to turn it off.

Now the question is how I can connect this SD pin to disable the amplifier during the flashing procedure and also keep it off by default in normal mode and use something like digitalWrite() to turn it on manually in my application when it is needed. Thanks

body:
SD is pulled up to VIN by a 10kΩ resistor. You will need to pull it down to ground with something "stronger" that 10kΩ - a 1kΩ resistor would probably do it.

Then you can drive the pin HIGH and override that 1kΩ resistance to enable the module.

You could also modify the module to remove the 10kΩ pull-up resistor (the one right by the VIN label which has 1002 printed on it) and use a weaker pull-down resistor (10kΩ would be good).


message:
Connecting LCD TFT shield to NodeMCU

I have the following screen:

[![LCD][1]][1]

I want to connect it to a NodeMCU device:

[![NodeMCU][2]][2]

I read somewhere that it is not possible. However, I am not interested in the touch ability nor the SD card. I just want to draw something on the screen.

Is it possible to make the connection in somehow?

  [1]: https://i.stack.imgur.com/UMWKw.jpg
  [2]: https://i.stack.imgur.com/yhAL0.jpg

body:
The driver chip was identified by https://www.waveshare.com/wiki/2.8inch_TFT_Touch_Shield and https://www.waveshare.com/w/upload/8/84/2.8inch-TFT-Touch-Shield-UserManual-EN.pdf as being the **HX8347D**.

At https://github.com/jshnaidman/UTFT_ESP8266_HX8347D there seems to be a library, with which you can use the `HX8347D` display type to instantiate a `UTFT` object, with which you can draw. You can build upon this [demo code][1].

The connections for the SPI interface are detailed [here][2]. BL (backlight) pin is detailed [here][3]. The pin number for the D/C pin must be given in the code in the constructor and can be chosen freely.

Other reference code (which you might have to port) are:

* [HX8347D by Majenko][4]
* [Code from Watterott][5]

  [1]: https://github.com/jshnaidman/UTFT_ESP8266_HX8347D/blob/master/examples/ESP8266/UTFT_Demo_320x240_Serial_HW/UTFT_Demo_320x240_Serial_HW.ino
  [2]: https://nodemcu.readthedocs.io/en/master/en/modules/spi/
  [3]: https://github.com/jshnaidman/UTFT_ESP8266_HX8347D/blob/master/src/tft_drivers/hx8347d/initlcd.h
  [4]: https://github.com/DisplayCore/HX8347D
  [5]: https://github.com/watterott/Arduino-Libs/blob/master/MI0283QT2/MI0283QT2.cpp


message:
Is it correct to use a 9V 1A transformer to power my project?

I have a quick question:

I have a small alarm project running on an ArduinoNanoV3 (a chinese clon). Counting *sensors, actuators* and the *arduino itself* the consumed current (theoretically speaking, calculated by the data provided by the datasheets) doesn't approach to a max of 300mA. Now, the way I plan to feed the project is using a 110V (AC) transformer that gives me **9V** output with **1A** maximum output. My fear is the output of this transformer (that says 1A) when in all places recommend not to use sources that give currents greater than **500mA** when you are going to feed it by the pin VIn with **9V**.

My question is: if my project is not going to consume more than 300mA, is there any danger/trouble when connecting the 9V ~ 1A transformer for energize my Arduino based project?

body:
> in all places recommend not to use sources that give currents greater than 500mA when you are going to feed it by the pin VIn with 9V.

Nowhere says that.  They say you should not *draw* more than 500mA when you supply with 9V.

The heat generated by the 5V voltage regulator is proportional to the current multiplied by the voltage.  The more current you draw the hotter the regulator will get. The higher the input voltage, the more voltage it has to drop, and thus the hotter it gets.

So the higher the input voltage the lower the current drawn by your project can be before the regulator gets too hot.

Since you are only around 300mA that's below the recommended maximum for a 9V input.


message:
Rc receiver giving wrong values when controlling servo

So I'm building a helicopter. That why I need a receiver (tgy 9x) to read the values from my controller. Those values get passed to my Arduino due where some calculation happen and then get sent to the servos.

Now the problem is the moment I move my servo all the value I get from my receiver immediately become gibberish.

The values I should get and get when I am not sending anything to my servos. These values are in microseconds.

    Channel1 Channel2 Channel3 Channel4
    1486     1484     1482     1472
    1486     1484     1482     1472
    1486     1484     1482     1472
    1486     1484     1482     1472

What I get after moving the servo. These should be between 1000 and 2000.

    Channel1 Channel2 Channel3 Channel4
    1495     18660    1105     17182
    1495     2337     5667     3070
    8828     7674     8795     6198
    10289    7674     8795     11404

The Arduino gets power from the USB (at the moment) and the servo from the ESC of my motor. All the grounds are connected. There is only one servo hooked up and all wires from the receiver are not anywhere near any power lines or servos.

So the question is why is the receiver giving me gibberish and how do I fix it.

Right now I have commented everything out except this:

**RC_controller.h**

    #ifndef RC_controller
    #define RC_controller

    #include <Arduino.h>
    #include "eeprom.h"

    void RC_init();
    void calc_input0();
    void calc_input1();
    void calc_input2();
    void calc_input3();
    void calc_input4();
    void calc_input5();
    #endif

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

**RC_controller.cpp**

    #define RC_NUM_CHANNELS  8
    uint32_t volatile rc_start[RC_NUM_CHANNELS];
    uint32_t volatile rc_shared[RC_NUM_CHANNELS];
    uint32_t volatile rc_raw[RC_NUM_CHANNELS];

    int rc_channels_pin[8] = {2, 3, 4, 5, 6, 7, 8, 9};

    void calc_input0() {
     int identifyer = 0;
       if (digitalRead(rc_channels_pin[identifyer]) == HIGH) {
         rc_start[identifyer] = micros();
       } else {
         rc_raw[identifyer] = (uint16_t)(micros() - rc_start[identifyer]);
       }
    }

    ...

    void RC_init()
    {

     for (byte i = 0; i > RC_NUM_CHANNELS; i++)
       pinMode(rc_channels_pin, INPUT);

     attachInterrupt(digitalPinToInterrupt(rc_channels_pin[0]), calc_input0, CHANGE);
     attachInterrupt(digitalPinToInterrupt(rc_channels_pin[1]), calc_input1, CHANGE);
     attachInterrupt(digitalPinToInterrupt(rc_channels_pin[2]), calc_input2, CHANGE);
     attachInterrupt(digitalPinToInterrupt(rc_channels_pin[3]), calc_input3, CHANGE);
     attachInterrupt(digitalPinToInterrupt(rc_channels_pin[4]), calc_input4, CHANGE);
     attachInterrupt(digitalPinToInterrupt(rc_channels_pin[5]), calc_input5, CHANGE);
    }

--------------------------------------------------
**main.cpp**

    ...
    void setup()
    {
    Serial.begin(115200);
      Wire.begin();
    #if I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif
    for (int a = 0; a < 3; a++)
      swashplate[a].attach(10+a, 1200, 1800);
    RC_init();
    }

    void loop()
    {
    if (rc_raw[0] < 2000)
      {
        swasplate[0].write(rc_raw[0]);
      }

      Serial.print(rc_raw[0]);
      Serial.print("    ");
      Serial.print(rc_raw[1]);
      Serial.print("    ");
      Serial.print(rc_raw[2]);
      Serial.print("    ");
      Serial.print(rc_raw[3]);
      Serial.print("    ");
      Serial.print(rc_raw[4]);
      Serial.print("    ");
      Serial.print(rc_raw[5]);
      Serial.print("    ");
      Serial.println();
    }

body:
I found the problem. The problem was with the interrupts when the program was running and doing calculations at that moment the Arduino would be interrupted and stop in the middle of it, and change the value it was doing calculations with. This somehow caused the Arduino to sent interference over the signal wires. Reading the signals with a reading guard fixed the problem.

    void read_inputs()
    {
      noInterrupts();

      byte identifyer = 0;
      rc_shared[identifyer] = rc_raw[identifyer];

      ...

      interrupts();
    }


message:
NodeMCU ESP12 Voltage

I'd like to power an NodeMCU off of four 1.5v batteries.  That's 6v.

Depending on the source I've read that 5.1v will fry the board and, just a few clicks later, that the board will take up to a 20v input.

What is the real, practical input voltage range for an NodeMCU?  Even the spec sheets seem to disagree.

body:
I edited your question and changed ESP-12 to NodeMCU, based on the title and tag.

5.1 V will 'fry' a plain ESP12, but the NodeMCU is development board with esp8266 and the board has a power regulator for USB power or Vin pin. The parameters of the regulator depend on the regulator used by the manufacturer of your board.


message:
Motor shield not providing enough current to 2 12V DC fans

I have 2 fans and they require up to 3A current, but my motor shield (Arduino Motor Shield Rev3) on my Arduino MEGA can only provide 2A per channel (4A max).  Is it ok to run the fans at a lower speed or are there other options to run (H-bridge)? Thanks.

Fans:
https://www.amazon.com/HIGHFINE-4000RPM-Cooling-FFC1212DE-Computer/dp/B01LLYQ2VE/ref=sr_1_1?ie=UTF8&qid=1523596613&sr=8-1&keywords=12V+dc+fan+200+cfm

body:
I kinda doubt that that fan will actually draw 3A. You could probably get away with using your shield--just measure the fan current draw by directly connecting it up to a 12V supply and measuring with a multimeter.

If it actually draws 3A, any of these sounds like a decent idea:

https://www.amazon.com/WGCD-Controller-Module-Stepper-Arduino/dp/B06X9D1PR9/ref=sr_1_4?s=electronics&ie=UTF8&qid=1523692716&sr=1-4&keywords=arduino+h+bridge

https://www.amazon.com/Diymall-Module-Stepper-Modules-Arduino/dp/B00NJOTBOK/ref=sr_1_8?s=electronics&ie=UTF8&qid=1523692716&sr=1-8&keywords=arduino+h+bridge

https://www.amazon.com/SainSmart-Stepper-Controller-Mega2560-Duemilanove/dp/B00AJGM37I/ref=sr_1_11?s=electronics&ie=UTF8&qid=1523692716&sr=1-11&keywords=arduino+h+bridge


message:
"Serial does not name a type error"

I m getting serial does not name a type error, expected declaration before '}' token line 69

    const int trigPin = 9;
    const int echoPin = 10;
    const int buzzer = 11;
    const int ledPin = 13;

    // defines variables
    long duration;
    int distance;
    int safetyDistance;

    void setup() {
      pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
      pinMode(echoPin, INPUT); // Sets the echoPin as an Input
      pinMode(buzzer, OUTPUT);
      pinMode(ledPin, OUTPUT);
      Serial.begin(9600); // Starts the serial communication
    }

    void loop() {
    // Clears the trigPin
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);

    // Sets the trigPin on HIGH state for 10 micro seconds
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);

    // Reads the echoPin, returns the sound wave travel time in microseconds
      duration = pulseIn(echoPin, HIGH);

    // Calculating the distance
      distance = duration * 0.034 / 2;

      safetyDistance = distance;
      if (safetyDistance <= 5) {
        digitalWrite(buzzer, HIGH);
        digitalWrite(ledPin, HIGH);

        tone(buzzer, 1000);
        delay(100);
        noTone(buzzer);
        delay(100);
      }

      else {
        digitalWrite(buzzer, LOW);
        digitalWrite(ledPin, LOW);
      }
      if (safetyDistance > 5 && safetyDistance <= 10) {
        digitalWrite(buzzer, HIGH);
        digitalWrite(ledPin, HIGH);

        tone(buzzer, 3000);
        delay(3000);
        noTone(buzzer);
        delay(3000);
      } else {
        digitalWrite(buzzer, LOW);
        digitalWrite(ledPin, LOW);
      }
      }
      Serial.print("Distance: ");
      Serial.println(distance);

    }

body:
      if (safetyDistance > 5 && safetyDistance <= 10) {
        digitalWrite(buzzer, HIGH);
        digitalWrite(ledPin, HIGH);

        tone(buzzer, 3000);
        delay(3000);
        noTone(buzzer);
        delay(3000);
      } else {
        digitalWrite(buzzer, LOW);
        digitalWrite(ledPin, LOW);
      }
      }                           //<--
      Serial.print("Distance: ");
      Serial.println(distance);

    }

There is a duplicate `}` after the `else` clause is closed. Remove it and your code will compile.


message:
USBasp problem: could not upload sketches to Arduino clone with PL2303 USB-to-UART chip

I'm trying to upload sketch to a Gizduino board (these boards have PL2303 chip for USB-to-Serial communication; other than that they are entirely similar with Arduino Uno).

I have installed the driver for it and can verify that the board associates to a COM Port whenever the board is connected to my PC (Win10) via USB. But everytime I try to upload a sketch, IDE (tried with 1.8.2 and 1.6.9) throws the error below, with or without the PL2303 driver installed on my PC.

    avrdude: error: could not find USB device with vid=0x16c0 pid=0x5dc vendor='www.fischl.de' product='USBasp'

I'm certain that I have selected the right board from the Boards List.

So my intuition was that the PL2303 driver is not working the way it should be. I've been trying to get more information about avrdude and USBasp but so far was not able to find anything remotely similar to my case.

**UPDATE:** Realized that all I needed to do is install the driver for USBasp (whihch I'm having trouble doing); this post could be off-topic. But I'm urged to raise another question: Which programmer should I select from the programmer list? Currently its "AVRISP mkII". In fact it doesn't matter which one I use. Same error about USBasp occurs with any of them selected.

body: Do you have a USBasp plugged into the computer? if yes then you need to install USBasp driver else why don't you just use the bootloader option from the arduino IDE.


message:
nodemcu pins + sensors reading values

what are the SDA & SCL pins in NodeMCU? (Pins 20 & 21 in Arduino MEGA2560) I already implemented a simple project to read 2 accelerometers values from Arduino and send them through wifi to firebase database. I used Arduino Mega before for the same project and the sensors gave me readings between approximately -300 to 300. Now when I moved to NodeMCU the sensors became very sensitive and are getting values up to 65500+. And with a very small angle change the axis reading drop down to 20 or less.

I used pins D1 and D2 for SCL and SDA. Are the pins correct? And What about the reading values how to fix that?

body:
The ESP8266 doesn't have a hardware Two Wire Interface. I²C is done in software, so you can use any 2 pins, as long as you specify them in your code using `Wire.begin(SDA, SCL)`.

My guess would be that there's another problem. 65500+ sounds like an integer overflow, for example. (`(uint16_t) -1 == 65535`)


message:
Bluetooth a pushbutton from one arduino to another to turn on a LED

For a major project at school i need to get a bluetooth module to be able to communicate between two  HC-05 modules as a master and slave. They need to be able to press a pushbutton on the slave and it lights up a LED on the master.
I have been able to get the two hc-05's to connect to each other but i cant find a code and wiring that will work for what i need to do.
any help will be appreciated. Thanks[![master code][1]][1]

[![slave code][2]][2]

  [1]: https://i.stack.imgur.com/1cdWJ.png
  [2]: https://i.stack.imgur.com/QHKqo.png

body:
So, you have done the hard part and now need the easy bit :)

Firstly you need a button (failing that touching two wire together will just about do).  There are loads of quick tutorials on the web, here is one https://www.arduino.cc/en/Tutorial/Button.  They will end up with you having a pin that goes high or low when the button is pressed, you can either poll/loop to detect the press or go posh and use interrupts (leave that for later).  When the pin detects the press you need to send some data via your HC05 link to the master, something like 'ON' or 1, who cares so long as the master understands it.  And when it disconnects you need to send a off or 0 message (Remember the number 1 and the character '1' are not the same thing, so make sure you know what you are sending).

When the master receives the command it will execute a bit of code that will send a pin high (lets say pin 7).  Connected to pin 7 will be the +ve side of a LED, the -ve leg of the led will be connected to a resistor of 200-250 ohms and the other end of the resistor will be connected to ground.  Then when pin7 goes high it will light the resistor.

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

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

<!-- End schematic -->

As always you probably will need to break it down to test it, have a little app that toggles pin 7 high for 2 seconds and low for two seconds, etc (just like blink).

There is a phenomenon called 'bouncing' which is where the useless human finger presses a switch and doesn't instantly create a perfect connection and perfect disconnection.  This might make the slave send 101010101010101 when you just expect 1, you can either debounce using software or hardware, but only worry about that if you have a good quality switch :)


message:
transmit a sequence of bit using arduino uno

How do i code to transmit a sequence of bit using arduino uno?My project is about a transmitter and a receiver.Arduino as the transmitter and an application as the receiver.Light sensor will detect the bits sent.How do i send a sequence of bit for example 00101010.What kind of function should i use? i am a beginner for arduino. thank you.

body:
Bit-wise sending of a chunk of data is really just:

* go through each byte of the data
* for each byte (= 8-bits), put each bit on the LED and wait

This also has some substantial drawbacks:

* no error detection or correction. If you get interference on your light sensor / camera due to the environment, you will read wrong data. For this you would need to code the data with some coding scheme or append a checksum
* outputting on the built-in LED on the Arduino Uno / Nano is a bad idea sine it's directly next to the power, RX and TX LED
* outputting in the visible spectrum is asking for interference. That's why we have InfraRed transmissions.
* receiver and transmitter might out of sync; that means that the receiver does not sample the output of the transmitter at the correct time -- you should use a preamble, oversampling and averaging at the receiver to overcome this

That said, you might be better off using other proven methods such as IR, 2.4GHz transceivers, et cetera, from my point of view. Other microcontrollers ([example][1]) have even built-in peripherals to do IR transmission according to some protocol.

On the Arduino Uno/Nano you could also use the [IRemote][2] library to send and receive data using a cheap IR LED and a IR receiver, many of which are included in starter kits (and are also otherwise cheap).

The code below simply takes a stream of bytes and outputs them bit-wise on the LED. Nothing else done. Also, `digitalWrite` is slow and should be replaced by [a faster variant][3].

    #include <Arduino.h>

    /* LED to output from */
    const int LEDTrans = 13;
    /* Length of a symbol */
    const int timeWait = 500;

    const char dataToSend[] = "Hello World";

    /* Transmits data bitwise */
    void transmitData(const char* data, size_t length) {
     //go through each byte of the data
     for(size_t i = 0; i < length; i++) {
      uint8_t currentByte = (uint8_t) data[i];

      //Go through each of the 8 bits in the byte
      //Goes from LSB to MSB (right-to-left)
      for(int j = 0; j < 8; j++) {
       //uses Arduino.h macro "bitRead"
       bool currentBit = bitRead(currentByte, j);

       //Set the LED on/off
       digitalWrite(LEDTrans, currentBit);
       //Wait for the symbol time
       delay(timeWait);
      }
     }
    }

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

    void loop() {
     transmitData(dataToSend, strlen(dataToSend));
     //turn LED OFF again
     digitalWrite(LEDTrans, 0);
     delay(2000);
    }

  [1]: http://www.st.com/resource/en/datasheet/cd00161566.pdf
  [2]: https://github.com/z3t0/Arduino-IRremote
  [3]: https://github.com/NicksonYap/digitalWriteFast


message:
Arduino receive response from SIM800H to AT+CCLK? command

I've been trying to make a program that interacts with SIM800H trough AT commands. It worked with the String class, but it was full of "memory leaks" and after a few hours it just hanged. Then I tried to write it again with char arrays, but for some reason I couldn't get it to work properly.

Can someone suggest me a correction to my program and also a way to get char by char with loop and `Serial.read();`? Serial in this case (Arduino Leonardo) is the USB port and Serial1 is the port to the modem.

Here is my code:

    const long interval = 2000;
    static long currentMillis;

    char wherecclk = 0; //To determine where is the + in +CCLK in the char array

    char serialdata[256] = ""; //Array to store the chars before parsing

    char rtcy1[3]; //Current year  Format: yy\0
    char rtcm1[3]; //Current month  Format: mm\0
    char rtcd1[3]; //Current day  Format: dd\0
    char rtch1[3]; //Current hour  Format: hh\0
    char rtcmm1[3]; //Current minute  Format: mm\0
    char rtcs1[3]; //Current second  Format: ss\0

    int rdpos = 0;

    void setup() {
        Serial.begin(9600); //USB to Computer
        Serial1.begin(9600); //UART to Modem
        Serial1.print("ATE0\r"); //Disable echo
    }

    void loop() {
        wherecclk = 0;
        if (Serial1.available () > 0) { //when something comes on real serial
            strcpy(serialdata, "OK\n\n+CCLK: \"04/01/01,01:35:31+00\"\n\nOK\n"); //This is a real sample of the response coming from the modem emulated
            while (rdpos < 256) //loop timeout: 256 bytes
            {
                if (serialdata[rdpos] == '+') {
                    break; //We have reached the first + char. Stop incrementing it
                }
                rdpos++;
            }
            if (serialdata[rdpos + 1] == 'C' && serialdata[rdpos + 2] == 'C' && serialdata[rdpos + 3] == 'L' && serialdata[rdpos + 4] == 'K') { //If the serial command mathes +CCLK save its position
                wherecclk = rdpos;
            }
            rdpos = 0;

            if (wherecclk != 0) {
                rtcy1[0] = serialdata[wherecclk + 8]; //getting first char with its offset
                rtcy1[1] = serialdata[wherecclk + 9];
                rtcy1[2] = '\0';
                rtcm1[0] = serialdata[wherecclk + 11];
                rtcm1[1] = serialdata[wherecclk + 12];
                rtcm1[2] = '\0';
                rtcd1[0] = serialdata[wherecclk + 14];
                rtcd1[1] = serialdata[wherecclk + 16];
                rtcd1[2] = '\0';
                rtch1[0] = serialdata[wherecclk + 17];
                rtch1[1] = serialdata[wherecclk + 18];
                rtch1[2] = '\0';
                rtcm1[0] = serialdata[wherecclk + 20];
                rtcm1[1] = serialdata[wherecclk + 21];
                rtcm1[2] = '\0';
                rtcs1[0] = serialdata[wherecclk + 23];
                rtcs1[1] = serialdata[wherecclk + 24];
                rtcs1[2] = '\0';
            }

        }

        if (millis() - currentMillis >= interval) //This is done every second
        {
            Serial1.print("AT+CCLK?\r"); //ask for the time
            //delay(50);
            Serial.println("");
            Serial.println("=====");
            Serial.println(millis());

            Serial.println("YEAR: ");
            Serial.print(rtcy1[0]);
            Serial.println(rtcy1[1]);
            Serial.println("MONTH: ");
            Serial.print(rtcm1[0]);
            Serial.println(rtcm1[1]);
            Serial.println("DAY: ");
            Serial.print(rtcd1[0]);
            Serial.println(rtcd1[1]);
            Serial.println("HOUR: ");
            Serial.print(rtch1[0]);
            Serial.println(rtch1[1]);
            Serial.println("MINUTE: ");
            Serial.print(rtcmm1[0]);
            Serial.println(rtcmm1[1]);
            Serial.println("SECOND: ");
            Serial.print(rtcs1[0]);
            Serial.println(rtcs1[1]);

            currentMillis = millis();
        }
    }

Here is the output (a screenshot, because serial monitor doesn't give me full code):

[![serial monitor][1]][1]

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

body: You declare your variables for month and minute differently (`rtcm1[3]` vs `rtcmm1[3]`), but you load `rtcm1` with month, and then a few lines later, with minutes.


body:
Here's the final code in case someone needs it:

 const long interval = 1000;
 static long currentMillis;

 char wherecclk = 0; //To determine where is the + in +CCLK in the char array

 char serialdata[256] = ""; //Array to store the chars before parsing

 char rtcy1[3]; //Current year  Format: yy\0
 char rtcm1[3]; //Current month  Format: mm\0
 char rtcd1[3]; //Current day  Format: dd\0
 char rtch1[3]; //Current hour  Format: hh\0
 char rtcmm1[3]; //Current minute  Format: mm\0
 char rtcs1[3]; //Current second  Format: ss\0

 int rdpos = 0;

 int pointingfinger = 0;

 void setup() {
   Serial.begin(9600); //USB to Computer
   Serial1.begin(9600); //UART to Modem
   Serial1.print("ATE0\r"); //Disable echo
 }

 void loop() {
   if (Serial1.available () > 0) { //when something comes on real serial
  rdpos = 0;
  wherecclk = 0;
  if (pointingfinger == 255) {
    pointingfinger = 0;
  }

  serialdata[pointingfinger] = Serial1.read();

  while (rdpos < 256) //loop timeout: 256 bytes
  {
    if (serialdata[rdpos] == '+') {
   break; //We have reached the first + char. Stop incrementing it
    }
    rdpos++;
  }
  if (serialdata[rdpos + 1] == 'C' && serialdata[rdpos + 2] == 'C' && serialdata[rdpos + 3] == 'L' && serialdata[rdpos + 4] == 'K') { //If the serial command mathes +CCLK save its position
    wherecclk = rdpos;
  }

  pointingfinger++;
   }

   if (millis() - currentMillis >= interval) //This is done every second
   {
  pointingfinger = 0;
  //Serial.println("=========");
  //Serial.println(serialdata);
  //Serial.println("=========");
  if (wherecclk != 0) {
    rtcy1[0] = serialdata[wherecclk + 8]; //getting first char with its offset
    rtcy1[1] = serialdata[wherecclk + 9];
    rtcy1[2] = '\0';
    rtcm1[0] = serialdata[wherecclk + 11];
    rtcm1[1] = serialdata[wherecclk + 12];
    rtcm1[2] = '\0';
    rtcd1[0] = serialdata[wherecclk + 14];
    rtcd1[1] = serialdata[wherecclk + 15];
    rtcd1[2] = '\0';
    rtch1[0] = serialdata[wherecclk + 17];
    rtch1[1] = serialdata[wherecclk + 18];
    rtch1[2] = '\0';
    rtcmm1[0] = serialdata[wherecclk + 20];
    rtcmm1[1] = serialdata[wherecclk + 21];
    rtcmm1[2] = '\0';
    rtcs1[0] = serialdata[wherecclk + 23];
    rtcs1[1] = serialdata[wherecclk + 24];
    rtcs1[2] = '\0';
  }
  Serial1.print("AT+CCLK?\r"); //ask for the time
  //delay(50);
  Serial.println("");
  Serial.println("=====");
  Serial.println(millis());

  Serial.println("YEAR: ");
  Serial.print(rtcy1[0]);
  Serial.println(rtcy1[1]);
  Serial.println("MONTH: ");
  Serial.print(rtcm1[0]);
  Serial.println(rtcm1[1]);
  Serial.println("DAY: ");
  Serial.print(rtcd1[0]);
  Serial.println(rtcd1[1]);
  Serial.println("HOUR: ");
  Serial.print(rtch1[0]);
  Serial.println(rtch1[1]);
  Serial.println("MINUTE: ");
  Serial.print(rtcmm1[0]);
  Serial.println(rtcmm1[1]);
  Serial.println("SECOND: ");
  Serial.print(rtcs1[0]);
  Serial.println(rtcs1[1]);

  currentMillis = millis();
   }
 }


message:
Arduino - use print(.., DEC) to save into variable

I am using:

    Serial.print(rawCodes[i - 1], DEC);

to print into serial monitor, but how can I save `(rawCodes[i - 1], DEC)` to save into variable?

body:
Assuming your code comes from here: https://www.alanzucconi.com/2015/08/19/how-to-hack-any-ir-remote-controller/

Since `rawCodes` is declared as

    unsigned int rawCodes[35];

I.e., it is a 35-element array of `unsigned int` elements, we can access a single `unsigned int` element at some index and save it in a variable like

    unsigned int myVariable = rawCodes[i - 1]; //assuming i is some integer variable
                                               //and exists in this scope

If conversion to a `String` object is needed it can be passed into the constructor of the `String` class as

    String myString = String(myVariable);

That answers your syntactical question on how to save that element into a variable; however, it is unlikely that this is your real underlying problem. We cannot determine that until you tell us what exactly you actually want.

References:

* [Arrays in C tutorial][1]

  [1]: https://www.tutorialspoint.com/cprogramming/c_arrays.htm


message:
Why is this variable giving me always the value of 0?

I am doing a project and here is the code that I am using, but I do not know why the values of duration and sofia is always 0 so the values of distance and monroy are also 0

    const int trigPin = 9;
    const int echoPin = 10;

    const int t = 8;
    const int e = 7;

    long duration, sofia;
    int distance, monroy;
    void setup() {
      pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
      pinMode(echoPin, INPUT); // Sets the echoPin as an Input
      pinMode(t, OUTPUT);
      pinMode (e, INPUT);
      Serial.begin(9600); // Starts the serial communication
    }
    void loop() {
      // Clears the trigPin
      digitalWrite(trigPin, LOW);
      digitalWrite (t, LOW);
      delayMicroseconds(2);
      // Sets the trigPin on HIGH state for 10 micro seconds
      digitalWrite(trigPin, HIGH);
      digitalWrite (t, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      digitalWrite (t, LOW);
      // Reads the echoPin, returns the sound wave travel time in microseconds
      duration = pulseIn(echoPin, HIGH);
      sofia = pulseIn(e, HIGH);
      // Calculating the distance
      distance = duration * 0.034 / 2;
      monroy = sofia * 0.034 / 2;
      Serial.print(duration);
      if (distance = 15);
      {
        digitalWrite (3, HIGH);
        delay (5000);
        digitalWrite (3, LOW);
      }

      if ((monroy >= 0) && (monroy <= 5));
      {
        digitalWrite (4, HIGH);
        digitalWrite (5, LOW);
        digitalWrite (6, LOW);
      }
      if ((monroy >= 5.1) && (monroy <= 9));
      {

        digitalWrite (5, HIGH);
        digitalWrite (6, LOW);
      }
      if (monroy >= 9.1);
      {

        digitalWrite (5, LOW);
        digitalWrite (6, HIGH);
      }
    }

body:
When I formatted your code for readability and then compiled it I got these warnings:

    /tmp/arduino_modified_sketch_71221/sketch_may02a.ino: In function 'void loop()':
    /tmp/arduino_modified_sketch_71221/sketch_may02a.ino:34:20: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
       if (distance = 15);
                        ^
    /tmp/arduino_modified_sketch_71221/sketch_may02a.ino:34:21: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]
       if (distance = 15);
                         ^
    /tmp/arduino_modified_sketch_71221/sketch_may02a.ino:41:38: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]
       if ((monroy >= 0) && (monroy <= 5));
                                          ^
    /tmp/arduino_modified_sketch_71221/sketch_may02a.ino:47:40: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]
       if ((monroy >= 5.1) && (monroy <= 9));
                                            ^
    /tmp/arduino_modified_sketch_71221/sketch_may02a.ino:53:21: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]
       if (monroy >= 9.1);

These are **important** - you should pay attention to them. For example, here:

      if (distance = 15);  // <-- NO SEMICOLON NEEDED HERE!
      {
        digitalWrite (3, HIGH);
        delay (5000);
        digitalWrite (3, LOW);
      }

Putting a semicolon there means that stuff under the `if` is **always executed** - the semicolon terminates the scope of the `if`.

---

To see the warnings open the Preferences dialog in the IDE GUI and change "Compiler warnings" to "All".

---

Also:

      if (distance = 15);

This **assigns** 15 to distance, so distance will always be 15. You mean:

      if (distance == 15)


message:
add ID number to the feather m0 bootloader (flash)

I'm trying to add a serial number to the bootloader's flash area of Adafruit Feather m0 board. Seems like feather m0 0-0x2000 area on the flash is non writable by the arduino sketch. i wanted to add a serial number to address 0x2000 - 8 on the flash.
The idea is for the data to be included in the bootloader elf\bin so i can easily flash it on devices and later on access it using flash address  (0x2000 - 8) with NVMCTRL.

I've started out with this solution:

downloaded the code from [samd21 arduino bootloader github directory][1] and in ./bootloaders/zero edited the boololoader ld script, first the "Memory" section

    FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 0x2000 /* First 8KB used by bootloader */
    FLASHID (rx) : ORIGIN = 0x00002000 - 0x0008, LENGTH = 8

Then the 'sections' section:

    .id_sec :
      {
        KEEP(*(.myid))
      } > FLASHID

This should have saved some room in the end of the flash for the id. now in the main.c file:

    __attribute__ ((section(".myid"))) const unsigned long ID = 0xdead1234;

Which should have saved the 0xdead1234 hex value in the (0x2000-8) address.

The issue is this:
I compiled this code and linked it just fine, got .hex,.bin,.elf files.
If i'm correct (unless they are somehow compressed) i should be able to see the code 0xdead in the binary.
**BUT** i don't.
After objdump on the binary(any of them) i can't find the 0xde 0xad in any order anywhere.
The `arm-none-eabi-size" --format=sysv -t -x build/.elf` does not show the new section i added no where.
Also i do wonder, as i said the 0x2000 address on the flash is non writable once i flashed with atmel-ice \j-link even the bootloader code cannot write to it, i did define in the ld script that i want that memory region part of the flash so i do expect that the compiler + linker + jlink flasher will know to write that data to the right place but not sure.

Anyone got some experience with it ? did it before ?

  [1]: https://github.com/arduino/ArduinoCore-samd

body:
This is quite an easy fix, actually.

The problem here is the compiler doesn't think the const is used for anything - so it (quite rightly) throws it away.

All you need to do is tell the compiler that it's `used` and all should be good:

    __attribute__((section(".myid"),used)) const unsigned long ID = 0xdead1234;

And when you compile:

    build/.elf  :
    section             size         addr
    .vectors            0x40          0x0
    .text             0x18d4         0x40
    .data               0x5c   0x20000000
    .bss               0x34c   0x2000005c
    .id_sec              0x4       0x1ff8
    .ARM.attributes     0x28          0x0
    .comment            0x80          0x0
    .debug_frame        0x68          0x0
    Total             0x1dd0

Properly, though, you should make some more changes to the linker script to properly isolate those 8 bytes of flash (though you don't *have* to).

1. You should reduce `FLASH` by 8 bytes.
2. You should include the FLASHID length in the `__sketch_vectors_ptr` calculation.

That's:

    MEMORY
    {
      FLASH   (rx) : ORIGIN = 0x00000000, LENGTH = 0x1FF8 /* First 8KB used by bootloader */
      FLASHID (rx) : ORIGIN = 0x00001FF8, LENGTH = 8
      RAM    (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00008000-0x0004 /* 4 bytes used by bootloader to keep data between resets */
    }

And:

    PROVIDE(__sketch_vectors_ptr = ORIGIN(FLASH) + LENGTH(FLASH) + LENGTH(FLASHID));

That way the compiled bootloader code can never be placed in the FLASHID area (not that it would at the moment, but if a new version of the bootloader were released that used 100% of the lower block of flash it would conflict).

Of course, if all you need is something unique to identify the board with, all AVR and SAMD devices that have built-in USB support have a unique ID number. This is intended to be used as the Serial Number for the USB, but could also be used for a MAC address for Ethernet (or for portions of it anyway) or other unique "node" addresses.


message:
Arduino 4wd rover

Guys i have made an arduino 4wd rover using L298N BRIDGE MODULE, HC-05 and Arduino uno but the power supply output of L298N was very low that even 1 motor is working too slow so please help me with power out put please...
Here is the code...

    #define enA 9
    #define in1 4
    #define in2 5
    #define enB 10
    #define in3 6
    #define in4 7

    int xAxis, yAxis;
    int  x = 0;
    int  y = 0;

    int motorSpeedA = 0;
    int motorSpeedB = 0;

    void setup() {
      pinMode(enA, OUTPUT);
      pinMode(enB, OUTPUT);
      pinMode(in1, OUTPUT);
      pinMode(in2, OUTPUT);
      pinMode(in3, OUTPUT);
      pinMode(in4, OUTPUT);

      Serial.begin(38400); // Default communication rate of the Bluetooth module
    }

    void loop() {
      // Default value - no movement when the Joystick stays in the center
      xAxis = 510;
      yAxis = 510;

      // Read the incoming data from the Smartphone Android App
      while (Serial.available() >= 2) {
        x = Serial.read();
        delay(10);
        y = Serial.read();
      }
      delay(10);

      // Makes sure we receive corrent values
      if (x > 60 & x < 220) {
        xAxis = map(x, 220, 60, 1023, 0); // Convert the smartphone X and Y values to 0 - 1023 range, suitable motor for the motor control code below
      }
      if (y > 60 & y < 220) {
        yAxis = map(y, 220, 60, 0, 1023);
      }

      // Y-axis used for forward and backward control
      if (yAxis < 470) {
        // Set Motor A backward
        digitalWrite(in1, HIGH);
        digitalWrite(in2, LOW);
        // Set Motor B backward
        digitalWrite(in3, HIGH);
        digitalWrite(in4, LOW);
        // Convert the declining Y-axis readings for going backward from 470 to 0 into 0 to 255 value for the PWM signal for increasing the motor speed
        motorSpeedA = map(yAxis, 470, 0, 0, 255);
        motorSpeedB = map(yAxis, 470, 0, 0, 255);
      }
      else if (yAxis > 550) {
        // Set Motor A forward
        digitalWrite(in1, LOW);
        digitalWrite(in2, HIGH);
        // Set Motor B forward
        digitalWrite(in3, LOW);
        digitalWrite(in4, HIGH);
        // Convert the increasing Y-axis readings for going forward from 550 to 1023 into 0 to 255 value for the PWM signal for increasing the motor speed
        motorSpeedA = map(yAxis, 550, 1023, 0, 255);
        motorSpeedB = map(yAxis, 550, 1023, 0, 255);
      }
      // If joystick stays in middle the motors are not moving
      else {
        motorSpeedA = 0;
        motorSpeedB = 0;
      }

      // X-axis used for left and right control
      if (xAxis < 470) {
        // Convert the declining X-axis readings from 470 to 0 into increasing 0 to 255 value
        int xMapped = map(xAxis, 470, 0, 0, 255);
        // Move to left - decrease left motor speed, increase right motor speed
        motorSpeedA = motorSpeedA - xMapped;
        motorSpeedB = motorSpeedB + xMapped;
        // Confine the range from 0 to 255
        if (motorSpeedA < 0) {
          motorSpeedA = 0;
        }
        if (motorSpeedB > 255) {
          motorSpeedB = 255;
        }
      }
      if (xAxis > 550) {
        // Convert the increasing X-axis readings from 550 to 1023 into 0 to 255 value
        int xMapped = map(xAxis, 550, 1023, 0, 255);
        // Move right - decrease right motor speed, increase left motor speed
        motorSpeedA = motorSpeedA + xMapped;
        motorSpeedB = motorSpeedB - xMapped;
        // Confine the range from 0 to 255
        if (motorSpeedA > 255) {
          motorSpeedA = 255;
        }
        if (motorSpeedB < 0) {
          motorSpeedB = 0;
        }
      }
      // Prevent buzzing at low speeds (Adjust according to your motors. My motors couldn't start moving if PWM value was below value of 70)
      if (motorSpeedA < 70) {
        motorSpeedA = 0;
      }
      if (motorSpeedB < 70) {
        motorSpeedB = 0;
      }
      analogWrite(enA, motorSpeedA); // Send PWM signal to motor A
      analogWrite(enB, motorSpeedB); // Send PWM signal to motor B
    }

![enter image description here](https://i.stack.imgur.com/jjJP3.png)

body:
You need more power!

The formula for power is Volts * Amps. A PP3 has about 500mAh, which means its can (in theory) output 9V at 500mA for an hour, which means you have about 4.5 watts.

So what power do your motors need? I'll assume they are about 1.5W motors, which means you need 6W to drive all the motors.

Your PP3 can output 6W, but it won't last long if it does and it will get hot.  Also, if you have 12V motors and are only giving the 9V then they are going to be asking for 1/3 more amps to balance the equation and get their power.  You are probably asking the PP3 to supply 1A which means it will last less than 30 minutes if it is brand new and good quality.

A "simple" solution would be to use two (or more) batteries in parallel.  Parallel gives you more power without changing the voltage.  A better solution would be to look at alternative battery packs, a couple or LiPo 3.7V 1100mAh battery packs, a sealed lead acid gel (heavy).  An even better solution would be to see if you can get lower power motors that can supply the same torque.

Failing that, get a meaty desktop power supply and a long cable :)