body:
I am trying to set up an LED-strip of 30 RGB LEDs (model WS2801). The strip is connected to an Arduino Uno and an external power supply and the goal is to send colors to the arduino using PySerial which are then shown on the LED strip.

I have been trying to wrap my head around the communications, which I am having a hard time with, especially due to the loose typing of python.

I wrote some code that generates smooth color transitions and got the strip to actually show a fairly smooth color transition, unfortunately the colors are the wrong ones.

Now I am guessing something overflows somewhere, especially since colors such as 0xFF0000 (red) show as a yellow tone, which indicates that on top of red some green gets added as well.

The Python code using pySerial:

    @classmethod
    def set_lights(self: RGBHardware, colors: List[int]) -> None:
        for i in range(len(colors)):
            rgb = color_to_rgb(colors[i])
            self.arduino.write(chr(76).encode()) # 'L'
            self.arduino.write(chr(i).encode())
            self.arduino.write(chr(rgb[0]).encode())
            self.arduino.write(chr(rgb[1]).encode())
            self.arduino.write(chr(rgb[2]).encode())
        self.arduino.write(chr(90).encode()) # 'Z'

    @classmethod
    def turn_on(self) -> None:
        self.arduino = serial.Serial('/dev/ttyACM0', 115200)
        if self.arduino.isOpen:
            self.arduino.close()
        self.arduino.open()
        pass

The code running on the Arduino Uno:

    void setup() {
    #if defined(__AVR_ATtiny85__) && (F_CPU == 16000000L)
      clock_prescale_set(clock_div_1); // Enable 16 MHz on Trinket
    #endif

      Serial.begin(115200);
      strip.begin();
      // Update LED contents, to start they are all 'off'
      strip.show();
    }

    void loop() {
       while (Serial.available()) {
            uint8_t serial = Serial.read();
            if (serial == 'Z') {
                strip.show();
            } else if (serial == 'L') {
                int i = getNextInput();
                int r = getNextInput();
                int g = getNextInput();
                int b = getNextInput();
                strip.setPixelColor(i, Color(r,g,b));
            }
       }
    }

    uint8_t getNextInput() {
      while(!Serial.available()); // wait for a character
      return Serial.read();
    }

I am having the strong feeling I am just missing a miniscule detail and it is quite frustrating.

Any help would be greatly appreciated!

EDIT:
So I recorded some data and pasted the results below. I found that always not the whole LED-strip was updated and none of it with the correct color. Once even the character "Z" seemed to go missing (that causes the strip to fully refresh) so no color was showing at all.

What I also forgot to mention earlier was that I am using Celery in Python to do the light switching as a background task.

To record the results I used

`print("i, R,G,B: " + str(i) + ", " + str(rgb[0]) + "," + str(rgb[1]) + "," + str(rgb[2]))` to print the data in python and

`Serial.println("i, R,G,B: " + String(i) + ", " + String(r) + "," + String(g) + "," + String(b));` to do the same on the Arduino.

Sending color red from Python:

    [2018-07-23 16:13:57,121: WARNING/ForkPoolWorker-7] i, R,G,B: 0, 255,0,0
    [2018-07-23 16:13:57,122: WARNING/ForkPoolWorker-7] i, R,G,B: 1, 255,0,0
    [2018-07-23 16:13:57,123: WARNING/ForkPoolWorker-7] i, R,G,B: 2, 255,0,0
    [2018-07-23 16:13:57,125: WARNING/ForkPoolWorker-7] i, R,G,B: 3, 255,0,0
    [2018-07-23 16:13:57,126: WARNING/ForkPoolWorker-7] i, R,G,B: 4, 255,0,0
    [2018-07-23 16:13:57,127: WARNING/ForkPoolWorker-7] i, R,G,B: 5, 255,0,0
    [2018-07-23 16:13:57,127: WARNING/ForkPoolWorker-7] i, R,G,B: 6, 255,0,0
    [2018-07-23 16:13:57,128: WARNING/ForkPoolWorker-7] i, R,G,B: 7, 255,0,0
    [2018-07-23 16:13:57,129: WARNING/ForkPoolWorker-7] i, R,G,B: 8, 255,0,0
    [2018-07-23 16:13:57,129: WARNING/ForkPoolWorker-7] i, R,G,B: 9, 255,0,0
    [2018-07-23 16:13:57,131: WARNING/ForkPoolWorker-7] i, R,G,B: 10, 255,0,0
    [2018-07-23 16:13:57,132: WARNING/ForkPoolWorker-7] i, R,G,B: 11, 255,0,0
    [2018-07-23 16:13:57,132: WARNING/ForkPoolWorker-7] i, R,G,B: 12, 255,0,0
    [2018-07-23 16:13:57,133: WARNING/ForkPoolWorker-7] i, R,G,B: 13, 255,0,0
    [2018-07-23 16:13:57,134: WARNING/ForkPoolWorker-7] i, R,G,B: 14, 255,0,0
    [2018-07-23 16:13:57,136: WARNING/ForkPoolWorker-7] i, R,G,B: 15, 255,0,0
    [2018-07-23 16:13:57,137: WARNING/ForkPoolWorker-7] i, R,G,B: 16, 255,0,0
    [2018-07-23 16:13:57,139: WARNING/ForkPoolWorker-7] i, R,G,B: 17, 255,0,0
    [2018-07-23 16:13:57,140: WARNING/ForkPoolWorker-7] i, R,G,B: 18, 255,0,0
    [2018-07-23 16:13:57,141: WARNING/ForkPoolWorker-7] i, R,G,B: 19, 255,0,0
    [2018-07-23 16:13:57,142: WARNING/ForkPoolWorker-7] i, R,G,B: 20, 255,0,0
    [2018-07-23 16:13:57,144: WARNING/ForkPoolWorker-7] i, R,G,B: 21, 255,0,0
    [2018-07-23 16:13:57,145: WARNING/ForkPoolWorker-7] i, R,G,B: 22, 255,0,0
    [2018-07-23 16:13:57,146: WARNING/ForkPoolWorker-7] i, R,G,B: 23, 255,0,0
    [2018-07-23 16:13:57,147: WARNING/ForkPoolWorker-7] i, R,G,B: 24, 255,0,0
    [2018-07-23 16:13:57,148: WARNING/ForkPoolWorker-7] i, R,G,B: 25, 255,0,0
    [2018-07-23 16:13:57,149: WARNING/ForkPoolWorker-7] i, R,G,B: 26, 255,0,0
    [2018-07-23 16:13:57,150: WARNING/ForkPoolWorker-7] i, R,G,B: 27, 255,0,0
    [2018-07-23 16:13:57,151: WARNING/ForkPoolWorker-7] i, R,G,B: 28, 255,0,0
    [2018-07-23 16:13:57,151: WARNING/ForkPoolWorker-7] i, R,G,B: 29, 255,0,0

Received color red on the arduino:

    i, R,G,B: 0, 195,191,0
    i, R,G,B: 1, 195,191,0
    i, R,G,B: 2, 195,191,0
    i, R,G,B: 3, 195,191,0
    i, R,G,B: 4, 195,191,0
    i, R,G,B: 5, 195,191,0
    i, R,G,B: 6, 195,191,0
    i, R,G,B: 7, 195,191,0
    i, R,G,B: 8, 195,191,0
    i, R,G,B: 9, 195,191,0
    i, R,G,B: 10, 195,191,0
    i, R,G,B: 11, 195,191,0
    i, R,G,B: 12, 195,191,0
    i, R,G,B: 13, 195,191,0
    i, R,G,B: 14, 195,191,0
    i, R,G,B: 15, 195,191,0
    i, R,G,B: 16, 195,191,0
    i, R,G,B: 17, 195,191,0
    i, R,G,B: 18, 195,191,0
    i, R,G,B: 19, 195,191,0
    i, R,G,B: 20, 195,191,0
    i, R,G,B: 21, 195,191,0
    i, R,G,B: 22, 195,191,0
    i, R,G,B: 23, 195,191,0
    i, R,G,B: 24, 195,191,0
    i, R,G,B: 25, 195,191,0
    i, R,G,B: 26, 76,27,195

Sending color green from Python:

    [2018-07-23 16:22:34,374: WARNING/ForkPoolWorker-8] i, R,G,B: 0, 0,255,0
    [2018-07-23 16:22:34,376: WARNING/ForkPoolWorker-8] i, R,G,B: 1, 0,255,0
    [2018-07-23 16:22:34,377: WARNING/ForkPoolWorker-8] i, R,G,B: 2, 0,255,0
    [2018-07-23 16:22:34,378: WARNING/ForkPoolWorker-8] i, R,G,B: 3, 0,255,0
    [2018-07-23 16:22:34,380: WARNING/ForkPoolWorker-8] i, R,G,B: 4, 0,255,0
    [2018-07-23 16:22:34,381: WARNING/ForkPoolWorker-8] i, R,G,B: 5, 0,255,0
    [2018-07-23 16:22:34,382: WARNING/ForkPoolWorker-8] i, R,G,B: 6, 0,255,0
    [2018-07-23 16:22:34,383: WARNING/ForkPoolWorker-8] i, R,G,B: 7, 0,255,0
    [2018-07-23 16:22:34,384: WARNING/ForkPoolWorker-8] i, R,G,B: 8, 0,255,0
    [2018-07-23 16:22:34,385: WARNING/ForkPoolWorker-8] i, R,G,B: 9, 0,255,0
    [2018-07-23 16:22:34,386: WARNING/ForkPoolWorker-8] i, R,G,B: 10, 0,255,0
    [2018-07-23 16:22:34,387: WARNING/ForkPoolWorker-8] i, R,G,B: 11, 0,255,0
    [2018-07-23 16:22:34,387: WARNING/ForkPoolWorker-8] i, R,G,B: 12, 0,255,0
    [2018-07-23 16:22:34,388: WARNING/ForkPoolWorker-8] i, R,G,B: 13, 0,255,0
    [2018-07-23 16:22:34,389: WARNING/ForkPoolWorker-8] i, R,G,B: 14, 0,255,0
    [2018-07-23 16:22:34,389: WARNING/ForkPoolWorker-8] i, R,G,B: 15, 0,255,0
    [2018-07-23 16:22:34,390: WARNING/ForkPoolWorker-8] i, R,G,B: 16, 0,255,0
    [2018-07-23 16:22:34,390: WARNING/ForkPoolWorker-8] i, R,G,B: 17, 0,255,0
    [2018-07-23 16:22:34,391: WARNING/ForkPoolWorker-8] i, R,G,B: 18, 0,255,0
    [2018-07-23 16:22:34,392: WARNING/ForkPoolWorker-8] i, R,G,B: 19, 0,255,0
    [2018-07-23 16:22:34,393: WARNING/ForkPoolWorker-8] i, R,G,B: 20, 0,255,0
    [2018-07-23 16:22:34,393: WARNING/ForkPoolWorker-8] i, R,G,B: 21, 0,255,0
    [2018-07-23 16:22:34,394: WARNING/ForkPoolWorker-8] i, R,G,B: 22, 0,255,0
    [2018-07-23 16:22:34,395: WARNING/ForkPoolWorker-8] i, R,G,B: 23, 0,255,0
    [2018-07-23 16:22:34,395: WARNING/ForkPoolWorker-8] i, R,G,B: 24, 0,255,0
    [2018-07-23 16:22:34,396: WARNING/ForkPoolWorker-8] i, R,G,B: 25, 0,255,0
    [2018-07-23 16:22:34,397: WARNING/ForkPoolWorker-8] i, R,G,B: 26, 0,255,0
    [2018-07-23 16:22:34,398: WARNING/ForkPoolWorker-8] i, R,G,B: 27, 0,255,0
    [2018-07-23 16:22:34,398: WARNING/ForkPoolWorker-8] i, R,G,B: 28, 0,255,0
    [2018-07-23 16:22:34,399: WARNING/ForkPoolWorker-8] i, R,G,B: 29, 0,255,0

Received color green on the Arduino:

    i, R,G,B: 0, 0,195,191
    i, R,G,B: 1, 0,195,191
    i, R,G,B: 2, 0,195,191
    i, R,G,B: 3, 0,195,191
    i, R,G,B: 4, 0,195,191
    i, R,G,B: 5, 0,195,191
    i, R,G,B: 6, 0,195,191
    i, R,G,B: 7, 0,195,191
    i, R,G,B: 8, 0,195,191
    i, R,G,B: 9, 0,195,191
    i, R,G,B: 10, 0,195,191
    i, R,G,B: 11, 0,195,191
    i, R,G,B: 12, 0,195,191
    i, R,G,B: 13, 0,195,191
    i, R,G,B: 14, 0,195,191
    i, R,G,B: 15, 0,195,191
    i, R,G,B: 16, 0,195,191
    i, R,G,B: 17, 0,195,191
    i, R,G,B: 18, 0,195,191
    i, R,G,B: 19, 0,195,191
    i, R,G,B: 20, 0,195,191
    i, R,G,B: 21, 0,195,191
    i, R,G,B: 22, 0,195,191
    i, R,G,B: 23, 0,195,191
    i, R,G,B: 24, 0,195,191
    i, R,G,B: 25, 0,195,191
    i, R,G,B: 26, 76,28,0

Sending color blue from Python:

    [2018-07-23 16:26:52,416: WARNING/ForkPoolWorker-2] i, R,G,B: 0, 0,0,255
    [2018-07-23 16:26:52,416: WARNING/ForkPoolWorker-2] i, R,G,B: 1, 0,0,255
    [2018-07-23 16:26:52,417: WARNING/ForkPoolWorker-2] i, R,G,B: 2, 0,0,255
    [2018-07-23 16:26:52,417: WARNING/ForkPoolWorker-2] i, R,G,B: 3, 0,0,255
    [2018-07-23 16:26:52,418: WARNING/ForkPoolWorker-2] i, R,G,B: 4, 0,0,255
    [2018-07-23 16:26:52,418: WARNING/ForkPoolWorker-2] i, R,G,B: 5, 0,0,255
    [2018-07-23 16:26:52,419: WARNING/ForkPoolWorker-2] i, R,G,B: 6, 0,0,255
    [2018-07-23 16:26:52,419: WARNING/ForkPoolWorker-2] i, R,G,B: 7, 0,0,255
    [2018-07-23 16:26:52,420: WARNING/ForkPoolWorker-2] i, R,G,B: 8, 0,0,255
    [2018-07-23 16:26:52,420: WARNING/ForkPoolWorker-2] i, R,G,B: 9, 0,0,255
    [2018-07-23 16:26:52,421: WARNING/ForkPoolWorker-2] i, R,G,B: 10, 0,0,255
    [2018-07-23 16:26:52,421: WARNING/ForkPoolWorker-2] i, R,G,B: 11, 0,0,255
    [2018-07-23 16:26:52,422: WARNING/ForkPoolWorker-2] i, R,G,B: 12, 0,0,255
    [2018-07-23 16:26:52,422: WARNING/ForkPoolWorker-2] i, R,G,B: 13, 0,0,255
    [2018-07-23 16:26:52,423: WARNING/ForkPoolWorker-2] i, R,G,B: 14, 0,0,255
    [2018-07-23 16:26:52,423: WARNING/ForkPoolWorker-2] i, R,G,B: 15, 0,0,255
    [2018-07-23 16:26:52,424: WARNING/ForkPoolWorker-2] i, R,G,B: 16, 0,0,255
    [2018-07-23 16:26:52,424: WARNING/ForkPoolWorker-2] i, R,G,B: 17, 0,0,255
    [2018-07-23 16:26:52,425: WARNING/ForkPoolWorker-2] i, R,G,B: 18, 0,0,255
    [2018-07-23 16:26:52,426: WARNING/ForkPoolWorker-2] i, R,G,B: 19, 0,0,255
    [2018-07-23 16:26:52,427: WARNING/ForkPoolWorker-2] i, R,G,B: 20, 0,0,255
    [2018-07-23 16:26:52,427: WARNING/ForkPoolWorker-2] i, R,G,B: 21, 0,0,255
    [2018-07-23 16:26:52,428: WARNING/ForkPoolWorker-2] i, R,G,B: 22, 0,0,255
    [2018-07-23 16:26:52,428: WARNING/ForkPoolWorker-2] i, R,G,B: 23, 0,0,255
    [2018-07-23 16:26:52,429: WARNING/ForkPoolWorker-2] i, R,G,B: 24, 0,0,255
    [2018-07-23 16:26:52,429: WARNING/ForkPoolWorker-2] i, R,G,B: 25, 0,0,255
    [2018-07-23 16:26:52,430: WARNING/ForkPoolWorker-2] i, R,G,B: 26, 0,0,255
    [2018-07-23 16:26:52,430: WARNING/ForkPoolWorker-2] i, R,G,B: 27, 0,0,255
    [2018-07-23 16:26:52,431: WARNING/ForkPoolWorker-2] i, R,G,B: 28, 0,0,255
    [2018-07-23 16:26:52,431: WARNING/ForkPoolWorker-2] i, R,G,B: 29, 0,0,255

Received color blue on the Arduino:

    i, R,G,B: 0, 0,0,195
    i, R,G,B: 1, 0,0,195
    i, R,G,B: 2, 0,0,195
    i, R,G,B: 3, 0,0,195
    i, R,G,B: 4, 0,0,195
    i, R,G,B: 5, 0,0,195
    i, R,G,B: 6, 0,0,195
    i, R,G,B: 7, 0,0,195
    i, R,G,B: 8, 0,0,195
    i, R,G,B: 9, 0,0,195
    i, R,G,B: 10, 0,0,195
    i, R,G,B: 11, 0,0,195
    i, R,G,B: 12, 0,0,195
    i, R,G,B: 13, 0,0,195
    i, R,G,B: 14, 0,0,195
    i, R,G,B: 15, 0,0,195
    i, R,G,B: 16, 0,0,195
    i, R,G,B: 17, 0,0,195
    i, R,G,B: 18, 0,0,195
    i, R,G,B: 20, 0,0,195
    i, R,G,B: 23, 191,76,26

Sending color orange from Python:

    [2018-07-23 16:29:20,725: WARNING/ForkPoolWorker-9] i, R,G,B: 0, 255,128,0
    [2018-07-23 16:29:20,726: WARNING/ForkPoolWorker-9] i, R,G,B: 1, 255,128,0
    [2018-07-23 16:29:20,727: WARNING/ForkPoolWorker-9] i, R,G,B: 2, 255,128,0
    [2018-07-23 16:29:20,728: WARNING/ForkPoolWorker-9] i, R,G,B: 3, 255,128,0
    [2018-07-23 16:29:20,729: WARNING/ForkPoolWorker-9] i, R,G,B: 4, 255,128,0
    [2018-07-23 16:29:20,731: WARNING/ForkPoolWorker-9] i, R,G,B: 5, 255,128,0
    [2018-07-23 16:29:20,732: WARNING/ForkPoolWorker-9] i, R,G,B: 6, 255,128,0
    [2018-07-23 16:29:20,733: WARNING/ForkPoolWorker-9] i, R,G,B: 7, 255,128,0
    [2018-07-23 16:29:20,734: WARNING/ForkPoolWorker-9] i, R,G,B: 8, 255,128,0
    [2018-07-23 16:29:20,735: WARNING/ForkPoolWorker-9] i, R,G,B: 9, 255,128,0
    [2018-07-23 16:29:20,736: WARNING/ForkPoolWorker-9] i, R,G,B: 10, 255,128,0
    [2018-07-23 16:29:20,737: WARNING/ForkPoolWorker-9] i, R,G,B: 11, 255,128,0
    [2018-07-23 16:29:20,738: WARNING/ForkPoolWorker-9] i, R,G,B: 12, 255,128,0
    [2018-07-23 16:29:20,739: WARNING/ForkPoolWorker-9] i, R,G,B: 13, 255,128,0
    [2018-07-23 16:29:20,740: WARNING/ForkPoolWorker-9] i, R,G,B: 14, 255,128,0
    [2018-07-23 16:29:20,741: WARNING/ForkPoolWorker-9] i, R,G,B: 15, 255,128,0
    [2018-07-23 16:29:20,742: WARNING/ForkPoolWorker-9] i, R,G,B: 16, 255,128,0
    [2018-07-23 16:29:20,743: WARNING/ForkPoolWorker-9] i, R,G,B: 17, 255,128,0
    [2018-07-23 16:29:20,744: WARNING/ForkPoolWorker-9] i, R,G,B: 18, 255,128,0
    [2018-07-23 16:29:20,744: WARNING/ForkPoolWorker-9] i, R,G,B: 19, 255,128,0
    [2018-07-23 16:29:20,745: WARNING/ForkPoolWorker-9] i, R,G,B: 20, 255,128,0
    [2018-07-23 16:29:20,746: WARNING/ForkPoolWorker-9] i, R,G,B: 21, 255,128,0
    [2018-07-23 16:29:20,747: WARNING/ForkPoolWorker-9] i, R,G,B: 22, 255,128,0
    [2018-07-23 16:29:20,747: WARNING/ForkPoolWorker-9] i, R,G,B: 23, 255,128,0
    [2018-07-23 16:29:20,749: WARNING/ForkPoolWorker-9] i, R,G,B: 24, 255,128,0
    [2018-07-23 16:29:20,750: WARNING/ForkPoolWorker-9] i, R,G,B: 25, 255,128,0
    [2018-07-23 16:29:20,750: WARNING/ForkPoolWorker-9] i, R,G,B: 26, 255,128,0
    [2018-07-23 16:29:20,751: WARNING/ForkPoolWorker-9] i, R,G,B: 27, 255,128,0
    [2018-07-23 16:29:20,752: WARNING/ForkPoolWorker-9] i, R,G,B: 28, 255,128,0
    [2018-07-23 16:29:20,752: WARNING/ForkPoolWorker-9] i, R,G,B: 29, 255,128,0

Received color orange on the Arduino:

    i, R,G,B: 0, 195,191,194
    i, R,G,B: 1, 195,191,194
    i, R,G,B: 2, 195,191,194
    i, R,G,B: 3, 195,191,194
    i, R,G,B: 4, 195,191,194
    i, R,G,B: 5, 195,191,194
    i, R,G,B: 6, 195,191,194
    i, R,G,B: 7, 195,191,194
    i, R,G,B: 8, 195,191,194
    i, R,G,B: 9, 195,191,194
    i, R,G,B: 10, 195,191,194
    i, R,G,B: 11, 195,191,194
    i, R,G,B: 12, 195,191,194
    i, R,G,B: 13, 195,191,194
    i, R,G,B: 14, 195,191,194
    i, R,G,B: 15, 195,191,194
    i, R,G,B: 16, 195,191,194
    i, R,G,B: 17, 195,191,194
    i, R,G,B: 18, 195,191,194
    i, R,G,B: 19, 195,191,194
    i, R,G,B: 76, 23,195,191
    i, R,G,B: 194, 128,0,76

Received color orange on the Arduino (again):

    i, R,G,B: 0, 195,191,194
    i, R,G,B: 1, 195,191,194
    i, R,G,B: 2, 195,191,194
    i, R,G,B: 3, 195,191,194
    i, R,G,B: 4, 195,191,194
    i, R,G,B: 5, 195,191,194
    i, R,G,B: 6, 195,191,194
    i, R,G,B: 7, 195,191,194
    i, R,G,B: 8, 195,191,194
    i, R,G,B: 9, 195,191,194
    i, R,G,B: 10, 195,191,194
    i, R,G,B: 11, 195,191,194
    i, R,G,B: 12, 195,191,194
    i, R,G,B: 13, 195,191,194
    i, R,G,B: 14, 195,191,194
    i, R,G,B: 15, 195,191,194
    i, R,G,B: 16, 195,191,194
    i, R,G,B: 17, 195,191,194
    i, R,G,B: 18, 195,191,194
    i, R,G,B: 128, 0,76,24
    i, R,G,B: 27, 195,191,194

Another Edit:
What is also interesting is that the main color (e.g. when I send red most of the LEDs are yellow) stays the same every time I tried.
But the amount of LEDs that gets passed differs with each try. The same goes for the last one or two LEDs the Arduino receives. Their colors and indexes are all over the place.

title: RGB LED strip controlled through PySerial only somewhat functional

Answers: 1

body:
This

    ...
      self.arduino.write(chr(76).encode()) # 'L'
      self.arduino.write(chr(i).encode())
      self.arduino.write(chr(rgb[0]).encode())
      self.arduino.write(chr(rgb[1]).encode())
      self.arduino.write(chr(rgb[2]).encode())
    self.arduino.write(chr(90).encode()) # 'Z'
    ...
should be spelled:

      self.arduino.write(b'L')
      self.arduino.write(i.to_bytes(1,'big'))
      self.arduino.write(bytes(rgb))
    self.arduino.write(b'Z')

It is much more readable this way; you could refactor even further:

      sout = b'L' + i.to_bytes(1,'big') + bytes(rgb)
      self.arduino.write(sout)
    self.arduino.write(b'Z')
Your also wasting effort here:

    Serial.println("i, R,G,B: " + String(i) + ", " + String(r) + "," + String(g) + "," + String(b));
This should be said more like this:

    Serial.print(i);
    Serial.print(", ");
    Serial.print(r);
    Serial.print(", ");
    Serial.print(g);
    Serial.print(", ");
    Serial.println(b);

This eliminates three temporary String objects you were creating with String().

The rest of the code looks like it should work so you should try trouble shooting, you could:

 - Lower the baud rate till it works
 - Try 9600 baud and increase it until it stops working
 - Try the a serial sample program, make sure the serial portion is working correctly first
 - Write your own minimal test program, make sure the serial is working correctly at first.


body:
I would like to know if there are always the latest features in Arduino Desktop IDE if I update it every day.

I mean if there is a new feature in Arduino Web Editor, can I get it on Arduino Desktop IDE?

title: In the latest version of Arduino Desktop IDE, are there all features of Arduino Web Editor?

Answers: 1

body:
You will always get the same API features in both, because the API is separate to both of them - it's a plugin that's developed separately.

Would you get the same GUI facilities? No idea. Maybe - maybe not. It depends how useful they would be. You may get features added to the GUI that don't appear on the web. Or you may get the other way around. If they are essential to the operation of the system, though, you will get them added to both.


body:
I have a Uno R3 and although I can add an external power supply for the SG90 micro servo it would make the project more complicated. Can I power the servo using the 5v pin of the Uno R3?

I measured the current and it does not seem to pass 160mA and in normal use, it uses only 60mA.

title: Do I need an external power supply for the SG90 micro servo?

Answers: 2

body:
I'm not sure if the data sheet for every SG90 servo is the same, but if you look at this one, [SG90 Specifications][1], you'll see the "stall current" can be between 570mA and 730mA. You may want to test your servo under this condition before deciding to power it with an Uno.

  [1]: https://arduino.stackexchange.com/a/49755/37523

body: Does your servo have to push or pull anything? Or is this just to practice writing code for an unattached SG90 and see it move? If it's the former, the servo will draw more current than an Arduino can deliver so you'd need a separate power supply. If it's the latter, you can get away with it. The SG90 is about the least demanding (of current) servo available and you can drive an *unloaded* one directly off the Arduino. It's current-peaks should be short enough to limit thermal damage to the Arduino pin driver. Just make short test runs and don't leave it see-sawing for any length of time.


body:
I've got an Arduino UNO REV3 SMD EDITION.

In the Arduino Editor, I've selected `Arduino/Genuino Uno`.

In a tutorial, I saw `Hardware required : Arduino or Genuino Board`

What is the difference between Arduino board and Genuino Board?

Answers: 1

body:
The name Genuino grew out of the split between Massimo and Gianluca (aided in part by Microsoft of course, and a trademark wrangle that went wrong). Each side wanted to appear to be more "genuine" than the other. That lead to the "Genuino" name (a *genuine* Arduino), and a version number war with the IDE.

Both sides started making their own variants of boards, with some only available from the USA (Arduino) and others only outside the USA (Genuino).

Since they have patched up their differences now the two boards are one and the same. A Genuino Uno and an Arduino Uno are the exact same board. They always have been, there has just been arguments over the name.


body:
Is it safe to build a circuit while the Arduino board is powered?

Should I power the board only when I have to upload the program?

title: Do I need to power off the Arduino board before doing something?

Answers: 2

body:
It can be dangerous, not only to the Arduino, but to whatever you are connecting, if you do so with the power applied.

Current can end up flowing where it shouldn't, and components can become damaged.

However if it's something as simple as an LED then it really doesn't matter.

body:
It is not safe, as you may accidentally connect some points, which should not be connected and destroy Arduino and/or any other part of circuit. typically legs of resistors/LEDs tends to touch other legs near them, when you are putting it in - and if it is powered, magical smoke can happened easily.

Even if you do not this kind of mistake, not everything can be put in random order without risc of damage.

So everytime you change something with circuit, disconnect power source/USB first. And if you have big capacitors anywhere, you better make sure, they are discharged too.

You switch on the board, when the building is done and you want to program it, or use the already present program.


body:
To finalize a prototype, I would like to have a proper structure containing the arduino (uno here), its shields and its sensors. I would like the sensors to be soldered to the arduino+shields block, but the sensors were sold on a small separate PCB ([example][1]).

**What is the recommended method to have a strong, clean link between the two ?**

  [1]: http://a.co/aeGIzCB

title: How to properly link an Arduino and its sensors

Answers: 1

body:
You could solder those modules to a prototype shield.  If you replace the header with a right-angle one (or even just bend the pins on the existing one) you could even mount it vertically to save space.

* Prototype shield:

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

* Right-angled headers:

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

  [1]: https://i.stack.imgur.com/YL7nR.jpg
  [2]: https://i.stack.imgur.com/117lf.jpg


body:
I am currently experimenting with a Digistump ATTiny85. Since it has no Serial, I use the basic `DigiUSB` library for communication. The RTC library used is this one: https://github.com/JChristensen/DS3232RTC/. The DigiUSB library is from Digispark.

I attached a DS3232 via TWI to the Digistump, because I want to use this construct as a USB-Realtime-Clock.

Initially setting the time in the `setup` method works as follows

      RTC.set(1532341020);

But I am unable to transfer the time via the pseudo serial connection and set it remotely. What I've tried so far:

* Using `union` with `char` and `uint32_t`. Althougt the char representation is correct (tried DigiUSB.println()), the `uint32_t` representation of this union is not what I need.
* Tried to adapt to some shifting examples, but seriously got lost here. All examples where about 4 byte streams.
* `atoi` and some other functions with no success.

Here is my current sketch

    #include <DS3232RTC.h>
    #include <DigiUSB.h>

    //union ArrayToInteger {
    //  char array[10];
    //  uint32_t integer;
    //};

    unsigned char foo[10];
    uint32_t num;

    void setup() {
      RTC.begin();
      //RTC.set(1532341020);
      DigiUSB.begin();
    }

    void loop() {
      if (DigiUSB.available() >= 10) {
        for (int i=0; i<=10; i++) {
        foo[i] = DigiUSB.read();
      }
      RTC.set((uint32_t)foo);
      DigiUSB.delay(100);
      DigiUSB.refresh();
      //DigiUSB.println(_foo.array);
      DigiUSB.println(RTC.get());
    } else {
      DigiUSB.refresh();
      DigiUSB.println(RTC.get());
      DigiUSB.refresh();
      DigiUSB.delay(1000);
      }
    }

In the end I need the a `char _foo 0123456789` represented as/converted to `uint32_t num 0123456789`

Kinda stuck here. Can anyone point me in the right direction ore provide an example?

title: Reconstruct uint32_t from char array to RTC.set

Answers: 2

body:
There are several possible issues here:

* can you send the number, as a string, from the PC to the ATtiny?
* can you convert the string to an actual number?
* can you give this number to the RTC?

The phrasing of your question sounds like your issue is with the
conversion. However that is easily handled with `atol()`. Here is a test
program I tried on my Uno:

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

    void setup() {
        char time_string[] = "1532341020";
        uint32_t time_number = atol(time_string);

        Serial.begin(9600);
        Serial.print("string: \"");
        Serial.print(time_string);
        Serial.print("\", number = ");
        Serial.println(time_number);
    }

The output is:

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

    string: "1532341020", number = 1532341020

body:
Answering this question based on the help from above. It works with this code. Thank you all for the help. The clock does not reply the newly set time instantly, but after a few seconds.

    #include <DS3232RTC.h>
    #include <DigiUSB.h>
    char foo[10];

    void setup() {
      RTC.begin();
      DigiUSB.begin();
    }

     void loop() {
       if (DigiUSB.available() >= 10) {
         for (int i=0; i<=10; i++) {
           foo[i] = DigiUSB.read();
       }
       RTC.set(atol(foo));
       DigiUSB.delay(100);
       DigiUSB.refresh();
       DigiUSB.println(RTC.get());
    } else {
       DigiUSB.refresh();
       DigiUSB.println(RTC.get());
       DigiUSB.refresh();
       DigiUSB.delay(1000);
       }
    }


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

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

<!-- End schematic -->

(Newbie in arduino)
Hi so i have a project which involves creating an rc car which uses the 433Mhz rf module and an arduino nano with a servo motor and an ultrasonic parking sensor.

I'm having problems with the code both on the transmitter and receiver,
Here is the code for the transmitter.

     #include <RCSwitch.h>
    RCSwitch mySwitch = RCSwitch();
    // Assigning controller buttons to Digital Pins
     const int forward = 8;
     const int reverse = 9;
     const int rightTurn = 10;
     const int leftTurn = 11;

     int Fwd = 0
     int Bwd = 0
     int Lt  = 0
     int Rt  = 0

    void setup () {
      pinMode (forward, INPUT);
      pinMode (reverse, INPUT);
      pinMode (rightTurn, INPUT);
      pinMode (leftTurn, INPUT);
      mySwitch.enableTransmit(7);
      Serial.begin (9600);         // Debugging only
      Serial.println ("Transmitting");
    }

    void loop () {
      Fwd = digitalRead(forward);
      Bwd = digitalRead(reverse);
      Rt  = digitalRead(rightTurn);
      Lt  = digitalRead(leftTurn);

      if (Fwd == HIGH) {
        mySwitch.send('1');
        Serial.println ("Forward");
        delay(100);
      }

      if (Bwd == HIGH) {
        mySwitch.send('2');
        Serial.println ("Reverse");
        delay(100);
      }

      if (Rt == HIGH) {
        mySwitch.send('3');
        Serial.println ("Left Turn");
        delay(100);
      }

      if (Lt == HIGH) {
        mySwitch.send('4');
        Serial.println ("Right Turn");
        delay(100);
      }
    }

And here's the code for the receiver

    #include <RCSwitch.h>
    #include <Servo.h>

    const int IN1 = 3;
    const int IN2 = 4;
    const int trigPin = 5;
    const int echoPin = 6;
    int distance = 0;

    RCSwitch mySwitch = RCSwitch();
    Servo myservo;

    void setup () {
      mySwitch.enableReceive(2);
      myservo.attach(7);
      pinMode(IN1, OUTPUT);
      pinMode(IN2, OUTPUT);
      pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
      pinMode(echoPin, INPUT); // Sets the echoPin as an Input
      Serial.begin (9600);    // Debugging only
      Serial.println ("Receiver Ready");
    }

    void loop () {
     if (mySwitch.available()) {

        int value = mySwitch.getReceivedValue();

          if(value == '1') {
            forward ();
            Serial.println (" = forward");
          }

          if(value == '2'){
            backward ();
            Serial.println (" = backward");
          }

          if(value == '3') {
            left ();
            Serial.println (" = left");
          }

          if(value == '4') {
            right ();
            Serial.println (" = right");
          }
          Serial.print(" ");
        }

    }

    void forward () {
      digitalWrite (IN1, LOW);
      digitalWrite (IN2, HIGH);
    }
    long duration;
    int value = mySwitch.getReceivedValue();
    void backward () {
      if ((distance > 10)&& (value == '2'))
      {
      digitalWrite (IN1, LOW);
      digitalWrite (IN2, LOW);
      }
      else if ((distance < 10)&& (value == '2'))
      {
      digitalWrite (IN1, HIGH);
      digitalWrite (IN2, LOW);
      }
      delayMicroseconds(10);
      // 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;
      // Prints the distance on the Serial Monitor
      Serial.print("Distance: ");
      Serial.println(distance); //distance is the returned integer,
    }

    void right () {
      myservo.write(0);
      digitalWrite (IN1, LOW);
      digitalWrite (IN2, HIGH);
    }

    void left () {
      myservo.write(90);
      digitalWrite (IN1, LOW);
      digitalWrite (IN2, HIGH);
    }

The problem is when i run the code the buttons start getting pressed even if I'm not pressing them and even when i disconnect them from the arduino. and also the receiver cant receive any data.
Please help

title: Rc car controller using the RC-switch library

Answers: 1

body:
As you wrote in your comment, you didn't use  pullup or pulldown resistors for connecting the buttons. In this case the pin is floating, whenever the corresponding button is not pressed. It will pick up random noise from the environment and change it's state randomly.

A pullup or pulldown resistor defines a specific value for the pin, if the button is not pressed (LOW or HIGH). The value of such is a resistor is not critical, as long, as it isn't a too big load. Pick some value in the kiloohms (for example 10kOhm).

But you don't need external resistors for this. The Atmega328, which is the heart of the Arduino Nano, already has buildin pullup resistors for each digital output pin. You can activate them by using

    pinMode(pin_number, INPUT_PULLUP);

In this case you will have to change the if-statements to check for `LOW` instead of `HIGH` and connect the button to ground instead of 5V, because with a pullup resistor in idle state the pin will be pulled up to 5V and the button can then pull it down to ground.


body:
  Serial.write(0x0d); // hex

  Serial.write(13);   // ASCII

  Serial.write('\r');  // char

Is one more efficient? I read how it depends on the terminal program. So does that mean the IDE? (This is my first time working with serial comm.)

title: For Arduino, is there a meaningful difference between carriage returns?

Answers: 3

body:
> Is one more efficient?

after compilation it is same for all notations. the function and the value are the same for all 3 notations.

body: There is no difference between all the lines of code in your question. All representations stand for one value, containing one byte. There is only one implementation of `Serial::write()`, which has a `uint8_t` as parameter. So all the different representations result in a `uint8_t` anyway.

body:
As mentioned before they are all the same. The thing you have to rememeber is that the compiler takes the human readable code you write and turns it into the instructions the processor can understand. If you want to explore ways the compiler does thing you can compile the program into the hex file and then compare. Or for even less detail, but much easier, look at the size of the file created when you compile in the IDE
using just the one line in question inside the setup function

    write(0x0d)  ----> 1334 bytes
    write(13)    ----> 1334 bytes
    write('\r')  ----> 1334 bytes

For this simple example we can assume that all three of these are producing the exact same hex file.   There are many more complicated example of different ways to do the same task that may produce more or less efficient code, but in this case the compiler is going to produce the same instruction set to the processor.

As pointed out in the comments, I am not saying that because they are the same size they must be the same hex code. As any single byte being written would produce the same size code, but not the same result. But when comparing two methods that we know are the same functionality ( 0x0d and '\r') and they produce the same size binary, then we can assume the compiler reduced them to the same code.


body:
I'm trying to create an Arduino Uno following the circuit described in the diagram below which I'd based from [here][1].

I'd tried this circuit on an Atmega328 PDIP version (with the correct connections since the PDIP has different pinouts from this TQFP) and I was successful in creating and using my own Arduino.

However, when I've used the TQFP version and had this circuit layout and printed on a pcb, I can't burn the bootloader using an Arduino UNO.

I've double checked the pinouts from the Atmega328P datasheet and they are correct. Using a tester, I've also verified that the connections are there.

By the way, I've used the following connections.

    Arduino Digital Pin 13 to SCLK
    Arduino Digital Pin 12 to MISO
    Arduino Digital Pin 11 to MOSI
    Arduino Digital Pin 10 to RESET
    Arduino 5V to VCC
    Arduino GND to GND

I've also burned the ArduinoISP program on th Arduino UNO, selected Arduino as ISP and chosen Arduino UNO as board.

When I press 'Burn Bootloader', I'm getting this error message.

    avrdude: Device signature = 0x000000
    avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

I've looked at different forums and they are only saying to check the connections which I'd already checked that there is.

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

  [1]: https://www.arduino.cc/en/Main/Standalone
  [2]: https://i.stack.imgur.com/095Gh.png

title: Can't burn Bootloader on Atmega328P Using Arduino Uno

Answers: 3

body:
I have had this problem in the past and it has always been one of two solutions

 1. The wires __were__ misconfigured, and I only saw it after the Nth time
 2. Wrong chip, I was trying to program a 328 when it expected a 328p

And the secret third option:

 3. Some chip/wire/etc. was busted/burned/bad.

Unfortunately These were the only outcomes to ever come for me when I encountered that particular error.

body:
The design is missing 0.1uF caps on VCC, AVCC, and Aref.

Aref should not connect to 5V directly. It is connected internally thru a mux and only needs the 0.1uF to Gnd.  If Aref is direct connected and then the sketch selects the internal 1.1V reference, it can/will damage the chip.

Change the 220 ohm resistor on D13/SCK to 1K.  220 ohm puts quite a load on the SCK line for a Programmer. 1K will result in a plenty bright LED.

Do you have a 0.1uF between DTR of a Serial programmer and the Reset pin?  A Programmer needs direct control of the Reset line, a Serial programmer (such as an FTDI Basic module) needs to go thru a cap so a Reset pulse is created.

body:
[![Arduino on breadboard][1]][1]
here is a Link... https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard

If bootloader is burned with arduino uno in atmega328 then code will be uploaded for once and run correctly but next time you tried to burn code in atmega328 then code will not burn in atmega328. I also tried this way but it just work one time for me then I bought usbasp(price 1.5$) to burn bootloader permanently. after burning bootloader with usbasp then its works perfect for me.
Just connect crystall with filtering capacitor thats enough to burn bootloader. above config is just in case you want to use it as MCU.

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


body:
I made a Arduino program to control my air conditioner(model:GREE Lomo) by PC.
I download IRremote library from [here][1] for that.

    #include "IRremote.h"

    IRsend irsend;
    int irPin = 3; // pin IR led

    int khz = 38; // 38kHz carrier frequency for the NEC protocol

    const unsigned int irSignalOn[] = {8972, 4492, 644, 1664, 640, 564, 644, 564, 640, 1668, 636, 568, 640, 1664, 644, 560, 644,
                                   560, 644, 564, 640, 564, 644, 560, 644, 1664, 640, 564, 644, 564, 640, 564, 640, 1668, 640, 1664, 640, 564, 644,
                                   1664, 640, 564, 644, 564, 640, 1668, 640, 1664, 640, 564, 644, 564, 640, 564, 640, 564, 644, 564, 640, 1664, 644,
                                   560, 644, 1664, 640, 564, 644, 564, 640, 1668, 640, 560, 644, 19980, 640, 564, 644, 1664, 640, 1668, 640, 564, 640,
                                   564, 644, 1660, 644, 560, 644, 564, 644, 560, 644, 564, 640, 564, 644, 560, 644, 564, 640, 1664, 640, 564, 644, 564,
                                   640, 564, 640, 564, 644, 564, 640, 564, 644, 560, 644, 564, 640, 564, 644, 564, 640, 564, 640, 564, 644, 560, 644, 564,
                                   640, 564, 640, 564, 644, 1664, 640, 564, 644, 39972, 8976, 4496, 640, 1664, 644, 560, 644, 564, 640, 1668, 640, 564, 640,
                                   1668, 640, 564, 640, 564, 644, 560, 644, 564, 640, 564, 644, 1664, 640, 564, 644, 564, 640, 564, 644, 1664, 640, 1668, 640,
                                   564, 640, 1668, 640, 564, 640, 564, 644, 1668, 636, 1668, 640, 564, 640, 564, 640, 564, 644, 560, 644, 564, 644, 560, 644,
                                   1668, 640, 1664, 640, 564, 644, 564, 640, 1668, 640, 564, 640, 19980, 640, 564, 644, 564, 640, 564, 644, 560, 644, 564, 640,
                                   564, 644, 560, 644, 564, 640, 564, 640, 564, 644, 564, 640, 1668, 636, 568, 640, 1664, 640, 564, 640, 1672, 636, 1664, 640,
                                   564, 644, 564, 640, 564, 640, 1668, 640, 564, 640, 564, 640, 568, 640, 1664, 640, 564, 640, 564, 644, 564, 640, 1692, 616,
                                   1664, 640, 564, 640, 1664, 640, 39980, 8972, 4492, 644, 1664, 640, 568, 636, 564, 644, 1664, 640, 564, 640, 1668, 640, 564,
                                   640, 564, 644, 564, 640, 564, 640, 564, 640, 1668, 640, 564, 640, 568, 640, 560, 644, 1664, 640, 1664, 644, 564, 640, 1668,
                                   640, 564, 640, 564, 644, 1660, 644, 1664, 640, 564, 644, 560, 644, 564, 640, 564, 640, 564, 644, 1664, 640, 1664, 644, 1664,
                                   644, 560, 644, 564, 640, 1668, 640, 560, 644, 19984, 640, 564, 644, 560, 644, 564, 640, 564, 640, 564, 640, 564, 644, 564, 640,
                                   564, 644, 564, 640, 564, 640, 564, 640, 568, 640, 564, 644, 560, 644, 564, 640, 564, 644, 560, 644, 564, 640, 564, 644, 564,
                                   640, 1664, 640, 1668, 640, 564, 640, 564, 640, 564, 644, 564, 640, 568, 640, 560, 644, 1668, 640, 1664, 640, 564, 640, 564, 644
                                  };

    const unsigned int irSignalOff[] = {8996, 4496, 640, 1688, 616, 568, 636, 568, 640, 568, 636, 568, 640, 1688, 616, 568, 640, 564, 640, 564, 640, 564, 644, 564,
                                    640, 1688, 616, 1692, 616, 568, 640, 568, 636, 1668, 640, 1688, 616, 1692, 616, 568, 636, 568, 640, 564, 640, 1692, 616,
                                    568, 636, 568, 636, 568, 640, 564, 640, 568, 636, 568, 640, 1688, 616, 564, 640, 1692, 616, 568, 636, 564, 640, 1672, 636,
                                    564, 644, 19980, 640, 568, 636, 1692, 616, 1688, 616, 568, 636, 568, 640, 1688, 616, 572, 636, 564, 640, 568, 640, 564, 640,
                                    568, 636, 568, 636, 568, 640, 1688, 616, 568, 640, 564, 640, 568, 636, 564, 640, 568, 640, 564, 640, 564, 640, 568, 640, 568,
                                    636, 568, 636, 568, 640, 564, 640, 564, 640, 568, 636, 568, 640, 1688, 616, 568, 636, 1692, 616, 39980, 8972, 4496, 640, 1688,
                                    616, 568, 636, 568, 640, 568, 636, 568, 636, 1692, 616, 564, 640, 568, 640, 564, 640, 564, 640, 568, 640, 1688, 616, 1692, 612,
                                    568, 640, 564, 640, 1692, 612, 1692, 616, 1692, 616, 564, 640, 568, 640, 564, 640, 1692, 612, 568, 640, 568, 636, 568, 636, 568,
                                    640, 564, 640, 564, 640, 568, 640, 1692, 612, 1692, 616, 568, 640, 564, 640, 1688, 616, 568, 636, 19984, 640, 564, 640, 568, 640,
                                    564, 640, 568, 636, 568, 636, 568, 640, 564, 640, 568, 636, 568, 640, 564, 640, 564, 644, 1688, 616, 568, 640, 564, 640, 568, 636,
                                    568, 640, 564, 640, 568, 636, 1672, 636, 1692, 612, 568, 640, 564, 640, 568, 636, 568, 640, 1692, 612, 568, 640, 568, 636, 568, 640,
                                    564, 640, 1692, 616, 1668, 632, 568, 640, 39980, 8972, 4500, 640, 1688, 616, 568, 636, 568, 640, 564, 640, 568, 636, 1668, 640, 568,
                                    636, 568, 640, 568, 636, 564, 640, 568, 636, 1692, 616, 1688, 616, 568, 636, 568, 640, 1668, 636, 1688, 620, 1692, 612, 568, 640, 564,
                                    640, 564, 640, 1692, 612, 568, 640, 564, 644, 564, 640, 564, 640, 552, 652, 568, 640, 1688, 616, 1688, 616, 1692, 616, 564, 640, 568,
                                    640, 1664, 640, 564, 640, 19988, 636, 568, 640, 564, 640, 568, 636, 568, 640, 564, 640, 568, 636, 568, 640, 564, 640, 564, 640, 568,
                                    636, 568, 640, 568, 636, 568, 640, 568, 640, 564, 636, 568, 640, 568, 636, 568, 636, 568, 636, 568, 640, 1668, 636, 1692, 616, 568,
                                    640, 564, 640, 564, 640, 568, 636, 568, 640, 564, 640, 1692, 616, 564, 640, 568, 636, 1692, 616
                                   };

    void setup() {
      pinMode(irPin, OUTPUT);
      Serial.begin(9600);
    }

    void loop() {

      if (Serial.available() > 0) {
        char letter = Serial.read();
        if (letter == '1') {
          irsend.sendRaw(irSignalOn, sizeof(irSignalOn) / sizeof(irSignalOn[0]), khz); //Note the approach used to automatically calculate the size of the array.
          Serial.println("ON");
        } else if (letter == '0') {
          irsend.sendRaw(irSignalOff, sizeof(irSignalOff) / sizeof(irSignalOff[0]), khz); //Note the approach used to automatically calculate the size of the array.
          Serial.println("OFF");
        }
      }
    }

i got an error for arduino uno :
 Global variables use 2080 bytes (101%) of dynamic memory, leaving -32 bytes for local variables. Maximum is 2048 bytes.

how can i fix it?

EDIT 07/26:

I know with board like ATmega2560 problem will fix but I want use Arduino uno.

I tried to save my data at program memory but I don't know how to read that.

  [1]: https://github.com/z3t0/Arduino-IRremote

title: storage problem

Answers: 3

body:
A solution is to move the tables into program memory (aka PROGMEM). Use the below:

    const unsigned int irSignalOn[] PROGMEM = {
     ...
    };

And modify the call to `sendRaw()` to `sendRaw_P()`.

    irsend.sendRaw_P(irSignalOn, sizeof(irSignalOn) / sizeof(irSignalOn[0]), khz);

For more information see the library documentation.

Cheers!

body: One can also jump to a Atmega1284P based board, with it's 16K of SRAM, 8x that of a '328P's 2K and 2x that of the Mega's 8K.  Dual hardware serial ports too if your project should need one.

body:
**not an answer**

please try this

let me know if it turns on the A/C when you press `1`

 #include "IRremote.h"

 IRsend irsend;
 int irPin = 3; // pin IR led

 int khz = 38; // 38kHz carrier frequency for the NEC protocol

 void setup() {
   pinMode(irPin, OUTPUT);
   Serial.begin(9600);
 }

 void loop() {

   if (Serial.available() > 0) {
     char letter = Serial.read();
     if (letter == '1') {
          irsend.sendNEC(0x4A08D3052, 35);
          irsend.sendNEC(0x64040002,  32);
          irsend.sendNEC(0x4A08D3032, 35);
          irsend.sendNEC(0x0015888D,  32);
          irsend.sendNEC(0x4A08D3072, 35);
          irsend.sendNEC(0x00000C0C,  32);

          Serial.println("ON");
     }
   }
 }


body:
[![circuit diagram][1]][1]

When button 1 is pressed, the message should be sent to 4 members. But we are receiving the message for one member and after some delay for the other members. But receiving to all members of contacts given in the code (Here numbers are not mentioned)

    #include <LiquidCrystal.h>

    int ButtonValue1=0;
    int ButtonValue2=0;
    int ButtonValue3=0;
    int ButtonValue4=0;

    int Button1=8;
    int Button2=9;
    int Button3=10;
    int Button4=11;
    int buz=12;
    LiquidCrystal lcd(2, 3, 4, 5, 6, 7);

    void okcheck()
    {
      unsigned char rcr;
      do{
        rcr = Serial.read();
      }while(rcr != 'K');
    }

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

      pinMode(buz,OUTPUT);
      pinMode(Button1,INPUT);
      pinMode(Button2,INPUT);
      pinMode(Button3,INPUT);
      pinMode(Button4,INPUT);

      digitalWrite(12, HIGH);

      lcd.begin(16, 2);
      lcd.clear();
      lcd.print("INNOVATIVE CLG");
      lcd.setCursor(0, 1);
      lcd.print("BUS INFO SYSTEM");

      delay(1000);
    }

    void loop()
    {
      ButtonValue1=digitalRead(Button1);
      ButtonValue2=digitalRead(Button2);
      ButtonValue3=digitalRead(Button3);
      ButtonValue4=digitalRead(Button4);

      if(ButtonValue1!=0)
      {
        lcd.clear();
        lcd.print("BUS STARTED...");
        Serial.write("AT\r\n");         okcheck();
        Serial.write("ATE0\r\n");         okcheck();
        Serial.write("AT+CMGF=1\r\n");         okcheck();
        Serial.write("AT+CNMI=1,2,0,0\r\n");         okcheck();
        Serial.write("AT+CSMP=17,167,0,0\r\n");         okcheck();
        Serial.write("AT+CMGS=\"+91...........\"\r");
        delay(100);
        Serial.write("GUD MNG.. BUS STARTED FROM STARTING POINT\r");
        delay(100);
        Serial.write(0x1A);
        delay(1000);delay(1000);
        Serial.write("AT+CMGS=\"+91...........\"\r");
        delay(100);
        Serial.write("GUD MNG.. BUS STARTED STARTING POINT\r");
        delay(100);
        Serial.write(0x1A);
        delay(1000);delay(1000);
        Serial.write("AT+CMGS=\"+91...........\"\r");
        delay(100);
        Serial.write("GUD MNG.. BUS STARTED STARTING POINT\r");
        delay(100);
        Serial.write(0x1A);
        delay(1000);delay(1000);
        Serial.write("AT+CMGS=\"+91...........\"\r");
        delay(100);
        Serial.write("GUD MNG.. BUS STARTED STARTING POINT\r");
        delay(100);
        Serial.write(0x1A);
        delay(1000);delay(1000);
      }
      if(ButtonValue2!=0)
      {
        lcd.clear();
        lcd.print("BUS IS @ 1st stage");
        Serial.write("AT\r\n");         okcheck();
        Serial.write("ATE0\r\n");         okcheck();
        Serial.write("AT+CMGF=1\r\n");         okcheck();
        Serial.write("AT+CNMI=1,2,0,0\r\n");         okcheck();
        Serial.write("AT+CSMP=17,167,0,0\r\n");         okcheck();
        Serial.write("AT+CMGS=\"+91...........\"\r");
        delay(1000);
        Serial.write("BUS IS @ 1st stage\r");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);delay(1000);
        Serial.write("AT+CMGS=\"+91...........\"\r");
        delay(1000);
        Serial.write("BUS IS @ 1st stage\r");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);delay(1000);
        Serial.write("AT+CMGS=\"+91...........\"\r");
        delay(1000);
        Serial.write("BUS IS @ 1st stage\r");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);delay(1000);
      }
      if(ButtonValue3!=0)
      {
        lcd.clear();
        lcd.print("BUS IS @ 2nd stage");
        Serial.write("AT\r\n");         okcheck();
        Serial.write("ATE0\r\n");         okcheck();
        Serial.write("AT+CMGF=1\r\n");         okcheck();
        Serial.write("AT+CNMI=1,2,0,0\r\n");         okcheck();
        Serial.write("AT+CSMP=17,167,0,0\r\n");         okcheck();
        Serial.write("AT+CMGS=\"+91...........\"\r");
        delay(1000);
        Serial.write("BUS IS @ 2nd stage\r");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);delay(1000);
        Serial.write("AT+CMGS=\"+91...........\"\r");
        delay(1000);
        Serial.write("BUS IS @ 2nd stage\r");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);delay(1000);
      }
      if(ButtonValue4!=0)
      {
        lcd.clear();
        lcd.print("BUS IS @ COLLEGE");
        digitalWrite(buz,LOW);
        delay(1000);
        digitalWrite(buz,HIGH);
      }
    }

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

title: need help in code to send sms to multiple contacts using arduino, gsm800, push button

Answers: 1

body:
You need to refactor you code, It has become just too complicated for this kind of straight linear code! Your code must be organized better, Don't Repeat Yourself ([DRY][1]); just by doing this you may find your error(s).

First lets fix your variables:

    #include <LiquidCrystal.h>
    #define NUMBUTTS 4
    int ButtonValues[NUMBUTTS]= {0,0,0,0};
    int Buttons[NUMBUTTS]= {8,9,10,11};
    int buz=12;
    LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
and add some new ones

    String numbers[NUMBUTTS] =
    {
        "+91234567890",
        "+91234567890",
        "+91234567890",
        "+91234567890",
    }

    String msgs[NUMBUTTS-1] =
    {
       "GUD MNG.. BUS STARTED FROM STARTING POINT\r",
       "BUS IS @ 1st stage\r",
       "BUS IS @ 2nd stage\r",
    }
next lets clean up your function:

    void okcheck()
    {
        unsigned char rcr = 0;
        while(rcr != 'K') // rcr can't be 'K' when it starts as 0
            rcr = Serial.read();
    }
Setup needs to be changed now that we changed your vars:

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

        pinMode(buz,OUTPUT);
        digitalWrite(buz, HIGH);

        for(int i=0; i<NUMBUTTS; i++)
            pinMode(Buttons[i],INPUT);

        lcd.begin(16, 2);
        lcd.clear();
        lcd.print("INNOVATIVE CLG");
        lcd.setCursor(0, 1);
        lcd.print("BUS INFO SYSTEM");

        delay(1000);
    }
now we need to extract duplicated code and put it in a function:

    // common starting code.
    void preamble()
    {
        Serial.write("AT\r\n");
        okcheck();

        Serial.write("ATE0\r\n");
        okcheck();

        Serial.write("AT+CMGF=1\r\n");
        okcheck();

        Serial.write("AT+CNMI=1,2,0,0\r\n");
        okcheck();

        Serial.write("AT+CSMP=17,167,0,0\r\n");
        okcheck();
    }

    // common message code
    void send_sms(String& msg)
    {
        String prefix = "AT+CMGS=\"";
        preamble();

        for(int i=0;i<NUMBUTTS;i++)
        {
            Serial.write(prefix+numbers[i]+"\"\r");
            delay(100);

            Serial.write(msg);
            delay(100);

            Serial.write(0x1A);
            delay(2000)
        }
    }
now we need to fix up loop():

    void loop()
    {
        for(int i=0; i<NUMBUTTS; i++)
        {
            ButtonValues[i]=digitalRead(Buttons[i]);
        }

        for(int i=0; i<NUMBUTTS-1; i++)
        {
            if(ButtonValues[i]!=0)
            {
                lcd.clear();
                lcd.print(msgs[i]);
                send_sms(msgs[i]);
            }
        }

        //special case for button4
        if(ButtonValue[3]!=0)
        {
             lcd.clear();
             lcd.print("BUS IS @ COLLEGE");
             digitalWrite(buz,LOW);
             delay(1000);
             digitalWrite(buz,HIGH);
        }
    }

Now your program logic is separate from the code that sends the messages, and you can test each in isolation from each other. You can test that send_sms() actually sends SMSs. Then you can see if your logic does what you think it does; by either replacing send_sms() with a test stub, or just by inspection.

With clean code it should be easier to spot your problem. The code looks like it should work, so I would guess that the modem itself may be causing the delays, maybe it takes a while to send a message and you are queuing them up and it takes a few seconds to get through each one, its possible that not all get send because one or more gets dropped while it is busy sending another. Hard to know without looking at the documentation for your module.

Your diagram looks like it is hooked up wrong, you have TX-> RX, but MOSI -> TX; Serial.read() reads from RX not MOSI, so i don't know how checkok() doesn't just loop forever, since you left the arduino RX floating.

  [1]: https://en.wikipedia.org/wiki/Don't_repeat_yourself


body:
How do I use 4 input lines as a [binary decoder][1]? I would like to read the 4 inputs (16 variations) and based on that choose one of 16 output behaviors?

I need to be able to set my “Ten Moon Phase Indicator” (MPI ECP) circuit project to the phase of the Moon as seen in the sky on this day, or to a specific time as indicated in one of the many apps available on the Internet. Currently the MPI ECP resets to the start of the Full Moon loop, as it is the only loop available. (this code works) NOTE: Due to the circuit & Arduino processor power consumption for this application, a eternal power will be necessary.

To resolve this problem my intent is to use four of the available 14 I\O on the Arduino Uno as INPUT's employing four debounced toggle switches (with pull up resistors): (0) Off, (1) as On. The other ten available I/O's to be used for the ten Moon display OUTPUT LED's or to control ten relays.

What I would like the sketch program to accomplish:

1. `digitalRead` pins `0`, `1`, `12`, `13`
2. Depending on 1 of 16 resulting four on/off combinations that are possible, run a specific loop.

This is what I came up with: (note, the code does not compile, I'm new)

     void setup()  {
     pinMode(2, OUTPUT);   // New     Waxing:
     pinMode(3, OUTPUT);   // Young  Waxing:
     pinMode(4,OUTPUT);   // Crescent Waxing:
     pinMode(5, OUTPUT);   // Quarter Waxing:
     pinMode(6, OUTPUT);   // Gibbous Waxing:
     pinMode(7,OUTPUT);   // Full Moon:
     pinMode(8, OUTPUT);   // Gibbous Wanning:
     pinMode(9, OUTPUT);   // Quarter Wanning:
     pinMode(10, OUTPUT);  // Crescent Wanning:
     pinMode(11, OUTPUT);  // Old Wanning:
     pinMode(13, INPUT);  // Switch 4
     pinMode(12,INPUT);     // Switch 3
     pinMode(1, INPUT);     // Switch 2
     pinMode(0,INPUT);      // Switch 1

     } void loop() {
     int Reading = digitalRead;
    Reading = digitalRead (12); Reading = digitalRead (13);
    Reading = digitalRead (1);   Reading = digitalRead (0);

     if  (digitalRead(0) == HIGH; digitalRead (1)==
       HIGH; digitalRead(12) == HIGH; (digitalRead(13) == HIGH);  { } else
        {   // loop Full Moon Start   digitalWrite(7, HIGH);  // FULL MOON ON
      delay(5000);
      digitalWrite(7, LOW);    // FULL MOON OFF
            delay(10);
       digitalWrite(8,HIGH);   // WAN GIBBOUS MOON ON
            delay(5000);
     digitalWrite(8, LOW);    // WAN GIBBOUS MOON OFF
              delay(10);
      digitalWrite(9, HIGH);   // 3RD QUARTER MOON ON
              delay(5000);
       digitalWrite(9, LOW);     // 3RD QUARTER MOON OFF
              delay(10);
      digitalWrite(10, HIGH);    // WAN CRESENT MOON ON
             delay(5000);
      digitalWrite(10, LOW);     // WAN CRESENT MOON OFF
              delay(10);
      digitalWrite(11, HIGH);     // OLD MOON ON
             delay(5000);
     digitalWrite(11, LOW);      // OLD MOON OFF
              delay(5000);
       digitalWrite(2, HIGH);  // NEW MOON ON
              delay(5000);
      digitalWrite(2, LOW);   // NEW MOON OFF
              delay(10);
     digitalWrite(3, HIGH);  // YOUNG MOON ON
              delay(5000);
       digitalWrite(3, LOW);  // YOUNG MOON OFF
              delay(100);
     digitalWrite(4, HIGH);   // WAX CRESCENT MOON ON
             delay(5000);
       digitalWrite(4, LOW);    // WAX CRESCENT MOON OFF
              delay(10);
      digitalWrite(5, HIGH);   // FIRST QUARTER ON
              delay(5000);
       digitalWrite(5, LOW);     // FIRST CRESCENT OFF
              delay(10);
     digitalWrite(6, HIGH);   // WAX GIBBOUS ON
             delay(5000);
      digitalWrite(6, LOW);    // WAX GIBBOUS OFF
              delay(10);

    // loop for New moon Reset   if  (digitalRead(0) == LOW;digitalRead (1)==LOW; digitalRead(12) == LOW;(digitalRead(13) ==
        LOW);
      { } else   // loop New Moon Start
     digitalWrite(2, HIGH);  // NEW MOON ON
              delay(5000);
       digitalWrite(2, LOW);   // NEW MOON OFF
              delay(10);
       digitalWrite(3, HIGH);  // YOUNG MOON ON
              delay(5000);
       digitalWrite(3, LOW);    // YOUNG MOON OFF
              delay(100);
       digitalWrite(4, HIGH);   // WAX CRESCENT MOON ON
             delay(5000);
       digitalWrite(4, LOW);    // WAX CRESCENT MOON OFF
              delay(10);
       digitalWrite(5, HIGH);   // FIRST QUARTER ON
              delay(5000);
      digitalWrite(5, LOW);     // FIRST CRESCENT OFF
              delay(10);
      digitalWrite(6, HIGH);   // WAX GIBBOUS ON
             delay(5000);
       digitalWrite(6, LOW);    // WAX GIBBOUS OFF
              delay(10);
      digitalWrite(7, HIGH);  // FULL MOON ON
            delay(5000);
       digitalWrite(7, LOW);    // FULL MOON OFF
            delay(10);
       digitalWrite(8,HIGH);   // WAN GIBBOUS MOON ON
            delay(5000);
       digitalWrite(8, LOW);    // WAN GIBBOUS MOON OFF
              delay(10);
       digitalWrite(9, HIGH);   // 3RD QUARTER MOON ON
              delay(5000);
       digitalWrite(9, LOW);     // 3RD QUARTER MOON OFF
              delay(10);
      digitalWrite(10, HIGH);    // WAN CRESENT MOON ON
             delay(5000);
       digitalWrite(10, LOW);     // WAN CRESENT MOON OFF
              delay(10);
      digitalWrite(11, HIGH);     // OLD MOON ON
             delay(5000);
       digitalWrite(11, LOW);      // OLD MOON OFF
              delay(5000);
     { } else  { // Young moon Reset Start
     if  (digitalRead(0) == LOW; digitalRead (1)==LOW; digitalRead(12) ==
        LOW;(digitalRead(13) == HIGH;
     )
       { } else  // loop New Moon Start
             digitalWrite(3, HIGH);
      // YOUNG MOON ON
              delay(5000);
       digitalWrite(3, LOW);    // YOUNG MOON OFF
              delay(100);
      digitalWrite(4, HIGH);   // WAX CRESCENT MOON ON
             delay(5000);
      digitalWrite(4, LOW);    // WAX CRESCENT MOON OFF
              delay(10);
       digitalWrite(5, HIGH);   // FIRST QUARTER ON
              delay(5000);
      digitalWrite(5, LOW);     // FIRST CRESCENT OFF
              delay(10);
      digitalWrite(6, HIGH);   // WAX GIBBOUS ON
             delay(5000);
      digitalWrite(6, LOW);    // WAX GIBBOUS OFF
              delay(10);
     digitalWrite(7, HIGH);    // FULL MOON ON
            delay(5000);
       digitalWrite(7, LOW);    // FULL MOON OFF
            delay(10);
       digitalWrite(8,HIGH);   // WAN GIBBOUS MOON ON
            delay(5000);
      digitalWrite(8, LOW);    // WAN GIBBOUS MOON OFF
              delay(10);
      digitalWrite(9, HIGH);   // 3RD QUARTER MOON ON
              delay(5000);
     digitalWrite(9, LOW);     // 3RD QUARTER MOON OFF
              delay(10);
      digitalWrite(10, HIGH);    // WAN CRESENT MOON ON
             delay(5000);
       digitalWrite(10, LOW);     // WAN CRESENT MOON OFF
              delay(10);
      digitalWrite(11, HIGH);     // OLD MOON ON
             delay(5000);
      digitalWrite(11, LOW);      // OLD MOON OFF
              delay(5000);
             digitalWrite(2, HIGH);   // NEW MOON ON
              delay(5000);
       digitalWrite(2, LOW);       // NEW MOON OFF
              delay(10);
      }
     // Waxing Crescent Reset Start if  (digitalRead(0) == LOW; digitalRead (1)== LOW; digitalRead(12) ==
        HIGH; digitalRead(13) == HIGH;)    { } else  // Waxing Crescent Moon
        reset Start
      digitalWrite(4, HIGH);   // WAX CRESCENT MOON ON
             delay(5000);
       digitalWrite(4, LOW);    // WAX CRESCENT MOON OFF
              delay(10);
     digitalWrite(5, HIGH);   // FIRST QUARTER ON
              delay(5000);
       digitalWrite(5, LOW);     // FIRST CRESCENT OFF
              delay(10);
       digitalWrite(6, HIGH);   // WAX GIBBOUS ON
             delay(5000);
      digitalWrite(6, LOW);    // WAX GIBBOUS OFF
              delay(10);
      digitalWrite(7, HIGH);    // FULL MOON ON
            delay(5000);
       digitalWrite(7, LOW);    // FULL MOON OFF
            delay(10);
      digitalWrite(8,HIGH);   // WAN GIBBOUS MOON ON
            delay(5000);
       digitalWrite(8, LOW);    // WAN GIBBOUS MOON OFF
              delay(10);
      digitalWrite(9, HIGH);   // 3RD QUARTER MOON ON
              delay(5000);
       digitalWrite(9, LOW);     // 3RD QUARTER MOON OFF
              delay(10);
     digitalWrite(10, HIGH);    // WAN CRESENT MOON ON
             delay(5000);
       digitalWrite(10, LOW);     // WAN CRESENT MOON OFF
              delay(10);
      digitalWrite(11, HIGH);     // OLD MOON ON
             delay(5000);   digitalWrite(11, LOW);      // OLD MOON OFF
             delay(5000);
       digitalWrite(2, HIGH);   // NEW MOON ON
              delay(5000);
       digitalWrite(2, LOW);      // NEW MOON OFF
              delay(10);
       digitalWrite(3, HIGH);  // YOUNG MOON ON
              delay(5000);
       digitalWrite(3, LOW);       // YOUNG MOON OFF
              delay(100);
      }
      // First Quarter Moon Reset if  (digitalRead(0) == LOW; digitalRead(1) == HIGH; digitalRead(12) ==
        HIGH; digitalRead(13) == HIGH;)   { else  {
      //FIRST QUARTER  Moon
        reset Start
    digitalWrite(5, HIGH);   // FIRST QUARTER ON
              delay(5000);
       digitalWrite(5, LOW);     // FIRST CRESCENT OFF
              delay(10);
       digitalWrite(6, HIGH);   // WAX GIBBOUS ON
             delay(5000);
      digitalWrite(6, LOW);    // WAX GIBBOUS OFF
              delay(10);
      digitalWrite(7, HIGH);  // FULL MOON ON
            delay(5000);
       digitalWrite(7, LOW);    // FULL MOON OFF
            delay(10);
       digitalWrite(8,HIGH);   // WAN GIBBOUS MOON ON
            delay(5000);
      digitalWrite(8, LOW);    // WAN GIBBOUS MOON OFF
              delay(10);
      digitalWrite(9, HIGH);   // 3RD QUARTER MOON ON
              delay(5000);
       digitalWrite(9, LOW);     // 3RD QUARTER MOON OFF
              delay(10);
      digitalWrite(10, HIGH);    // WAN CRESENT MOON ON
             delay(5000);
       digitalWrite(10, LOW);     // WAN CRESENT MOON OFF
              delay(10);
      digitalWrite(11, HIGH);     // OLD MOON ON
             delay(5000);
      digitalWrite(11, LOW);      // OLD MOON OFF
              delay(5000);
      digitalWrite(2, HIGH);   // NEW MOON ON
              delay(5000);
      digitalWrite(2, LOW);    // NEW MOON OFF
              delay(10);
       digitalWrite(3, HIGH);  // YOUNG MOON ON
              delay(5000);
       digitalWrite(3, LOW);    // YOUNG MOON OFF
              delay(100);
       digitalWrite(4, HIGH);   // WAX CRESCENT MOON ON
             delay(5000);
      digitalWrite(4, LOW);        // WAX CRESCENT MOON OFF
              delay(10);
     }
    // code would continue with other loops. Thanks for looking at  my 16 RESET problem, email me. Any suggestions would be appreciated

  [1]: https://en.wikipedia.org/wiki/Binary_decoder

title: How do I use 4 inputs on the Arduino as a binary decoder?

Answers: 3

body:
Note that A0 to A5 are available as for `digitalRead()` also. I normally initialize them as

    byte pin14 = 14; // make the name mean something to you

    pinMode (pin14, INPUT_PULLUP);

    Then you can read it as

    if (digitalRead(pin14) == LOW){

    // pin is connected to Gnd

    }

Or if you use D14-17 for your 4 inputs, you can read all 4 with a PORT read, and act on that (you still use `pinMode()` to initialize them):

    byte addressByte = PORTC & 0x0F; // result is 0 to 15 based on state of the 4 pins

(I think PORTC is A0 to A5, might want to check that)

then read them and act accordingly. Way cleaner than a while bunch of `digitalRead()s` and `if()` statements.

    switch(addressByte){

    case 0:

    // whatever happens

    :

    :

    case 15:

    // whatever happens
    }

body:
a skeleton solution:

    int in[] = {0,1,12,13};
    int out[] = {2,3,4,5,6,7,8,9,10,11};
    ...
    void setup()
    {
        for(int i=0; i < 4; i++)
            pinMode(in[i], INPUT)

        for(int i=0; i < 10; i++)
            pinMode(out[i], OUTPUT)
    }
    ...
    void do0 {...};
    void do1 {...};
    void do2 {...};
    void do3 {...};
    void do4 {...};
    void do5 {...};
    void do6 {...};
    void do7 {...};
    void do8 {...};
    void do9 {...};
    void do10 {...};
    void do11 {...};
    void do12 {...};
    void do13 {...};
    void do14 {...};
    void do15 {...};
    ...
    void loop()
    {
        int addr = 0;
        for(int i=0; i<4; i++)
           addr |= digitalRead(in[i]) << i;

        switch(addr)
        {
        case 0:
           do0();
           break;
        case 1:
           do1();
           break;
        case 2:
           do2();
           break;
        case 3:
           do3();
           break;
        case 4:
           do4();
           break;
        case 5:
           do5();
           break;
        case 6:
           do6();
           break;
        case 7:
           do7();
           break;
        case 8:
           do8();
           break;
        case 9:
           do9();
           break;
        case 10:
           do10();
           break;
        case 11:
           do11();
           break;
        case 12:
           do12();
           break;
        case 13:
           do13();
           break;
        case 14:
           do14();
           break;
        case 15:
           do15();
           break;
        }
    }

body:
This may be a little too advanced for the OP but... reading esoterik’s
answer, I couldn't help the urge to transform that big switch/case into
an array lookup. Admittedly, the syntax for declaring the array of
function pointers is a little bit esoteric. ;-)

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

    void loop()
    {
        // List of implemented behaviors.
        static void (* const behaviors[])() = {
            do0, do1, do2,  do3,  do4,  do5,  do6,  do7,
            do8, do9, do10, do11, do12, do13, do14, do15
        };

        // Build the index of the requested behavior.
        int addr = 0;
        for (int i = 0; i < 4; i++)
           addr |= digitalRead(in[i]) << i;

        // Now do it.
        behaviors[addr]();
    }

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

**Edit**: To address the OP's issue. I may have missed something, but it
looks to me like all the cases do the exact same thing: loop through the
outputs, turn each one on, wait 5 seconds, then turn it off. The only
difference between the cases is the index of the output that is turned
on first. In this case, all this repetitive code can be factored into a
single loop as follows:

    // Turn on then off all the outputs in turn,
    // starting from the given index.
    void loop_outputs(int start_index)
    {
        int index = start_index;
        for (int count = 0; count < 10; count++) {

            // Light up that LED for 5 s.
            digitalWrite(out[index], HIGH);
            delay(5000);
            digitalWrite(out[index], LOW);
            delay(10);

            // Go to the next one, wrapping index 10 -> 0.
            if (++index == 10) index = 0;
        }
    }


body:
I have the following piece of code which opens a Bitmap from the SD card and outputs the width to the serial monitor.

    #include <SPI.h>
    #include <SD.h>

    File bitmap;

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

      Serial.println("Initializing SD card...");
      if (!SD.begin(4)) {
        Serial.println("initialization failed!");
        while (1);
      }
      Serial.println("initialization done.");

      bitmap = SD.open("/TEST2.BMP");

      int width[0]; // why can't I just write "int width;"
      bitmap.seek(18);
      bitmap.read(width, 4);
      Serial.println(width[0]); // and "Serial.println(width);"
    }

    void loop() {

    }

It works perfectly fine but I don't understand why I have to declare the buffer for the width as `int width[0];`. I tried `int width;` but then the output is just 0.

title: Reading bytes from a file on SD Card - Understanding Buffer

Answers: 2

body:
You don't *have* to, it's just one way of doing it.

Basically the `read` function needs a pointer to a buffer to store the data in.  By using an array with one entry you get a pointer to a buffer that is big enough for one (32-bit) integer. And you then get an "easy" way of accessing that one integer within that buffer.

Another way would be to just use a simple integer and pass a pointer to that integer to `read`:

    uint32_t width; // Use a fixed size integer for portability
    bitmap.seek(18);
    bitmap.read(&width, sizeof(width)); // Use sizeof for portability
    Serial.println(width);

body:
I think I have a bit of insight:

An array *is* a pointer. Thus,

int arr[0];

is equivalent of

int * simple;

So. read(arr...  or read(&simple...


body:
I have an Arduino UNO that is connected to an ADXL345. The problem is I need to collect data at 50Hz at least. The ADXL345 according to its Data sheet can go up to 3200Hz without any problem. I am using the [Adafruit][1] library using I2C interface but the accelerometer does not go above 10-12Hz as reported by the `getDataRate()` function of Adafruit library.

Im trying to set the data rate like this:

    accel.setDataRate(ADXL345_DATARATE_100_HZ);

The strange thing is that the data rate is depended more upon increasing the baud rate at the beginning of my setup function. If I set this to 38400 I get around 90-92 readings every second. I have setup my code in a way that every measurement from the accelerometer is recorded with the timestamp down to seconds. This is a snapshot of the output from the serial monitor.

    Data Rate:    9 Hz
    ------------------------------------
    Sensor:       ADXL345
    Driver Ver:   1
    Unique ID:    12345
    Max Value:    -156.91 m/s^2
    Min Value:    156.91 m/s^2
    Resolution:   0.04 m/s^2
    ------------------------------------

    Range:         +/- 8  g

    84.00,18:40:4,15/7/2018,0.59,9.14,2.82
    85.00,18:40:4,15/7/2018,0.59,9.14,2.86
    86.00,18:40:4,15/7/2018,0.63,9.10,2.86
    87.00,18:40:4,15/7/2018,0.55,9.10,2.82
    88.00,18:40:4,15/7/2018,0.55,9.10,2.82
    89.00,18:40:4,15/7/2018,0.59,9.10,2.82
    90.00,18:40:4,15/7/2018,0.59,9.10,2.82
    91.00,18:40:4,15/7/2018,0.55,9.10,2.86
    92.00,18:40:4,15/7/2018,0.55,9.10,2.86
    93.00,18:40:4,15/7/2018,0.63,9.10,2.90
    94.00,18:40:4,15/7/2018,0.63,9.10,2.90
    95.00,18:40:4,15/7/2018,0.63,9.06,2.82
    96.00,18:40:4,15/7/2018,0.63,9.06,2.82
    97.00,18:40:4,15/7/2018,0.59,9.06,2.82
    98.00,18:40:4,15/7/2018,0.59,9.06,2.82
    99.00,18:40:4,15/7/2018,0.59,9.10,2.82

Is it a problem with the code, or the adxl345?

  [1]: https://github.com/adafruit/Adafruit_ADXL345
  [2]: https://github.com/sparkfun/SparkFun_ADXL345_Arduino_Library

title: ADXL345 Data Rate seems to depend more upon Baud rate than the actual Data Rate that I set

Answers: 1

body:
You do know that sending data through serial takes time, don't you?

You are sending 41 bytes per reading. The serial port has a 64 byte buffer. By the second reading the buffer is full and all printing blocks until there is room in the buffer.

At 38400 baud that's sending 3840 bytes per second. With 41 bytes per reading that's 93.66 readings per second (not including the time taken to do the actual reading) that you can squeeze down the serial port.

Either run at a faster speed, or reduce the quantity of data you're sending per reading - or do both.


body:
I have two Arduino Unos (One clone, one genuine) and I'm trying to make a remote and a base station. Got everything working flawlessly, (Using RF24 library) and the last piece of the wiring was to get the remote Arduino off the USB and powered by battery. I have a 4 AA battery holder which I put 4 brand new alkaline batteries in. Soldered up some connectors, plugged it in and...nothing?

Ran [the demos everyone seems to use](https://forum.arduino.cc/index.php?topic=421081.msg3653559#msg3653559). Nothing again. Ran the "diagnostic script at the end of that thread...results seemed fine...

    CheckConnection Starting

    FIRST WITH THE DEFAULT ADDRESSES after power on
      Note that RF24 does NOT reset when Arduino resets - only when power is removed
      If the numbers are mostly 0x00 or 0xff it means that the Arduino is not
         communicating with the nRF24

    STATUS   = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
    RX_ADDR_P0-1  = 0xe7e7e7e7e7 0xc2c2c2c2c2
    RX_ADDR_P2-5  = 0xc3 0xc4 0xc5 0xc6
    TX_ADDR   = 0xe7e7e7e7e7
    RX_PW_P0-6  = 0x00 0x00 0x00 0x00 0x00 0x00
    EN_AA   = 0x3f
    EN_RXADDR  = 0x03
    RF_CH   = 0x4c
    RF_SETUP  = 0x07
    CONFIG   = 0x0e
    DYNPD/FEATURE  = 0x00 0x00
    Data Rate  = 1MBPS
    Model   = nRF24L01+
    CRC Length  = 16 bits
    PA Power  = PA_MAX

    AND NOW WITH ADDRESS AAAxR  0x41 41 41 78 52   ON P1
     and 250KBPS data rate

    STATUS   = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
    RX_ADDR_P0-1  = 0xe7e7e7e7e7 0x4141417852
    RX_ADDR_P2-5  = 0xc3 0xc4 0xc5 0xc6
    TX_ADDR   = 0xe7e7e7e7e7
    RX_PW_P0-6  = 0x00 0x20 0x00 0x00 0x00 0x00
    EN_AA   = 0x3f
    EN_RXADDR  = 0x03
    RF_CH   = 0x4c
    RF_SETUP  = 0x27
    CONFIG   = 0x0e
    DYNPD/FEATURE  = 0x00 0x00
    Data Rate  = 250KBPS
    Model   = nRF24L01+
    CRC Length  = 16 bits
    PA Power  = PA_MAX

Ran test on the working arduino, and got a similar result. Checked continuity on all pins twice. Can't think of what could have suddenly gone wrong? Definitely didn't change my code, but just to be sure tried the examples from the above thread...

The only thing I did different was supplying power from VIN at 6.5 V (Measured with multimeter). Should be well within range for the linear voltage regulator? Definitely correct polarity. Hooked in a servo and wrote a quick sketch to drive it then powered the PWM from the battery powered arduino. Other function from my code (rotary encoder, OLED, etc) all seem to be functioning perfectly.

Fried module?

**EDIT**

I was powering the module through the 3.3V regulated output pin on the Arduino.

Noticed with the battery plugged in whenever I check the voltage with my meter 3.3 pin bounces to 3.7 then settles to 3.3. Not sure if that's the meter, or just the regulator catching up to the (what should be very low with a multimeter) load. Same behavior occurs with USB.

title: nrf24l01 fried when supplying 6.5V to VIN?

Answers: 3

body:
If I remember correctly (IIRC) The nrf24l01 module:

 - runs on 3.3 Volts
 - doesn't have a voltage regulator

It could be fried, try supplying a regulated 3v3 supply and see if it works then.

body:
As per the datasheet nrf24L01 runs for voltages below 3.6V ~ 1.1V.
Also soldering a capacitor between the Vcc and Gnd of an nrf24L01 module would help you to in connection issues.
Please see this video for further assistance on working:
[A network of nrf24L01 ][1]

  [1]: https://www.youtube.com/watch?v=wgCyn3z8Ce8&t=157s

body:
The 3.3V regulator on the Arduino is only good for 150mA. On the clone, who knows.
If you're seeing 3.3V, the regulator may be capable. The nrf24L01 draws more current when transmitting, so it's possible it looks good at time and fails at other times.


body:
I'm not able to upload a sketch to this board with the Arduino IDE. This is the error during upload:

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

    Arduino: 1.8.5 (Windows 10), Board: "WEMOS LOLIN32, 80MHz, Default, 512000

    Build options changed, rebuilding all
    Archiving built core (caching) in: C:\Users\Karanbir\AppData\Local\Temp\arduino_cache_223140\core\core_espressif_esp32_lolin32_FlashFreq_80,PartitionScheme_default,UploadSpeed_512000_6da8d55d0c53c0ebef21ae478b9e06ba.a
    Sketch uses 178072 bytes (13%) of program storage space. Maximum is 1310720 bytes.
    Global variables use 13880 bytes (4%) of dynamic memory, leaving 313800 bytes for local variables. Maximum is 327680 bytes.
    C:\Users\Karanbir\Documents\Arduino\hardware\espressif\esp32/tools/esptool/esptool.exe --chip esp32 --port COM3 --baud 512000 --before default_reset --after hard_reset write_flash -z --flash_mode dio --flash_freq 80m --flash_size detect 0xe000 C:\Users\Karanbir\Documents\Arduino\hardware\espressif\esp32/tools/partitions/boot_app0.bin 0x1000 C:\Users\Karanbir\Documents\Arduino\hardware\espressif\esp32/tools/sdk/bin/bootloader_dio_80m.bin 0x10000 C:\Users\Karanbir\AppData\Local\Temp\arduino_build_547051/Test.ino.bin 0x8000 C:\Users\Karanbir\AppData\Local\Temp\arduino_build_547051/Test.ino.partitions.bin
    esptool.py v2.3.1
    Traceback (most recent call last):
      File "esptool.py", line 2637, in <module>
      File "esptool.py", line 2630, in _main
      File "esptool.py", line 2355, in main
      File "esptool.py", line 193, in __init__
      File "site-packages\serial\__init__.py", line 88, in serial_for_url
      File "site-packages\serial\serialwin32.py", line 62, in open
    serial.serialutil.SerialException: could not open port 'COM3': WindowsError(5, 'Access is denied.')
    Failed to execute script esptool
    the selected serial port Failed to execute script esptool
     does not exist or your board is not connected

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

This is displayed on the Arduino IDE's Serial Monitor on pressing the reboot button on the board:

    ets Jun  8 2016 00:22:57

    rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
    configsip: 0, SPIWP:0xee
    clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
    mode:DIO, clock div:2
    load:0x3fff0018,len:4
    load:0x3fff001c,len:4436
    load:0x40078000,len:0
    load:0x40078000,len:11816
    entry 0x4007a9fc
    [0;32mI (358) cpu_start: Pro cpu up.[0m
    [0;32mI (358) cpu_start: Single core mode[0m
    [0;32mI (359) heap_init: Initializing. RAM available for dynamic allocation:[0m
    [0;32mI (362) heap_init: At 3FFAE6E0 len 00001920 (6 KiB): DRAM[0m
    [0;32mI (368) heap_init: At 3FFC4E70 len 0001B190 (108 KiB): DRAM[0m
    [0;32mI (374) heap_init: At 3FFE0440 len 00003BC0 (14 KiB): D/IRAM[0m
    [0;32mI (380) heap_init: At 3FFE4350 len 0001BCB0 (111 KiB): D/IRAM[0m
    [0;32mI (387) heap_init: At 4008DE34 len 000121CC (72 KiB): IRAM[0m
    [0;32mI (393) cpu_start: Pro cpu start user code[0m
    [0;32mI (187) cpu_start: Starting scheduler on PRO CPU.[0m
    OSError: [Errno 2] ENOENT
    MicroPython v1.9.3-564-g9254f365 on 2018-04-26; ESP32 module with ESP32
    Type "help()" for more information.
    >>>

What can be wrong or needs correction?

title: Unable to upload to ESP32 LOLIN D32 board

Answers: 1

body:
I had the same problems with a USB cable of a length at 30cm

I took an other (10cm) and reduced the upload speed to 512000.

now it works


body:
I'm using an Arduino Uno to power some rgb LEDs.

Each LED takes 20mA (on average).
I have a strand of 400 LEDs.
This should be drawing ~8,000mA.

Arduino Uno has a limit on its 5v pin of 500mA.

**So how many amps is my Arduino outputting? My 8A worth of LEDs are illuminated, just dimly.

**Edit:**
My Arduino still runs, and the 8,000mA LEDs illuminate, just dimly. I’ve left the setup on for 12 hours, and it all still works.

So it appears the behavior of the Arduino Uno is to limit the amp output of its 5v pin. It does not burn out.

Any explanations for this observed behavior?

**Edit 2:**
I know how to wire up this setup correctly using power injection. I’m just curious why my Arduino is not burning out as we all expect it to.

title: What happens when I exceed amp limit on Arduino 5v pin?

Answers: 2

body:
If you exceed the amp limit, that can be drawn through (!) the Arduino, some components on the Arduino will be fried (As for most electronic devices. For the Arduino this is practically a short). There is no current limitation there. Which components are fried depends on how you provide the power. If you provide power through the power jack or VIN, the voltage regulator will burn out. If you provide power through USB a diode or the MOSFET will be fried (You can look this up in the Arduino UNOs schematic at [this site][1]).

The setup might output a current, that is a bit higher than 500mA, for a short time. But the mentioned components, that are in the currents path, will heat up very quickly and be destroyed. In this short time the LEDs will be very dim, since the Arduino cannot provide a current as big as 8A, not even for a short time.

All great loads have to be powered separately from the Arduino, so that their supply current will not flow through the Arduino. If you are using a powerful USB supply, you have to split the power lines, before giving the voltage to the Arduino. You can connect the USBs 5V pin to the 5V pin of the Arduino and to the LEDs. If you are using a power supply with a higher voltage than possible for your LEDs, you have to buy an extra regulator, that also capable of providing the needed current.

**Important note:** Since you didn't specify, how you are connecting the RGB LEDs, you also have to take care about the current limit of a single pin. It should not exceed 20mA, 40mA at the absolute maximum. So you cannot drive the LEDs directly. You will need a driver for then anyway. The simplest way is a MOSFET, that is capable of sourcing the corresponding current. It is then controlled by the Arduino, which needs very little current for it.

  [1]: https://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf

body:
If the 5V source is the barrel jack, (like from a 7.5V or 9V source), than you may be able to get up to 800mA to 1A from the 5V pin. There is a reverse polarity diode that is rated for 1A. The 5V regulator is only rated for 800mA. It does not have good heatsinking, and will overheat and shut before you see 800mA tho.
USB, well, you may get 500mA from that, if the source doesn't shut down first. If it doesn't, then the 500mA inline fuse should open.

You really need a seperate source for 5V for power to the strands.  Be sure to connect the Gnd from the source to the Arduino Gnd.

What kind of RGB LEDs are you using? WS2812B type LEDs?


body:
Trying to test [THIS][1]. Got following error:

 esptool v0.4.13 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
  setting board to nodemcu
  setting baudrate from 115200 to 9600
  setting port from COM1 to COM3
  setting address from 0x00000000 to 0x00000000
  espcomm_upload_file
  espcomm_upload_mem
  setting serial port timeouts to 1000 ms
 opening bootloader
 resetting board
 trying to connect
  flush start
  setting serial port timeouts to 1 ms
  setting serial port timeouts to 1000 ms
  flush complete
  espcomm_send_command: sending command header
  espcomm_send_command: sending command payload
  read 0, requested 1
 trying to connect
  flush start
  setting serial port timeouts to 1 ms
  setting serial port timeouts to 1000 ms
  flush complete
  espcomm_send_command: sending command header
  espcomm_send_command: sending command payload
  espcomm_send_command: receiving 2 bytes of data
  espcomm_send_command: receiving 2 bytes of data
  espcomm_send_command: receiving 2 bytes of data
  espcomm_send_command: receiving 2 bytes of data
  espcomm_send_command: receiving 2 bytes of data
  espcomm_send_command: receiving 2 bytes of data
  espcomm_send_command: receiving 2 bytes of data
  espcomm_send_command: receiving 2 bytes of data
 Uploading 356000 bytes from C:\Users\PRAMIT~1\AppData\Local\Temp\arduino_build_521093/testPersWiFiManager.ino.bin to flash at 0x00000000
  erasing flash
  size: 056ea0 address: 000000
  first_sector_index: 0
  total_sector_count: 87
  head_sector_count: 16
  adjusted_sector_count: 71
  erase_size: 047000
  espcomm_send_command: sending command header
  espcomm_send_command: sending command payload
  setting serial port timeouts to 15000 ms
  setting serial port timeouts to 1000 ms
  espcomm_send_command: receiving 2 bytes of data
  writing flash
 ................................................................................ [ 22% ]
 ................................................................................ [ 45% ]
 ................................................................................ [ 68% ]
 .......................An error occurred while uploading the sketch

All libraries are included, no compile error.
Steps followed:
1st uploaded the data using `Tools>ESP8266 Sketch data upload`.
Then `Sketch>upload`

After failing this, I tried a basic example similar to [THIS][2]. This uploaded successfully. The same configuration is used for both scenarios.

What am I missing? I am getting no clue.

Settings:

[![Settings][3]][3]

  [1]: https://github.com/r-downing/PersWiFiManager/tree/master/examples/spiffs_rest_api_nonblocking
  [2]: https://github.com/squix78/esp8266-getting-started/blob/master/Exercise_04_04_Solution/Exercise_04_04_Solution.ino
  [3]: https://i.stack.imgur.com/QBaa2.png

title: Help in "An error occurred while uploading the sketch"

Answers: 1

body: The upload to esp8266 with esptool used in IDE doesn't work good on slow baudrate. It fails for larger sketches. You can upload to NodeMcu at 921600 baud.


body:
I've shorted 5V to GND and the Arduino Nano (CH340 clone) stopped working (power LED light is dimming). The board had a burning smell, and I also checked if other Arduini on the same USB port worked and they did, so I'm quite sure the Arduino is dead.

After the incident, I de-soldered the TQFP Atmega328p (plus the crystal) to reuse. I'm thinking that if it's only the external circuitry that's damaged, then the chip should be OK. Can I reuse the chip if I solder onto a new board? What components could have been damaged?

title: Accidentally shorted 5V to GND on Arduino Nano, can I reuse the ATmega328p?

Answers: 1

body: On a Arduino Nano, there is a diode that prevents an external 5V source from back feeding into the USB source. If your clone equivalent has that as well, I suspect that is the part that got fried.


body:
I am using a NodeMCU v.1.0 ESP-12 for a small project. It is powered by 3xAA batteries (4.5v) in Vin, but to reduce power consumption I need to put in in deepsleep every now and then.

Running this small sketch:

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

      // Wait for serial to initialize.
      while(!Serial) { }

      Serial.println("I'm awake.");

      Serial.println("Going into deep sleep for 20 seconds");
      ESP.deepSleep(20e6); // 20e6 is 20 seconds
    }

    void loop() {
    }

I have measured a consumption of 8mA when it goes to deepsleep, and this is not acceptable for my purpose. In order to wake up from sleep I have connected pin GPIO16 (D0) to RST, and it works. I knew that NodeMCU should have only few µA of consumption in deepsleep. How can I fix this?

title: NodeMCU v1.0 high power consumption in deepsleep

Answers: 1

body:
Consider the TI TPL5110 timer chip with power control MOSFET. Set the timer period with a resistor then the TPL5110 powers on the NodeMCU periodically. Deep sleep is not used. RTC RAM will be lost so use SPIFFS for persistent data.

Adafruit has a breakout board. Take a look in Adafruit's forum for user comments because it has a few limitations.


body:
Okay so this is the code for my receiver.

This is quite confusing so let's dub Receiver = `DEVICE 1` and Transmitter = `DEVICE 2`

`DEVICE 1`: NRF24L01+, HC-05 (Bluetooth)

`DEVICE 2`: NRF24L01+

So `DEVICE 1` will receive data from `DEVICE 2`. Also When it receives data from my phone that is connected to the HC-05 module, it will `radio.StopListening` and `radio.write`.

But for some reason, after i do `radio.StopListening`, `radio.write` doesnt work.

Currently, `DEVICE 2` has a very simple code to receive data being sent from `DEVICE 1`. I've done this just to check if there's any data being sent when `DEVICE 1`'s HC-05 module receives data.

Code:
<!-- language-all: lang-cpp -->

    #include "Arduino.h"
    #include <nRF24L01.h>
    #include <printf.h>
    #include <RF24.h>
    #include <RF24_config.h>

    RF24 radio(9, 8);

    byte addresses[][6] = {"1Node","2Node"};

    void setup() {
      Serial.begin(9600);
      radio.begin();
      radio.setPALevel(RF24_PA_MIN);
      radio.setDataRate(RF24_2MBPS);
      radio.setChannel(124);

      // Open a writing and reading pipe on each radio, with opposite addresses
      radio.openWritingPipe(addresses[0]);
      radio.openReadingPipe(1, addresses[1]);
    }

    void loop() {
      unsigned char rf_data; //Make a variable to store the data
      unsigned char bt_data;
      unsigned char tosend;
      radio.startListening();

      if (radio.available()){
        while (radio.available()){
          radio.read(&rf_data, sizeof(rf_data));
          Serial.println(rf_data);
          }
        }

      if (Serial.available()>0){
        while (Serial.available()>0){
          bt_data = Serial.read();
          radio.stopListening();
          Serial.println(bt_data); //----------- I'M ABLE TO SERIAL PRINTLN ----
          radio.write(&bt_data, sizeof(bt_data)); //-------- BUT I'M UNABLE TO PERFORM THIS CODE HERE FOR SOME REASON
          }
        }

    }

I've added comments to show which part works and which part doesn't

I hope this question isn't too hard to understand.

title: NRF24L01+ - After stopListening, can't write data

Answers: 1

body:
There could be few reasons but, firstly I would like to ask you to check if your write command is working at all. Try to disable reading mode and leave just write mode:

    #include "Arduino.h"
    #include <nRF24L01.h>
    #include <printf.h>
    #include <RF24.h>
    #include <RF24_config.h>

    RF24 radio(9, 8);

    byte addresses[][6] = {"1Node","2Node"};

    void setup() {
      Serial.begin(9600);
      radio.begin();
      radio.setPALevel(RF24_PA_MIN);
      radio.setDataRate(RF24_2MBPS);
      radio.setChannel(124);

      // Open a writing and reading pipe on each radio, with opposite addresses
      radio.openWritingPipe(addresses[0]);
      //radio.openReadingPipe(1, addresses[1]);
    }

    void loop() {
      unsigned char rf_data; //Make a variable to store the data
      unsigned char bt_data;
      unsigned char tosend;
      //radio.startListening();

     // if (radio.available()){
     //   while (radio.available()){
     //     radio.read(&rf_data, sizeof(rf_data));
     //     Serial.println(rf_data);
     //    }
     //   }

      if (Serial.available()>0){
        while (Serial.available()>0){
          bt_data = Serial.read();
          //radio.stopListening();
          Serial.println(bt_data); //----------- I'M ABLE TO SERIAL PRINTLN ----
          radio.write(&bt_data, sizeof(bt_data)); //-------- BUT I'M UNABLE TO PERFORM THIS CODE HERE FOR SOME REASON
          }
        }

    }

Try above code and if it will not work change `RF24_2MBPS` to `RF24_1MBPS` and `RF24_PA_MIN` to `RF24_PA_LOW` on both modules (transmitter and receiver)


body: I am building an automatic door opener and for its mechanism I need a motor with a high torque and low speed. My question here is how to measure the torque needed to move the door as I cannot really weigh the door and find its mass. Can anyone help me out?

title: Necessary torque of motor to move a door.

Answers: 1

body:
You need a "hanging scale" preferably "analog one".

[![hanging scale][1]][1]

Mount it to any place of the door and slowly pool at 90 degrees. Check what value does the scale show when doors start moving. Static friction is always higher than dynamic friction.

[Torque][2] = Radius * Force

Raduis is the distance between mounting place and door hinges.
Force is 9.81 times max value shown by the scale in kilograms.

Do this many times for many mounting points then take average.
Use safety margin of 50% (motor should have at least 150% of required torque)

  [1]: https://i.stack.imgur.com/HjWsX.jpg
  [2]: https://en.wikipedia.org/wiki/Torque


body:
 #include <ArduinoJson.h>
 #include <FS.h>

 /* Set these to desired credentials in runtime */
 struct Config {
   String ssid = "";
   String pass = "";
   bool hFlag = false;
 };

 void setup() {
   // put your setup code here, to run once:
   Serial.begin(115200);
   Serial.println("");
   delay(1000);

   //allows serving of files from SPIFFS
   Serial.println("Mounting FS...");
   if (!SPIFFS.begin()) {
  Serial.println("Failed to mount file system");
  return;
   }

   if (readConfigFile("/LaSt.json", false)) {
  Serial.println("Config read");
   } else {
  Serial.println("Failed to read config");
   }
 }

 bool readConfigFile(char* fileName, bool whichFile)
 {
   File configFile = SPIFFS.open(fileName, "r");
   if (!configFile) {
  Serial.println("Failed to open config file");
  return false;
   }

   size_t size = configFile.size();
   if (size > 1024) {
  Serial.println("Config file size is too large");
  return false;
   }

   // Allocate the memory pool on the stack.
   // Use arduinojson.org/assistant to compute the capacity.
   StaticJsonBuffer<256> jsonBuffer;

   // Parse the root object
   JsonObject &root = jsonBuffer.parseObject(configFile);

   if (!root.success())
  Serial.println(F("Failed to read file, using default configuration"));

   // Copy values from the JsonObject to the Config
   Config.ssid = root["ssid"];
   Config.pass = root["pass"];
   if (whichFile)
   {
  Config.hFlag = root["hFlag"];
   }

   // We don't need the file anymore
   configFile.close();

   return true;
 }

Compile gives error in `Copy values from the JsonObject to the Config` section. Error: `expected unqualified-id before '.' token`.

Want to read file from SPIFFS, and store in variable to use.

title: Reading file from SPIFFS in nodemcu using ArduinoJson

Answers: 2

body:
Your code at the top:

    struct Config {
      String ssid = "";
      String pass = "";
      bool hFlag = false;
    };

defines a variable "type". It's like making a new `int` or `bool`, but yours is called `struct Config`.

After making the type, you need to create declare an instance of it.

    struct Config cfg;

Then, you refer to the one **you** created:

      // Copy values from the JsonObject to the Config struct named cfg
      cfg.ssid = root["ssid"];
      cfg.pass = root["pass"];
      if (whichFile)
      {
        cfg.hFlag = root["hFlag"];
      }

Note that a particular issue with ArduinoJSON and Strings is that you may get an error like:

    error: ambiguous overload for 'operator=' (operand types are 'String' and 'ArduinoJson::JsonObjectSubscript<const char*>')

There is an [ArduinoJSON FAQ entry][1] that states

> Most of the time you can rely on implicit casts.
>
> But there is one notable exception: when you convert a JsonVariant to
> a String.
>
> For example:
>
>     String ssid = network["ssid"];
>     ssid = network["ssid"];
>
> The first line will compile but the second will fail with the
> following error:
>
>     error: ambiguous overload for 'operator=' (operand types are 'String' and 'ArduinoJson::JsonObjectSubscript<const char*>')
>
> The solution is to remove the ambiguity with any of the following replacement:
>
>     ssid = (const char*)network["ssid"];
>     ssid = network["ssid"].as<const char*>();
>     ssid = network["ssid"].as<String>();

  [1]: https://arduinojson.org/v5/faq/how-to-fix-error-ambiguous-overload-for-operator/

body:
#include FS.h
#include ESP8266WiFi.h
#include ArduinoJson.h

/* Set these to desired credentials in runtime */

  String ssid = "tttttttt";
  String pass = "ssssssss";

#define fileName "/LaSt.json"

DynamicJsonBuffer jsonBuffer;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("");
  delay(1000);

  //allows serving of files from SPIFFS
  Serial.println("Mounting FS...");
  if (SPIFFS.begin()) {

 if (SPIFFS.exists(fileName)) {

  File subscribedUsersFile = SPIFFS.open(fileName, "r");

  delay(10);

  String file_content = subscribedUsersFile.readString();

  JsonObject& users = jsonBuffer.parseObject(file_content);

           if(users.containsKey("ssid"))          {ssid=users["ssid"].as<String>();}
           if(users.containsKey("pass"))          {pass=users["pass"].as<String>();}

    subscribedUsersFile.close();

    users.prettyPrintTo(Serial);

  }
else  {

   // Create empty file (w+ not working as expect)

   File subscribedUsersFile = SPIFFS.open(fileName, "a+");

   JsonObject& users = jsonBuffer.createObject();

   users.set("ssid", ssid);

   users.set("pass", pass);

  users.printTo(subscribedUsersFile);

  users.printTo(Serial);

  subscribedUsersFile.close();

  Serial.println("New Config File Created...\n");

  users.prettyPrintTo(Serial);

    }

  }
}