message:
storage problem

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

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!


sender: user

sender: assistant

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


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

[![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

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


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

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

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


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

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.

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


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

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

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.


message:
nrf24l01 fried when supplying 6.5V to VIN?

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.

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.


message:
Unable to upload to ESP32 LOLIN D32 board

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?

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


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

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.

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?


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

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

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.


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

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?

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.


message:
NodeMCU v1.0 high power consumption in deepsleep

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?

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.


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

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.

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)


message:
Necessary torque of motor to move a door.

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?

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


message:
Reading file from SPIFFS in nodemcu using ArduinoJson

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

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

    }

  }
}


message:
Sending >255 bytes array to arduino

I am trying to send a 50x50 bitmap bytearray from my python client to arduino where it should be displayed on a screen.

I need to receive 350 bytes to have the data to show the bitmap but as soon as i initialise the array with > 255 elements it does weird things (i guess because of the memory):

**When initialising the array with size 254 it does the expected:**

> Transmission of 350 completed in 2.805466s (arduino) Received: 253
> elements

**with size 350 I only get**

> "Received: 93 elements"

How can i split the bytes i receive with the available memory and then build the bitmap accordingly or what is a better way to do it? I would like to have it transmitted via serial rather than building the qrcode in arduino (as i couldn't get the libraries required working in my setup).

*My python client does basically this:*

    for element in qrCodeBytes:
        countElementsSent+=1
        ser.write(element)
        print("Sending " + str(element))
    ser.write("$".encode()) #stop char

*My arduino code is based on the popular Serial input basics guide
https://forum.arduino.cc/index.php?topic=288234.0*

     const byte numChars = 254;
     byte receivedChars[numChars]; // an array to store the received data

    boolean newData = false;

    void setup() {
     Serial.begin(114000);
     Serial.setTimeout(10000);
     Serial.println("<Arduino is ready>");
     display.begin(SSD1306_SWITCHCAPVCC, 0x3C);  // initialize with the I2C addr 0x3D (for the 128x64)
     display.clearDisplay();
     display.display();
    }

    void loop() {
     recvWithEndMarker();
     showNewData();
    }

    void recvWithEndMarker() {
     static byte ndx = 0;
     char endMarker = '$';
     char rc;

     // if (Serial.available() > 0) {
       while (Serial.available() > 0 && newData == false) {
         rc = Serial.read();
         if (rc != endMarker) {
           receivedChars[ndx] = rc;
           ndx++;
           if (ndx >= numChars) {
             ndx = numChars - 1;
           }
         }
         else {
         receivedChars[ndx] = '$'; // terminate the string
         Serial.println("Received: " + String(ndx) + " elements");
         ndx = 0;
         newData = true;
         }
       }
    }

    void showNewData() {
     if (newData == true) {
     Serial.println("This just in ... ");
     display.clearDisplay();
     drawBitMap(receivedChars,50,50,0);
     display.display();
     newData = false;
     }
    }

    void drawBitMap(unsigned char *img, int width, int height, int position){
      if (position ==0){
       display.drawBitmap(128/2-(width/2), 64/2-(height/2), img, width, height, 1);
      } else if (position == 1){
       display.drawBitmap(128-62,1, img, width, height, 1);
      } else if (position == 2){
       display.drawBitmap(0,5, img, width, height, 1);
      }
    }

body: You use type `byte` for the variable `ndx`. Type byte is 8 bits, so the max value is 255. The variable `ndx` is incremented and after 255 it continues counting from 0.


message:
Arduino writes file to SD but not content to file

I'm using an Arduino UNO, the Extended Database Library (EDB), and an microSD Card to read/write 2 database tables. I've managed to create both ".db" files on the SD (they show up in Finder when I load the microSD directly onto my Mac).

I can also populate them with placeholder data, but this data does not seem to be actually written to the file (and thus doesn't survive reboot).

Also, trying `dbFile = SD.open(db_name1, FILE_WRITE);` returns false, even though the files do exist on the drive?

Here's my create code:

    #include <SPI.h>
    #include <SD.h>
    #define SD_PIN 10  //SD read/write pin
    #define TABLE_SIZE 8192  //256*32
    #include "Arduino.h"
    #include <EDB.h>

    char* db_name1 = "/DB/SENSOR1.db";
    char* db_name2 = "/DB/SENSOR2.db";
    File dbFile;

    struct sensorLog1 {
      unsigned int id;
      float input;
      unsigned int timestamp;
    }
    sensorLog1;
    struct sensorLog2 {
      unsigned int id;
      float input;
      unsigned int timestamp;
    }
    sensorLog2;

    // Setting up EDB object
    inline void writer (unsigned long address, const byte* data, unsigned int recsize) {
      dbFile.seek(address);
      dbFile.write(data,recsize);
      dbFile.flush();
    }
    inline void reader (unsigned long address, byte* data, unsigned int recsize) {
        dbFile.seek(address);
        dbFile.read(data,recsize);
    }
    // Create an EDB object with the appropriate write and read handlers
    EDB db(&writer, &reader);

    void setup() {

      Serial.begin(9600);

      createDB(db_name1, "sensorLog1");
      createDB(db_name2, "sensorLog2");

      dbFile = SD.open(db_name1, FILE_WRITE);  // Doesn't work!
      if (!dbFile) { Serial.println("File does not exist"); }

    }

    void loop() {}

    void createDB(char* db_name, char* table_name) {

      // create file
      dbFile = SD.open(db_name, FILE_WRITE);
      db.create(0, TABLE_SIZE, (unsigned int)sizeof(table_name));

      // populate with placeholder data
      for (unsigned int i = 1; i <= 20; i++) {
        table_name.id = i;
        table_name.input = 0;
        table_name.timestamp = 0;
        EDB_Status result = db.appendRec(EDB_REC table_name);
      }

      // check data
      Serial.println(db.count());  // returns '20'

      // close file to write
      dbFile.close();

    }

body:
> db.create(0, TABLE_SIZE, __(unsigned int)sizeof(table_name)__);

The third parameter is the record size! sizeof doesn't work on data, it works on types, so your getting the size of a __char*__ instead of the size of your sensorlogN struct.

Your code as written shouldn't compile! a char* doesn't have a .id member.

    table_name.id = i;
    table_name.input = 0;
    table_name.timestamp = 0;


message:
What happens if you supply too much voltage to an LED?

Say I have an LED that requires 3.5v. What happens if I power it with more voltage?

For example, my Arduino Uno has a 5v pin. If I power the 3.5v LED from the 5v pin, what will happen?

body:
In the most simple terms: it will kill the LED.  However things are really not that simple.

First off, an LED is a *current* driven device, not a *voltage* driven device. That is, it doesn't really care what the voltage is, but it does care what the current is.  Of course, too much voltage will kill it - but too much current, regardless of the voltage, will kill it.

It's important to understand that an LED is what is known as a *non-linear component*.  Things like resistors are called *linear* because they have a linear relationship between voltage and current. Increase the voltage, and the current increases by the same proportion. Increase the resistance and the current decreases by the same proportion.

However an LED is not like that. A typical Voltage-vs-Current graph for an LED looks like this:

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

Once the voltage reaches the "forward voltage" of the LED the current flowing through it rapidly increases. As you can see it very quickly gets towards infinity. Above a certain point and an increase in voltage has no real difference in the current. In that example the difference between 3V and 5V would be both infinite and zero. In other words, it's pretty meaningless.

But we're still over-simplifying, and that's because we've assumed an *ideal* power supply. That is, one that can supply a fixed voltage, but *infinite* current. In other words, a power supply with *zero impedance*.

No such thing exists, though.

Every fixed-voltage power supply can be seen as an ideal voltage source with an in-line (series) resistor. That resistor limits the amount of current that the supply can provide before the voltage drops too low.  In schematic terms, it looks like this:

<!-- 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/qBiOw.png)

<!-- End schematic -->

If the voltage of the source is above the forward voltage of the LED it will try and draw an infinite amount of current from the source.  That current will lead to a voltage drop across the resistance *RZ*, which results in the output voltage of the source being reduced.

It will reduce to be the same as the forward voltage of the LED.

We can, of course, calculate the current that would come out of the supply if we know the impedance of the source, but that's not something that is often known.  So you assume it's low and take precautions.

For example, if we happen to know the impedance of the source is 1Ω (maybe it's stated in the datasheet for the power source...) and the voltage is 5V, and we have an LED that has a forward voltage of 2V (I like nice round numbers), we can work out that:

* The voltage drop caused by the impedance is 3V (5-2)
* The current that causes that drop is 3A (I=V/R, 3/1=3A)

3A is way off the scale for an LED, and it will basically melt internally.

So we add an extra resistance to drop *more* of the voltage at a lower current.

Now if we take the example of powering an LED directly from an Arduino's GPIO pin without a resistor, we can do the same kind of calculations.

We know that we mustn't draw more than 40mA from a pin (*absolute maximum*), so if we take that as the current that can come out of a pin before it drops below an acceptable level we can work out an estimate of the impedance. Since the datasheet tells us the output level it shouldn't drop below is 4.2V when powered by 5V, we know that the maximum voltage drop at the maximum current would be 0.8V (5-4.2).  So:

* R=V/I = 0.8/0.04 = 20Ω.

There. That's an approximation of the output impedance of a GPIO pin on an Arduino.  So we can plug that into our formulae and connect an LED, and we get:

* The voltage drop caused by the impedance is 3V (5-2)
* The current that causes that drop is 150mA (I=V/R, 3/20=0.15)

150mA is not massive. It's more than an LED typically wants (20-30mA tops), so the LED won't be happy, but it won't instantly blow at that level. It will be brighter than normal, get hotter than normal, and its lifetime will be much much shorter than normal.

That's not the worrying thing though.  The worst thing is the *power dissipation* from the impedance:

* P=I²R = 0.15²×20 = 0.45W.

That's almost half a watt of heat being generated by the GPIO pin's drivers. If you consider that a half-watt resistor is pretty chunky, if you can picture that power being crammed into the tiny space of a single MOSFET within a silicon chip, you can see how that may become a problem.

It's really not capable of dealing with that level of heat, and the GPIO pin's driver MOSFET goes belly up.  Bye bye MOSFET, bye bye GPIO pin.

As an aside, you would probably also see other strange things happening as the chip tries in vain to deliver large currents to a single GPIO pin. Other areas of the chip get starved of power, power rails drop in voltage, code crashes, etc. All from just one little LED being connected without a resistor.

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


message:
Using the Arduino compiler, is it possible to use Atmega2560 interrupt pins that are unused by Mega?

Looking into [the schematics for the Arduino Mega](https://www.arduino.cc/en/uploads/Main/arduino-mega2560-schematic.pdf) I noticed that pins PE6 and PE7 are interrupt-enabled (INT6 and INT7 respectively); however, they remain unconnected to any Arduino I/O pin.

I'm designing a custom board based on the Atmega2560 and want to use the Arduino IDE/Compiler to upload my code to it, so I'm pretty much replicating a big part of the Arduino Mega schematic into my board.

However, I would really like to enable these two extra interrupt pins (having 8 interrupt pins in total) in my board, but I'm now sure how to proceed from the software side. How could I enable this new pins in order to use them from the Arduino compiler?

![Atmega2560 Interrupt pins](https://i.stack.imgur.com/r4yNB.png)

Thanks!

body:
If you are not afraid of getting your hands dirty by touching hardware
registers, you can access those pins bare-metal style, using [port
manipulation][registers]. You will have to read the [datasheet][],
specifically the section “External Interrupts” if that's what you are
after.

This works with the stock Arduino core (or even without core), which may
be interesting from a maintenance point of view, but it's not as easy to
use as the Arduino interrupt API.

[registers]: https://www.arduino.cc/en/Reference/PortManipulation
[datasheet]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf


message:
How would I include Arduino libraries using AVR-gcc without the IDE?

I am writing my own code for the Arduino Uno. I compile my code with AVR-gcc, and then upload it with AVRdude. I am not using the Arduino software, but I do have it installed and working on my PC. I want to include some of the Arduino libraries in my project, like Wire.h for example.

I realise that I could either copy the source file to my current working directory or include the entire path, like: `#include "/usr/share/arduino/libraries/Wire/Wire.h"` but the issue with that is `Wire.h` includes `Stream.h` which includes `Print.h` which includes...you get the idea. These different libraries are not kept in the same place either. I would have to hunt up and down chains of files, copy them and then use them locally. This does not seem like a good option to me.

Including them like I normally would using the IDE doesn't work at all, which is not surprising.

So, how can I use these libraries in my project without all the pain of finding them manually?

body:
Since you will end up using a significant portion of the Arduino core
library, the easiest path is to accept the idea that you are now writing
“Arduino sketches” rather than plain C++ code. Don't resist, be
assimilated, fire the IDE and write `setup()` and `loop()`. ;-)

Once you have something working, the next step is to get rid of the IDE,
which is admittedly not very nice. A couple of ways to do that:

* Use [Arduino Builder][builder], the command-line tool for building
  Arduino sketches. The internals of this are the same as for the
  Arduino IDE, but it works on the command line.
* Use a Makefile, like [Sudar Muthu's Arduino-Makefile][makefile]. This
  is a generic Makefile for building Arduino programs. It is not 100%
  compatible with the IDE or Aduino builder, as it does not add function
  declarations for you, but it may suit you better if you are used to a
  more standard toolchain (it's just make + avr-gcc + avrdude).

[builder]: https://github.com/arduino/arduino-builder
[makefile]: https://github.com/sudar/Arduino-Makefile


message:
How do I make Arduino IDE use a specific version of GCC in Debian?

Using Raspbian Stretch.

I installed gcc-4.9 with specified version. Then I installed arduino (2.1.0.5) which in turn pulled gcc 4.6. When I try to compile [Marlin][1] in it, it says

> Marlin requires C++11 support (gcc >= 4.7, Arduino IDE >= 1.6.8).
> Please upgrade your toolchain.

 How do I make Arduino IDE use the correct version of GCC?

  [1]: https://reprap.org/wiki/Marlin

body:
As Majenko [pointed out][1], I should have used a tarball from the [official site][2] instead of the repositories. Which makes me wonder why that package wasn't deprecated or something...

  [1]: https://arduino.stackexchange.com/questions/54792/how-do-i-make-arduino-ide-use-a-specific-version-of-gcc-in-debian#comment115148_54792
  [2]: https://www.arduino.cc/en/Main/Software


body:
Installing the Arduino package from the Debian repository (or the one for derived distros like Ubuntu) performs the useful purpose of setting up all the necessary permissions for the Arduino IDE to work. Those permissions are NOT automatically removed when you uninstall the package.

The simplest way to get a working Arduino install:

1. Install Arduino from the repo

2. Immediately uninstall it

3. Get a current version of Arduino from arduino.cc and install that


message:
Memory chip for arduino

I know that you can't expand your ram because it is intern. But I want a extern memory chip (1024KBytes) that is very fast. I know that I need a library to access information on this chip. And functions to read and write data. A shield or breakout board it doesn't matter, and I want that it is compatible with Arduino mega. If the arduino lost power it doesn't matter if I lost the data. It must hold the data when the arduino is powerd.

body:
You can quite easily connect multiple 128kB SPI ram chips to an Arduino. 4 of them together would give you 512kB of extra SPI-connected SRAM.

Access isn't super fast.

Another option is to use a parallel 8-bit SRAM chip. These take a lot more wiring since you need 8 wires for the data, log2(n) wires for the address, plus a couple of control wires (OE, WE, etc). But if you wire it making use of entire IO ports you can get much faster access times.  Also, these come in larger capacities than the SPI SRAM chips.

There is also PSRAM available in even bigger capacities. The same interface as SRAM but it's actually DRAM. The "P" stands for "Pseudo". You can get these in megabyte capacities, although they are usually in a BGA footprint, so you'd need to find one on a breakout board.


message:
Arduino IDE won't upload sketches

I recently updated my Arduino IDE to 1.8.5 from 1.6.9. I am getting issues with uploading sketches. The sketch compiles, but when I try to upload it I get this message:

    Arduino: 1.8.5 (Mac OS X), Board: "Arduino/Genuino Mega or Mega 2560,
    ATmega2560 (Mega 2560)"

    Sketch uses 642 bytes (0%) of program storage space. Maximum is 253952 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 8183 bytes for local variables. Maximum is 8192 bytes.
    java.io.IOException: Cannot run program "___REMOVE___/bin/avrdude": error=2, No such file or directory
     at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
     at java.lang.Runtime.exec(Runtime.java:620)
     at java.lang.Runtime.exec(Runtime.java:485)
     at processing.app.helpers.ProcessUtils.exec(ProcessUtils.java:11)
     at cc.arduino.packages.Uploader.executeUploadCommand(Uploader.java:129)
     at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:207)
     at cc.arduino.UploaderUtils.upload(UploaderUtils.java:78)
     at processing.app.SketchController.upload(SketchController.java:713)
     at processing.app.SketchController.exportApplet(SketchController.java:686)
     at processing.app.Editor$DefaultExportHandler.run(Editor.java:2168)
     at java.lang.Thread.run(Thread.java:748)
    Caused by: java.io.IOException: error=2, No such file or directory
     at java.lang.UNIXProcess.forkAndExec(Native Method)
     at java.lang.UNIXProcess.<init>(UNIXProcess.java:247)
     at java.lang.ProcessImpl.start(ProcessImpl.java:134)
     at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
     ... 10 more
    An error occurred while uploading the sketch

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

I get this message whether or not an Arduino is connected. I also get the same message weather I connect my Arduino Mega or Uno. I tried my sketch, the blink sketch and a completely blank sketch, all with the same results.

Could I please get some help with this issue?

body:
You may be able to fix this by taking some drastic action. Be aware this is somewhat advanced and will remove any boards you have installed via Boards Manager:

1. Click the link on the line following **File > Preferences > More preferences can be edited directly in the file**. This will open the `Arduino15` (or similar name depending on OS) folder.
1. Delete all files and folders under the `Arduino15` folder except for preferences.txt. Please be very careful when deleting things from your computer. When in doubt, back up!
1. Restart the Arduino IDE.
1. Verify you can now upload before re-installing any boards via Boards Manager.


message:
Connect a TM1627 to ESP32

I want to control a 7 segment display that has a TM1637 integrated with an ESP32.

Some time ago I created a layout that used an ESP12e but I need more GPIO pins so I'm switching over to an ESP32.

This was how I had it hooked up:

    CLK -> GPOI14
    DIO -> GPIO12

I think I did it this way because I had to use the special CLK pin tou can see in [this](https://simba-os.readthedocs.io/en/latest/_images/esp12e-pinout.png) pinout.

Only I don't know if I need to hook them up with special pins on the ESP32. I can't find a good tutorial and I don't have the parts yet to test with.

Do you guys know which pin(s) are suitable for the TM1637?

body: The label CLK on esp8266 is in a context of SPI pins CLK, MISO, MOSI, SS. You had no reason to connect TM1637 CLK to this pin, since with TM1637 you can use any GPIO pins of the MCU for CLK and DIO.


message:
Relay does not trigger

Its my first attempt to work with relay
I tried to test my relay with this simple code

    int Relay = 2; void setup() {
      // put your setup code here, to run once:
      Serial.begin(115200);
      pinMode(Relay,OUTPUT);
    }

    void loop() {

      digitalWrite(Relay,HIGH);
      delay(1000);
      digitalWrite(Relay,LOW);
      delay(1000);
    }

[![I use thius simple 12V Relay][1]][1]

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

Connected to
IN -> Digital 2
GND -> GND
VCC -> 5V

The only thing is happened is the LED of the relay blinking in every sec. but can not hear the clicking sound from the relay box or testing with a multimeter's diode function the two(NC and COM) OUTs aren't close
I tried to test other relays(from the same type) but does not do anything else.

thank you for your help
What can be wrong?

body:
You need to define `Relay`.  If the LED on the relay module is blinking, then you must have defined as pin 2 output, but omitted it from the code you posted.  Please post all of the code!

It is good practice for all user variables to start with lowercase, e.g. `relay` not `Relay`.  Then the code becomes:

    relay = 2;
    void setup(){
    pinMode(relay,OUTPUT);
    digitalWrite(relay,"LOW");
    }

    void loop(){
    digitalWrite(relay,"HIGH");
    delay(1000);
    digitalWrite(relay,"LOW");
    delay(1000);
    }

If the relay still does not click on/off, test the microcontoller voltage output on the `relay` pin using your voltmeter.  Check the relay is not dead or mis-wired.


body:
NC is "Normally Connected" - this contact is connected to COM ("common") if coil of the relay is not powered - the relay is disconnected.

NO "Normally Open" is connected to COM when the coil of the relay is powered - the relay is connected.

Some relays have the coil powered when the signal from MCU is LOW.

If the coil of the relay doesn't click, but the signaling LED lights up, then VCC is not connected. Check if you plugged the wire really to 5 V on Arduino side.


message:
Timer interrupt triggers too often

The following question is based on the Arduino Pro Mini (8MHz, 3.3V)

I'm in process of developing (yet another) LED strip driver shield. For that I wrote a simple control loop, that adjusts the channel brightness (PWM duty cycle) to a given target value with a smooth transition.

For testing purposes I configured Timer1 with a 0.5Hz interval to randomly assign new target values. This works almost as intended. When watching the values you can see the constant value periods and completely random, fast changing periods in between (picture generated with Arduino built-in plot). The curved, rather smooth lines are the PWM outputs following the target value (that part is confirmed to work):
[![enter image description here][1]][1]

The relevant code responsible for the changing of the target value is

    ISR(TIMER1_COMPA_vect) //timer1 interrupt 0.5Hz
    {
      for(auto it = 0; it < 4; ++it)
      channel_target[it] = random(0, 255);  // assign a random value between 0..255 (max for pwm)
    }

My assumption is, that the ISR is called very fast in the fuzzy intervals but since I havn't done much with arduinos yet, I'm not familiar on what kind of background functions might interfere with that.

For completeness the full code:

    double    channel[4];
    uint8_t   channel_target[4];
    const double  channel_k_p[4]   = { 0.001, 0.001, 0.001, 0.001 };
    const double    channel_k_i[4]     = { 0.01, 0.01, 0.01, 0.01 };
    double   err;
    const uint8_t  led_pins[4]   = { 3, 5, 6, 9 };
    char    serial_buffer[100];

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

     for(auto it = 0; it < 4; ++it)
      channel[it] = 0;

     for(auto it = 0; it < 4; ++it)
     {
      pinMode(led_pins[it], OUTPUT);   // sets the pin as output
      analogWrite(led_pins[it], 0);
     }

     cli();//stop interrupts

     TCCR1A = 0;// set entire TCCR1A register to 0
     TCCR1B = 0;// same for TCCR1B
     TCNT1  = 0;//initialize counter value to 0
     // set compare match register for 1hz increments
     OCR1A = 15624;// = (8*10^6) / (0.5*1024) - 1 (must be <65536)
     // turn on CTC mode
     TCCR1B |= (1 << WGM12);
     // Set CS10 and CS12 bits for 1024 prescaler
     TCCR1B |= (1 << CS12) | (1 << CS10);
     // enable timer compare interrupt
     TIMSK1 |= (1 << OCIE1A);

     //set timer2 interrupt at 500Hz
     TCCR2A = 0;// set entire TCCR2A register to 0
     TCCR2B = 0;// same for TCCR2B
     TCNT2  = 0;//initialize counter value to 0
     // set compare match register for 8khz increments
     OCR2A = 248;// = (8*10^6) / (500*64) - 1 (must be <256)
     // turn on CTC mode
     TCCR2A |= (1 << WGM21);
     // Set CS21 bit for 64 prescaler
     TCCR2B |= (1 << CS21) | (1 << CS20);
     // enable timer compare interrupt
     TIMSK2 |= (1 << OCIE2A);

     sei();  // reactivate interrupts

     randomSeed(analogRead(0));
    }

    void loop()
    {
     for(auto it = 0; it < 4; ++it)
     {
      sprintf(serial_buffer, "%d ",  channel_target[it]);
      Serial.write(serial_buffer);
     }

     for(auto it = 0; it < 4; ++it)
     {
      sprintf(serial_buffer, "%d ", round(channel[it]));
      Serial.write(serial_buffer);
      }
     Serial.write("\n");

     delay(100);
    }

    ISR(TIMER2_COMPA_vect) // timer2 interrupt at 1kHz
    {
     // ******************************
     // Channel brightness control loop
     for(auto it = 0; it < 4; ++it)
     {
      err = channel_target[it] - channel[it];

      channel[it] += err * channel_k_p[it];      // proportional
      channel[it] -= err * 0.002 * channel_k_p[it]; // integral

      if(channel[it] > 255)
       channel[it] = 255;
      analogWrite(led_pins[it], floor(channel[it]));
     }
    }

    ISR(TIMER1_COMPA_vect) //timer1 interrupt 0.5Hz
    {
      for(auto it = 0; it < 4; ++it)
      channel_target[it] = random(0, 255);  // assign a random value between 0..255 (max for pwm)
    }

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

body:
The `analogWrite()` function generates a PWM output signal using a
hardware timer. Output on pin 3 is driven by timer 2, whereas
output on pin 9 is driven by timer 1. Here, you are trying to
use these timers for PWM generation **and** for your own code timing at
the same time. This cannot work. Either you let the Arduino core library
use the timers for `analogWrite()`, or you take them for you, but not
both.

The solution to your problem is very simple. Nothing in your code really
requires a timer to start with. You can handle both the brightness
control loop and the value changes using the technique of the [Blink
Without Delay][blink] Arduino tutorial:

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

    const uint32_t TARGET_CHANGE_PERIOD = 500000;
    const uint32_t BRIGHTNESS_UPDATE_PERIOD = 1000;

    void loop()
    {
        uint32_t now = micros();
        static uint32_t last_target_change;
        if (now - last_target_change >= TARGET_CHANGE_PERIOD) {
            last_target_change += TARGET_CHANGE_PERIOD;
            // Change the brightness targets.
        }
        static uint32_t last_brightness_update;
        if (now - last_brightness_update >= BRIGHTNESS_UPDATE_PERIOD) {
            last_brightness_update += BRIGHTNESS_UPDATE_PERIOD;
            // Update the channel brightnesses.
        }
    }

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


message:
HC-05 Bluetooth module got virus

We have a problem. Our HC-05 Bluetooth module got virus. We checked it in serial monitor and found out that the output is wrong. It has a mirrored question marks(⸮)and variables(b⸮, bW⸮, k⸮, U) which is not included in our codes. How can we fix it?

body:
It is unlikely this module got a virus. It sounds more like a data rate mismatch or a noisy connection.

If you get ONLY the strange characters and nothing that you would expect, even in part, then confirm that the serial port speeds are equal on both the Arduino and the HC-05 module.

If you get some expected data, with junk characters mixed in, then check that your wires are secure and that you have connected all grounds from the Arduino and HC-05 module together with the power supply ground.


body: Your module does NOT have a virus (Who would waste their time writing a virus for a bluetooth module...?!?!). You either have a bad baud rate setting, bad wiring, or you are trying to use a high baud rate coupled with SoftwareSerial.


message:
Can I call functions from a different sketch?

I am a beginner at programming with Arduino and I am unsure on how can I call functions (such as, getData()) for the touchscreen LCD to display that data. The purpose of my device would be to listen to data communications between sensors and a controller and thus I have one RedBoard with CAN-BUS shield with a dataComms.ino sketch, which initialises getting data functions from received data packets and parses them.

Do I need to create another sketch for the display? If so, how can I call functions from another sketch, so that display.ino would have access to received values? Or are there some better ways of displaying data?

body:
You can only use one sketch at a time, meaning one sketch can be stored inside an Arduino to be executed.

This means all your code (and functionality for all devices you want to access) needs to be within that single sketch.

So what you mostly need to do is:

- Add a library for every device that you want to use.
- Call functions from that library in your .ino file.
- If you want to add functions which are not part of a library, you add both the function code and the call (where you need it) in your .ino file.

Also if you are new, don't start with everything at the same time.

- First find an example how to control the display (that's probably easier than the CAN shield).
- Add the library for the display
- Change (or copy from an example) code for the display
- Run and debug it until it works.
- Create a new sketch for the CAN shield.
- Add the library for the CAN shield.
- Call functions from that library (or use an example if available).
- Once you are convinced you know how to use both devices (display + CAN), combine the sketches (create a new sketch, add both libraries, copy code and make it one sketch).


message:
DHT11 Sensor : Stand-by or Shut down?

I have an ATmega328P monitoring room temperature and humidity. It is enough for me to monitor every 8 seconds. In these 8 seconds, I am putting my Atmega to sleep.

Now , I want to know : Does shutting down the DHT11 for these 8 seconds affect the performance of the sensor in any way or is it advisable to keep it running (stand by) for these 8 seconds ?

[Shutting down means connecting the Vcc of the sensor to GND by means of digitalWrite(Sensor_pin,LOW);]

Also , (The below question is applicable only if your answer to the above question is to keep it in Stand-by) :-

I want to modify the above project such that Temp & Humidity is measured as and when only an input button is pressed.
In this case too, should I keep the DHT11 running?

Is a running DHT11 sensor more accurate than a instantly powered on DHT11 ?

[And in case you are speculating , yeah,I want to save the 50 micro-amps Standby current of the sensor.(but of course without sacrificing accuracy of the sensor)]

body:
At times like this it is useful to refer to the datasheet.  You can, in that document, find this paragraph:

> **4. Power and Pin**
>
> DHT11’s power supply is 3-5.5V DC. When power is supplied to the sensor, do not send any instruction to the sensor in within one second in order to pass the unstable status. One capacitor valued 100nF can be added between VDD and GND for power filtering.

So you can see that if you power down the sensor completely you have to wait at least 1 second before you can do anything with it.

With it just in the low power mode it defaults to between readings you can immediately start reading as soon as your ATMega wakes up.

So you have to ask yourself: Does running the ATMega at full power for 1 second consume more or less power than running the DHT11 in low power mode for 8 seconds?

As a rough guestimate - if the ATMega is using 30mA (ballpark figure) for 1 second (that's 30mAs - milliamp-seconds), and the DHT11 uses 50uA for 8 seconds, then you have 0.05*8 = 0.4mAs.

That's 0.4mAs (sleeping) vs 30mAs (powered down). So I'd go for leaving it powered and avoid the one second delay at full power.

Another option that may save more power would be to:

1. Power off the DHT11
2. Sleep 8 seconds
3. Power on the DHT11
4. Sleep 1 second
5. Read DHT11
6. Go to 1

Of course, that means your loop then takes 9 seconds not 8. You could compensate by sleeping for multiple amounts to make 7 seconds:

1. Sleep 4 seconds
2. Sleep 2 seconds
3. Sleep 1 second
4. Power on the DHT11
5. Sleep 1 second
6. Read DHT11
7. Power off the DHT11
8. Go to 1

But of course that then makes your sleeping less efficient - so is it really worth it?


message:
How to move Servo in between three positions

I want my tower pro 9g servo to start from pos=0, wait there for 1 second, then reach pos=90 wait for 1 second, then reach pos=180 and wait for 1 second. Now it goes back to pos=0 and repeats this cycle. I have written the following code for this purpose:

    #include <Servo.h>

    Servo myservo;  // create servo object to control a servo
    // twelve servo objects can be created on most boards

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

    void setup() {
      myservo.attach(12);  // attaches the servo on pin 9 to the servo object
    }

    void loop() {

      for (pos = 0; pos <= 180; pos += 90) { // goes from 0 degrees to 180 degrees
        // in steps of 90 degree
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(1000);                       // waits 1s for the servo to reach the position
      }

      for (pos = 180; pos >= 0; pos -= 90) { // goes from 180 degrees to 0 degrees
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(1000);                       // waits 1s for the servo to reach the position
      }

    }

But the behavior of the servo is not correct. It moves few degree from  initial position and then comes back.

What is wrong with the logic in my code ?

body:
I think that the servo is too slow. When you ask it to go 90 degrees it starts, than after one second (while it maybe reaches 5 degrees) you ask it to go to 180 degrees it is probably reaching 10 degrees. There it waits again one second.

Than you ask it to go back to 0 (which it does in the same 2 seconds as it moved from 0 to 10 degrees).

Try to adjust the delay times, or use a faster servo.

Also note that in your example (if you wish it would behave like coded), it will end 2 seconds at 0 and 180 degrees, and 1 second at 90 degrees).

Try:

    void move_servo(int pos)
    {
        myservo.write(pos);
        delay(30000);
    }

    void loop()
    {
        move_servo(  0);
        move_servo( 90);
        move_servo(180);
        move_servo( 90);
    }

It will wait 30 seconds between each step, make this less when possible.
To make the servo wait not more than needed, check the old and new servo position and wait as needed, it's probably reasonably linear.


body: The logic looks OK to me. But be aware that these servos don't perform well at or close to their limits - mine tend to jitter there but there may be other issues as well. I have 10 of these hobby servos; each has a different jitter-band at the ends of its travel. You may have better success driving them to 10, 90, and 170 degrees.