body:
I have a question about the reliability of Serial communication, i.e. in particular if I need to implement CRC/checksum/ECC because of bit transmission errors?
I

I however think there is no general answer as there are different ways in which serial communication with the Arduino Uno's Atmega328P chip might work.

 - (a) The serial communication is between two Atmega328P Chips, and using rather long wires
 - (b) The serial communication is between two Atmega328P Chips, and using rather short wires
 - (c) The serial communication is between one Atmega328P and the ATmega16U2, who picks up and forwards the signals via USB protocol (e.g. to a PC)

My question is with regard to the ATmega16U2. The distance (wire/line length) on the Arduino R3 board is about 2cm/1" tops, which I expect to reduce the likeliness that a signal will become corrupted.
Assuming that the USB protocol which is further employed to transport the signal by itself provides by itself an ECC/CRC/checksums, I wonder if it is not rather superflous to implement a CRC when receving and sending messages via the serial communication in the case (c), while I however expect it to be *more* necessary for (b) and almost certainly necessary for (c).

Also, if this matters to respond to the question, I was wondering if the power supply (i.e. if Arduino Uno is powered by the USB provided voltage of ~4.5V or rather via an external 12V power adapter) would have an impact on the "corruptability" of the signals on the TX/RX serial lines?

title: How reliable is Arduino Uno Serial, via USB (ATmega16U2), CRC needed?

Answers: 1

body:
If you use the appropriate buffering of the 0/5V signal over the long wires, case A, no error detection and correction is needed. RS232, RS485, your data will be just fine (can be up to thousands of feet).

Shorter wires, from Atmega device to Atmega device, I've neved had to use anything, even at 115200 speeds, case B, case C.

16U2 to PC, that will depend on the quality of the USB cable. The +/-3V differential signal (similar to RS485 levels) is quite high speed, like 4 Mbits/second, so you want a good cable with good shielding.


body: i have two arduino mega and they send data to each other by an I2C connection. But one of those arduinos is connected to an ethernet shield which allows it to send data to a web server. Being both connected does that mean that they both can send or access the web server. Sorry if any ambiguity was found but I didnt find a better way to ask this question.

title: if two arduinos are connected by I2C and one of them is using an ethernet shield, does that grant both of them access to the internet?

Answers: 2

body:
It can but only if the one with the shield allows it (it acts like a router).

The only way for the arduino without the shield can communicate with the internet if it can send a message to the one with the shield and it will forward that message and return the replies back.

body:
I2C does not automatically share resources between two connected devices. You would not be able to share an Internet connection from a Mega connected via I2C to another Mega which has an Ethernet shield.

However, you **could** write code for both Megas that implements a two-way communication in which the non-shield Mega sends requests or commands to the one with the Shield, and then passes that data back to the non-shield Mega.

However, you, as the coder, would be responsible for designing such a protocol and implementing it. It would be quite a task probably.


body:
I want to establish a connection between my arduino mega ( which is connected to an ethernet shield so internet access is available) to a web server. Any idea how the code should be?
I searched for it but all I found was a local host connection establishment.
Thanks in advance.

title: how to establish a connection between an arduino and a web server?

Answers: 1

body: The answer of this was already existing in the arduino examples which I forgot to check at first. Thanks Majenko for making me notice.


body:
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

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

Answers: 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);
        }
    }


body:
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

title: 3 digit 7 segment display

Answers: 1

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.


body:
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

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

Answers: 5

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:
You can use any pin of the esp-01
You may want to tell the TX and Rx pins though to behave like regular I/O with the pinMode/Function_3 command as described here:

https://arduinodiy.wordpress.com/2018/06/14/simple-wifi-relay-board-or-diy-sonoff-sv-sonoff-4-channel-2/

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.


body:
So,
I have the newest Arduino IDE (1.8.5) installed and the newest release of Arduino AVR Boards 1.6.21.

My OS: macOS 10.11.6.
Usually I only use Nano's china clones with an CH340 USB-Serial chip, I have installed the wch driver and it worked fine !
My Nano's have the newest bootloader (Arduino AVR Boards 1.6.21).

And now the really annoying problem:
I recently ordered Elegoo Uno R3 boards, they have the original 16U2 chip for USB-Serial, no FTDI and no CH340 it's a Atmega 16U2.
And of course nothing works..
When I connect the Elegoo Uno to the mac (over the USB cable), it will show up in the system report - > USB as Arduino, but the IDE won't found it.
Sometimes it will be found by the IDE, but when I click upload (the Blink sketch) it print following:

        avrdude: Version 6.3, compiled on Jan 17 2017 at 12:01:35
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "/Users/USERNAME/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino9/etc/avrdude.conf"
             User configuration file is "/Users/USERNAME/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : /dev/cu.usbmodem5D21
             Using Programmer              : arduino
             Overriding Baud Rate          : 115200
             AVR Part                      : ATmega328P
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PC2
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
               lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : Arduino
             Description     : Arduino
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_recv(): programmer is not responding
             Hardware Version: 3
             Firmware Version: 4.444305
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_recv(): programmer is not responding
             Vtarget         : 322122183.2 V
             Varef           : 49804.8 V
             Oscillator      : 548.816 Hz
             SCK period      : 3495249366.4 us

    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_recv(): programmer is not responding
    avrdude: initialization failed, rc=-1
             Double check connections and try again, or use -F to override
             this check.

    avrdude: stk500_recv(): programmer is not responding

    avrdude done.  Thank you.

So it receives the board information, but then the programmer does not respond, then he responds again and then not, a back and forth.
I have already made it by repeatedly clicking that the program has been uploaded.

Now the possible sources of error:

 1. USB cable

 2. Atmega328

 3. Atmega16U2

 4. My thought: something with the auto reset

Sidenote: I also update the 328 and 16U2(over DFU and USBasp) bootloader with an USBasp, no success (the bootloaders have been uploaded successfully, but I still can't upload a sketch)

Now the things I tried:

 1. Other USB cable -> no success

 2. Upload bootloader to the 328 -> success, program it via an TTL adapter over RX TX -> success, the led start blinking.

 3. Upload bootloader to the 16U2 -> success, but simultaneously not an success, because the bootloader was uploaded successfully, but I still can't upload a sketch.

 4. I read read read over 5 hours now, and the only helpful articles were:

[Same problem as me, he has/had an mac with 10.11.06][1]

He did it with an update of the USB drivers via MultiBeast (hackintosh driver installer) I also try it with no success (I also know that their is now driver for the 16U2, because normally there are built in CDC/ACM drivers, exception windows.)

..................

[Arduino IDE serial ports not working on EL Capitan OSX][2]

A big Github thread, with no real solution.

..................

[The 80% solution][3]

That gave me the idea to test it in a virtual windows machine and surprise surprise it worked, it uploaded without any errors (that I did not figure it out sooner, my fault).

So now I know that the usb cable, the 328, the 16U2 are fully working and nothing is damaged, the only thing that is not working is my mac.
Sometimes the UNO's are not recognized.
Sometimes the sketch is only uploaded to 90 percent, then the board doesn't respond.
The Nano's are fully woking, I thought maybe the CH340 driver for the NANO's make problems ?

So because of that my mac have problems with the UNO boards.

Honestly after that, I have no idea, I just want it to work.

  [1]: https://arduino.stackexchange.com/questions/19180/
  [2]: https://github.com/arduino/Arduino/issues/3928
  [3]: https://forum.arduino.cc/index.php?topic=221900.15

title: Arduino Uno R3 (with Atmega 16U2) and macOS 10.11 not working

Answers: 0


body:
The problem is that sometime I don't even need to press the button and it sent message and keep on sending continuously.

What I want to do is that once the button is pressed, sent 1 message.

I cannot figure out why it is happening. Please help me to figure out.

     #define CUSTOM_SETTINGS
        #define INCLUDE_GPS_SHIELD
        #define INCLUDE_SMS_SHIELD
        #define INCLUDE_VIBRATION_SHIELD

    /* Include 1Sheeld library.*/
    #include <OneSheeld.h>
    #include <string.h>
    #define SW 8

    /* Define a boolean flag. */

    float lat;
    float lon;
    String Message;
    String Message1;
    String Message2;
    char latitude[10];
    char longitude[10];

    void setup()
    {
      pinMode(SW, INPUT);
      /* Start communication.*/
      Serial.begin(9600);
      OneSheeld.begin();

    }

    void Emergency() {

          /* Send SMS. */
          if(digitalRead(SW) == 1)
          {
            lat = GPS.getLatitude();
            lon = GPS.getLongitude();
            Message1 = String(lat,8);
            Message2 = String(lon,8);

            Message = "I need Help! Google Maps - https://www.google.co.in/maps/place/" + Message1 + "," + Message2;
            Serial.println(Message);

            SMS.send("0637200721",Message);
            //Vibration.start(1000,2000);

            delay(3000);
          }
    }

    void loop()
    {
      Emergency();

      delay(1000);
    }

 This is how I connect the button. The Grey cable is for Ground, The red is for 5V and the orange is to pin8. Between Red and Grey there is resistor.

[![][1]][1]

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

title: Press button and Send Message Error

Answers: 1

body:
The problem is because I didn't put the following lines and I changed to use physical push button to 1Sheeld provided button from mobile. The follwing is the working code.

    #define CUSTOM_SETTINGS
    #define INCLUDE_GPS_SHIELD
    #define INCLUDE_SMS_SHIELD
    #define INCLUDE_VIBRATION_SHIELD
    #define INCLUDE_PUSH_BUTTON_SHIELD

    /* Include 1Sheeld library.*/
    #include <OneSheeld.h>
    #include <string.h>

    /* Define a boolean flag. */
    boolean isMessageSent = false;
    float lat;
    float lon;
    String Message;
    String Message1;
    String Message2;
    char latitude[10];
    char longitude[10];

    void setup()
    {
      /* Start communication.*/
      Serial.begin(9600);
      OneSheeld.begin();
      PushButton.setOnButtonStatusChange(&Emergency);
    }

    void loop()
    {

    }

    void Emergency(byte isButtonPressed) {
     if(isButtonPressed)
          {
            if(!isMessageSent)
            lat = GPS.getLatitude();
            lon = GPS.getLongitude();
            Message1 = String(lat,8);
            Message2 = String(lon,8);

            Message = "I need Help! Google Maps - https://www.google.co.in/maps/place/" + Message1 + "," + Message2;
            Serial.println(Message);

            SMS.send("0637200721",Message);
            isMessageSent = true; // This line
          }
          else{
            isMessageSent = false; // This line
          }


body:
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?

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

Answers: 1

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.


body:
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,...

title: comparison in a time sequence

Answers: 1

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


body:
im experiencing troubles with combining a arduino sketch with BMP280 and BM1750. At this moment i have 2 sketches which need to be combined.

#include Wire.h>
#include BH1750.h>

// ADDR line LOW/open:  I2C address 0x23 (0x46 including R/W bit) [default]
// ADDR line HIGH:      I2C address 0x5C (0xB8 including R/W bit)
BH1750 sensor(LOW);

void setup()
{
  Serial.begin(115200);
  Serial.println(F("BH1750 continues measurement basic example"));

  // Initialize I2C bus
  Wire.begin();

  // Initialize sensor in continues mode, medium 1 lx resolution
  sensor.begin(ModeContinuous, ResolutionMid);

  // Start conversion
  sensor.startConversion();
}

void loop()
{
  uint16_t lux;

  // Wait for completion (blocking busy-wait delay)
  if (sensor.isConversionCompleted()) {
    // Read light
    lux = sensor.read();

    // Print light
    Serial.print(F("Light: "));
    Serial.print(lux);
    Serial.println(F(" LUX"));
  }
}

and the BMP280

#include  Wire.h>
#include SPI.h>
#include Adafruit_Sensor.h>
#include Adafruit_BMP280.h>
#include ESP8266WiFi.h>
#include BH1750.h>

#define BMP_SCK 13
#define BMP_MISO 12
#define BMP_MOSI 11
#define BMP_CS 10

Adafruit_BMP280 bme; // I2C
BH1750 lightMeter;

/**************************
 *   S E T U P
 **************************/
void setup() {
  Serial.begin(9600);
  // Initialize the I2C bus (BH1750 library doesn't do this automatically)
  Wire.begin(D2,D1);
  // On esp8266 you can select SCL and SDA pins using Wire.begin(D4, D3);

  lightMeter.begin();
  Serial.println(F("BMP280 test"));
  if (!bme.begin()) {
    Serial.println("Could not find a valid BMP280 sensor, check wiring!");
  }

}

  /**************************
 *  L O O P
 **************************/
void loop() {

  uint16_t lux;

  // Wait for completion (blocking busy-wait delay)
  if (sensor.isConversionCompleted()) {
    // Read light
    lux = sensor.read();

    // Print light
    Serial.print(F("Light: "));
    Serial.print(lux);
    Serial.println(F(" LUX"));
  }
    Serial.print("T=");
    Serial.print(bme.readTemperature());
    Serial.print(" *C");

    Serial.print(" P=");
    Serial.print(bme.readPressure()/100);
    Serial.print(" hPa");

    Serial.print(" A= ");
    Serial.print(bme.readAltitude(1013.25)); // this should be adjusted to your local forcase
    Serial.println(" m");
    //every 20 sec
    delay(2000);
}

The BMP part is working fine.

title: Arduino weather station BMP280 and BM1750

Answers: 0


body:
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

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

Answers: 1

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.


body:
I played with one of those Adafruit FX sound boards in a project a while ago, and see a lot of potential uses for it.
I would like to create “something” for my daughter, when she turns the lights on, (110v bedroom lights) a voice may say “good evening Kyndra” and when she turns the lights off the voice may say “have a good day...”.
The power “on” is not a big problem, the power off is my issue.... I could run a separate circuit and use a solid state off delay that when it sees first circuit go down it triggers a line of code.
With all the new stuff coming out all the time, just wondering if anyone else has a better idea to build a poor mans version “Jarvis 1.0”.  Perhaps using an Arduino may not even be the route I want.

This is just a thought... I’ve been tossing over for a while now.  It’s not imperative it ever gets built. Just thought it would be cool for her.

title: Power on, power off voice using fx board

Answers: 0


body:
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

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

Answers: 1

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.


body:
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

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

Answers: 1

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;
      }

    }


body:
    #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;
    }

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

Answers: 1

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.


body:
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;
        }
    }

title: making a LCD dice for catan

Answers: 1

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.


body:
    #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;
      }

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

Answers: 1

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.


body:
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

title: Multiple node network communication over I²C

Answers: 1

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.


body:
I have recently made a shield for an arduino mega2560 with among others sensors, a CAN interface (MCP2515 and ISO1050).

The purpose is to create a CAN network with several arduino uno and one Mega.
Until now, the network is working well on all the Uno but unfortunately not on the Mega. As I have others sensors on the SPI bus, I've kept the MOSI, MISO and SCK pins unchanged (51,50,52) and I put the SS on the Analog pin A13 (number 67 for digital), which was the nearest unused pin I had during the routing process. Before making the shield I was careful and I've check if I could use it as a SS for my purpose.

Despite my caution, it appears that I'm not able to communicate within the CAN bus.

Before going futher, I'm using the SeeedStudio library made for their shield to test the connection.
I've tried to use A13 (using an #define)and 67 for the

    SPI_CS_PIN = 67;
without any success.

I've also tried to force the bus to be active with a digitalWrite at the beginning of the setup().

    // demo: CAN-BUS Shield, send data
    // loovee@seeed.cc

    #include <mcp_can.h>
    #include <SPI.h>

    // the cs pin of the version after v1.1 is default to D9
    // v0.9b and v1.0 is default D10
    const int SPI_CS_PIN = 67;

    MCP_CAN CAN(SPI_CS_PIN);                                    // Set CS pin

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

    while (CAN_OK != CAN.begin(CAN_500KBPS))              // init can bus : baudrate = 500k
    {
        Serial.println("CAN BUS Shield init fail");
        Serial.println(" Init CAN BUS Shield again");
        delay(100);
    }
    Serial.println("CAN BUS Shield init ok!");
    }

    unsigned char stmp[8] = {0, 0, 0, 0, 0, 0, 0, 0};

    void loop()
    {
    // send data:  id = 0x00, standrad frame, data len = 8, stmp: data buf
    stmp[7] = stmp[7]+1;
    if(stmp[7] == 100)
    {
        stmp[7] = 0;
        stmp[6] = stmp[6] + 1;

        if(stmp[6] == 100)
        {
            stmp[6] = 0;
            stmp[5] = stmp[6] + 1;
        }
    }

    CAN.sendMsgBuf(0x00, 0, 8, stmp);
    delay(100);                       // send data per 100ms
    }

If you have any idea on why it's not working and a way to solve this problem, please let me know :)

Undeadguy.

title: Slave Select on Analog pin for Can Bus

Answers: 0


body:
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?

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

Answers: 1

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).


body:
I've hit a wall with my code and keep getting a Panic error like this:

> Panic /Users/lewisaburrow/Library/Arduino15/packages/esp8266/hardware/esp8266/2.3.0/cores/esp8266/core_esp8266_main.cpp:98 __yield
>
> ctx: sys
> sp: 3ffff9d0 end: 3fffffb0 offset: 01b0

Please can you help shed some light on the error?

It's used to open and close curtains using Alexa by tricking it into thinking it is a Belkin WeMo device. It runs on an Adafruit Feather HUZZAH with ESP8266.

When I test the Alexa connection code it works fine. It's based on Fauxmo https://bitbucket.org/xoseperez/fauxmoesp
    And when I try the code in isolation that moves the stepper motor it works just fine.(This is with an Adafruit Featherwing Motor Controller: https://www.adafruit.com/product/2927 ). It's after the two are 'blended' together that I experience this issue...

The entire code looks like this:

    #include <Arduino.h>
    #ifdef ESP32
    #include <WiFi.h>
    #else
    #include <ESP8266WiFi.h>
    #endif
    #include "fauxmoESP.h"
    #include "credentials.sample.h"

    #define SERIAL_BAUDRATE                 115200
    #define LED                             2

    fauxmoESP fauxmo;

    //--------------------------------------------------
    // Motor

    #include <Wire.h>
    #include <Adafruit_MotorShield.h>
    #include "utility/Adafruit_MS_PWMServoDriver.h"

    // Create the motor shield object with the default I2C address
    Adafruit_MotorShield AFMS = Adafruit_MotorShield();
    // Or, create it with a different I2C address (say for stacking)
    // Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);

    // Connect a stepper motor with 200 steps per revolution (1.8 degree)
    // to motor port #2 (M3 and M4)
    Adafruit_StepperMotor *myMotor = AFMS.getStepper(200, 2);

    //-------------------------------------------------------
    //--------------------------

    // -----------------------------------------------------------------------------
    // Wifi
    // -----------------------------------------------------------------------------

    void wifiSetup() {

    // Set WIFI module to STA mode
    WiFi.mode(WIFI_STA);

    // Connect
    Serial.printf("[WIFI] Connecting to %s ", WIFI_SSID);
    WiFi.begin(WIFI_SSID, WIFI_PASS);

    // Wait
    while (WiFi.status() != WL_CONNECTED) {
        Serial.print(".");
        delay(100);
    }
    Serial.println();

    // Connected!
    Serial.printf("[WIFI] STATION Mode, SSID: %s, IP address: %s\n", WiFi.SSID().c_str(), WiFi.localIP().toString().c_str());

    }

    void setup() {

    // Init serial port and clean garbage
    Serial.begin(SERIAL_BAUDRATE);
    Serial.println();
    Serial.println();

    // Wifi
    wifiSetup();

    // LED
    pinMode(LED, OUTPUT);
    digitalWrite(LED, HIGH);

    // You can enable or disable the library at any moment
    // Disabling it will prevent the devices from being discovered and switched
    fauxmo.enable(true);

    // Add virtual devices
    fauxmo.addDevice("bedroom curtain");
 //fauxmo.addDevice("switch two"); // You can add more devices
 //fauxmo.addDevice("switch three");

    // -------------------------------
    // Motor

    AFMS.begin();  // create with the default frequency 1.6KHz
    //AFMS.begin(1000);  // OR with a different frequency, say 1KHz

    myMotor->setSpeed(10);  // 10 rpm

    //-------------------------------------------

    // fauxmoESP 2.0.0 has changed the callback signature to add the device_id,
    // this way it's easier to match devices to action without having to compare strings.
    fauxmo.onSetState([](unsigned char device_id, const char * device_name, bool state) {
        Serial.printf("[MAIN] Device #%d (%s) state: %s\n", device_id, device_name, state ? "ON" : "OFF");
        digitalWrite(LED, !state);

        if (state == HIGH) {
          Serial.print("Closing the curtain...");
        }
        else {
          Serial.print("Opening the curtain...");
          openCurtain();
        }

    });

    // Callback to retrieve current state (for GetBinaryState queries)
    fauxmo.onGetState([](unsigned char device_id, const char * device_name) {
        return !digitalRead(LED);
    });

    }

    void openCurtain() {
    myMotor->step(100, FORWARD, SINGLE);
    }

    void closeCurtain() {
    myMotor->step(100, BACKWARD, SINGLE);
    }

    void loop() {

    // Since fauxmoESP 2.0 the library uses the "compatibility" mode by
    // default, this means that it uses WiFiUdp class instead of AsyncUDP.
    // The later requires the Arduino Core for ESP8266 staging version
    // whilst the former works fine with current stable 2.3.0 version.
    // But, since it's not "async" anymore we have to manually poll for UDP
    // packets
    fauxmo.handle();

    static unsigned long last = millis();
    if (millis() - last > 5000) {
        last = millis();
        Serial.printf("[MAIN] Free heap: %d bytes\n", ESP.getFreeHeap());

    }

    }

and this is the full error being reported before the ESP8266 tries to reset itself:

    [MAIN] Device #0 (bedroom curtain) state: OFF
    Opening the curtain...
    Panic
    /Users/lewisaburrow/Library/Arduino15/packages/esp8266/hardware/esp8266/2.3.0/cores/esp8266/core_esp8266_main.cpp:98 __yield

    ctx: sys
    sp: 3ffff9d0 end: 3fffffb0 offset: 01b0

    >>>stack>>>
    3ffffb80:  00000001 00000002 3ffee770 40204b82
    3ffffb90:  4010702c 00007530 00000064 402059fd
    3ffffba0:  00000001 00000064 00007530 40204eca
    3ffffbb0:  00000001 00000000 3ffee984 402053e9
    3ffffbc0:  3ffe84e7 65526574 3ffffba0 3ffffe00
    3ffffbd0:  3ffee78c 00000000 3ffee984 40202204
    3ffffbe0:  3ffee78c 00000000 3ffee984 40202271
    3ffffbf0:  65707954 3ffffc00 00000000 40203881
    3ffffc00:  54534f50 70752f20 632f706e 72746e6f
    3ffffc10:  622f6c6f 63697361 6e657665 48203174
    3ffffc20:  2f505454 0d312e31 736f480a 31203a74
    3ffffc30:  312e3239 312e3836 3933312e 3032353a
    3ffffc40:  0a0d3030 65636341 203a7470 0d2a2f2a
    3ffffc50:  6e6f430a 746e6574 7079742d 74203a65
    3ffffc60:  2f747865 3b6c6d78 61686320 74657372
    3ffffc70:  7475223d 22382d66 4f530a0d 43415041
    3ffffc80:  4e4f4954 7522203a 423a6e72 696b6c65
    3ffffc90:  65733a6e 63697672 61623a65 65636973
    3ffffca0:  746e6576 5323313a 69427465 7972616e
    3ffffcb0:  74617453 0a0d2265 746e6f43 2d746e65
    3ffffcc0:  676e654c 203a6874 0d393932 3c0a0d0a
    3ffffcd0:  6c6d783f 72657620 6e6f6973 2e31223d
    3ffffce0:  65202230 646f636e 3d676e69 66747522
    3ffffcf0:  3f22382d 3a733c3e 65766e45 65706f6c
    3ffffd00:  6c6d7820 733a736e 7468223d 2f3a7074
    3ffffd10:  6863732f 73616d65 6c6d782e 70616f73
    3ffffd20:  67726f2e 616f732f 6e652f70 6f6c6576
    3ffffd30:  222f6570 653a7320 646f636e 53676e69
    3ffffd40:  656c7974 7468223d 2f3a7074 6863732f
    3ffffd50:  73616d65 6c6d782e 70616f73 67726f2e
    3ffffd60:  616f732f 6e652f70 69646f63 222f676e
    3ffffd70:  3a733c3e 79646f42 3a753c3e 42746553
    3ffffd80:  72616e69 61745379 78206574 736e6c6d
    3ffffd90:  223d753a 3a6e7275 6b6c6542 733a6e69
    3ffffda0:  69767265 623a6563 63697361 6e657665
    3ffffdb0:  22313a74 69423c3e 7972616e 74617453
    3ffffdc0:  3c303e65 6e69422f 53797261 65746174
    3ffffdd0:  752f3c3e 7465533a 616e6942 74537972
    3ffffde0:  3e657461 3a732f3c 79646f42 732f3c3e
    3ffffdf0:  766e453a 706f6c65 00003e65 40101ea2
    3ffffe00:  3fff0a5c 00000002 3fff0d0c 4010020c
    3ffffe10:  40102bb5 3ffec9a8 3ffffe60 3fff0d0c
    3ffffe20:  00000000 3ffee78c 3ffeb7c2 40203a5c
    3ffffe30:  54534f50 70752f20 632f706e 72746e6f
    3ffffe40:  622f6c6f 63697361 6e657665 48203174
    3ffffe50:  2f505454 00312e31 3ffe97fc 00000001
    3ffffe60:  000001fa 00007fff 000000ed 4010020c
    3ffffe70:  3ffee960 04c14103 00002200 00000000
    3ffffe80:  3fff0d0c 3fff09bc 00000000 40203a80
    3ffffe90:  3ffe97c0 00000000 3fff0084 40204504
    3ffffea0:  3fff0bdc 00000030 0000000f ffffffff
    3ffffeb0:  3fff026c 3fff0274 00000006 3fff0080
    3ffffec0:  3fff0bdc 3fff0088 3fff0084 4020454f
    3ffffed0:  3fff0bdc 3fff0088 3fff0084 40229c30
    3ffffee0:  000001fa 8b01a8c0 00000018 000001fa
    3ffffef0:  00000018 00000000 3ffeea40 401074e4
    3fffff00:  40100000 00000000 00000064 3fff0270
    3fffff10:  3ffeb79a 3fff0274 3fff09bc 40228139
    3fffff20:  3ffeff94 3fff072c 3fff072c 3ffedaf0
    3fffff30:  00000000 3fff09bc 0000001c 3fff072c
    3fffff40:  3ffeb78c 00000000 3fff09bc 40227535
    3fffff50:  6301a8c0 00000258 00000000 0000001c
    3fffff60:  00000002 0000001a 40207f53 3ffec9a8
    3fffff70:  3ffeb764 3fffdcc0 3ffe9040 3ffe9040
    3fffff80:  40207ec6 3ffec9a8 00000000 3fff079c
    3fffff90:  3fffdc80 00000000 3fff09bc 4021bfbb
    3fffffa0:  40000f49 3fffdab0 3fffdab0 40000f49
    <<<stack<<<

    ets Jan  8 2013,rst cause:2, boot mode:(1,7)

    ets Jan  8 2013,rst cause:4, boot mode:(1,7)

    wdt reset

title: Error when moving stepper motor - Alexa curtain opener

Answers: 0


body:
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
    }

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

Answers: 1

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.


body:
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);*/
    }
    }

title: Problem while connecting two arduino with NRF24L01

Answers: 1

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.


body:
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

title: Disable the Amplifier during the flashing ESP8266

Answers: 1

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).


body:
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

title: Connecting LCD TFT shield to NodeMCU

Answers: 1

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


body:
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?

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

Answers: 1

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.


body:
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();
    }

title: Rc receiver giving wrong values when controlling servo

Answers: 1

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();
    }


body:
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.

title: NodeMCU ESP12 Voltage

Answers: 1

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.


body:
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

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

Answers: 1

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


body:
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);

    }

title: "Serial does not name a type error"

Answers: 1

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.