text:
I'm getting watchdog timer resets in NodeMCU. How can I permanently disable or stop that?
I'm using NodeMCU for my project. At first it works fine, but after some days it is resetting frequently because of the watchdog timer. I have used the Esp.wdtfeed() method also. But it is not working. Can you please tell me what the problem exactly with or any solution? Here is my code:

void setup(void) {
  ESP.wdtDisable();
  ESP.wdtEnable(WDTO_8S);
  Serial.begin(9600);
  int n = WiFi.scanNetworks();
  Serial.println("");
  if (n == 0)
    Serial.println("no networks found");
  else {
    for(int i=0;i<n;i++) {
      if(WiFi.SSID(i)==ssid1) {
        WiFi.begin(ssid1,password1);
        ssid=ssid1;
      } else if(WiFi.SSID(i)==ssid2) {
        WiFi.begin(ssid2,password2);
        ssid=ssid2;
      } else if(WiFi.SSID(i)==ssid3) {
        WiFi.begin(ssid3,password3);
        ssid=ssid3;
      }
    }
  }
  display.init();
  display.flipScreenVertically();
  display.setFont(ArialMT_Plain_16);
  display.setTextAlignment(TEXT_ALIGN_LEFT);
  display.drawStringMaxWidth(15,15, 128,"Display started");
  display.display();
  // Wait for connection
  display.clear();
  int j=0;
  while(j<10) {
    display.drawStringMaxWidth(15,15, 128,"connected to");
    display.drawStringMaxWidth(15,32, 128,ssid);
    display.display();
    display.clear();
    delay(1000);
    j++;
  }
  display.drawStringMaxWidth(15,32, 128,"");
  display.display();
  Serial.print("Connected to ");
  display.clear();
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  if (mdns.begin("esp8266WebForm", WiFi.localIP())) {
    Serial.println("MDNS responder started");
  }
  server.onNotFound(handleNotFound);
  server.begin();
  Serial.print("Connect to http://esp8266WebForm.local or http://");
  Serial.println(WiFi.localIP());
  server.on("/", getvalues);
  pinMode(buzzPin,OUTPUT);
  pinMode(but,INPUT);
}

void loop(void) {
  ESP.wdtFeed();
  if((WiFi.status()== WL_DISCONNECTED)||(WiFi.status()==WL_CONNECTION_LOST)) {
    display.drawStringMaxWidth(15,15, 128,"disconnected");
    display.display();
    int n = WiFi.scanNetworks();
    Serial.println("");
    if (n == 0)
      Serial.println("no networks found");
    else {
      for(int i=0;i<n;i++) {
        if(WiFi.SSID(i)==ssid1) {
          WiFi.begin(ssid1,password1);
          ssid=ssid1;
        } else if(WiFi.SSID(i)==ssid2) {
          WiFi.begin(ssid2,password2);
          ssid=ssid2;
        } else if(WiFi.SSID(i)==ssid3) {
          WiFi.begin(ssid3,password3);
          ssid=ssid3;
        }
      }
      int j=0;
      display.clear();
      while(j<10) {
        display.drawStringMaxWidth(15,15, 128,"connected to");
        display.drawStringMaxWidth(15,32, 128,ssid);
        display.display();
        display.clear();
        delay(1000);
        j++;
      }
      display.clear();
      display.drawStringMaxWidth(15,32, 128,"");
      display.display();
    }
  }
  getvalues();
  delay(20000);
}

Likely, you will get some humerus comments (like do you work for a certain car company).  Seriously, it sounds like the watch dog has found a problem with your code or hardware.  Rather than defeating the watch dog, most people here will suggest you find the cause (why your code has failed to "kick the dog").

Could you post the error output from the console?

here my way to find the bug first
1.comment out the watchdog from the code.
2.debug the code flow and find it get struck. Debugging in the sense put "Serial.print()" in between your code where you feel stuck but here don't disable your watchdog.

After long time I have seen this question and thought of answering as I found the issue at that time itself, But not posted here.
After debugging for long time, I got to know that there is a string i am initializing with the data fetched from a site which has been overflown beyond the memory of NodeMCU. due to which it has thrown watchdog exception, So please do memory management properly as NodeMCU cannot do data processing and all.


text:
What can I do to increase the amount of LEDs I can power with a pro micro?
I am new to arduino and have a sparkfun pro micro that I'm using to power a one meter (60 pixels) APA 102 strip. I currently power it via USB and have a program that sends lighting instructions to it. I can only seem to power ~15 pixels with full range of brightness and ~30 if I keep the brightness at about half.
Anything more and the pro micro will stop recieving data and either freeze at the last color it's recieved or turn a bright red (which I assume is a visual indication of the fail because I didn't code that). At this point, the COM port will also become inaccessible until the code is either re-uploaded or in some cases, I simply disconnect the strip. This leads me to believe that the amount of power that I am demanding is too much for the board to put out.
So am I right in this assumption? and If so, what can I do to increase the amount of pixels I can power at full range?
I'll also post my code below in case there is something I can do there to increase the pixel amount:

#include <Adafruit_DotStar.h>
#include <SPI.h>

#define NUMPIXELS 60
#define DATAPIN    4
#define CLOCKPIN   5

Adafruit_DotStar strip(NUMPIXELS, DOTSTAR_BRG);

// Variables
int mode;
int numColors;
int fadeSpeed;
int BBCC;
int R;
int G;
int B;
int Bright;

void setup() {

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

  strip.begin(); // Initialize pins for output
  strip.show();  // Turn all LEDs off ASAP
}

int      head  = 0, tail = -10; // Index of first 'on' and 'off' pixels
uint32_t color = 0xFFFFFF;      // 'On' color (starts red)

void loop() {

  //strip.setPixelColor(head, color); // 'On' pixel at head
  //strip.setPixelColor(tail, 0);     // 'Off' pixel at tail
  strip.show();                     // Refresh strip
  delay(20);                        // Pause 20 milliseconds (~50 FPS)

  getData();

  if (mode == 1)
  {
    for (int i = 0; i < (60); i++)
    {
      if (i % 2 == 0)
        strip.setPixelColor(i, G, R, B);
    }
    strip.setBrightness(Bright);
    strip.show();
  }
  else
  {
    for (int i = 0; i < (60); i++)
    {
      if (i % 2 == 0)
        strip.setPixelColor(i, 150, 200, 40);
    }
    strip.setBrightness(255);
    strip.show();
  }
}

int readLine(int readch, char * buffer, int len)
{
  static int pos = 0;
  int rpos;

  if (readch > 0)
  {
    switch(readch)
    {
      case '\r':
      {
        break;
      }
      case '\n':
      {
        rpos = pos;
        pos = 0;
        return rpos;
      }
      default:
      {
        if (pos < len-1)
        {
          buffer[pos++] = readch;
          buffer[pos] = 0;
        }
      }
  }

  return 0;
}
}

void getData()
{
  char buf[80];
  bool redo = true;

  if(readLine(Serial.read(), buf, 80) > 0)
  {
    int i = 0;
    int j = 0;
    bool skip = false;
    char fin[3];
    if (skip == false)
    {
    do//                                mode
    {
      switch (buf[i])
      {
        case '\n':
        {
          skip = true;
          redo = false;
          break;
        }
        case '|':
        {
          mode = atoi(fin);
          //Serial.print(mode);
          i++;
          redo = false;
          break;
        }
        default:
        {
          fin[j] = buf[i];
          i++;
          break;
        }
      }
      j++;
    }while(redo);
    redo = true;
    j = 0;
    }

    if (skip == false)
    {
    do//                     number of colors
    {
      switch (buf[i])
      {
        case '\n':
        {
          skip = true;
          redo = false;
          break;
        }
        case '|':
        {
          numColors = atoi(fin);
          //Serial.print(numColors);
          i++;
          redo = false;
          break;
        }
        default:
        {
          fin[j] = buf[i];
          i++;
          break;
        }
      }
      j++;
    }while(redo);
    redo = true;
    j = 0;
    }

    if (skip == false)
    {
    do//
    {
      switch (buf[i])
      {
        case '\n':
        {
          skip = true;
          redo = false;
          break;
        }
        case '|':
        {
          fadeSpeed = atoi(fin);
          //Serial.print(fadeSpeed);
          i++;
          redo = false;
          break;
        }
        default:
        {
          fin[j] = buf[i];
          i++;
          break;
        }
      }
      j++;
    }while(redo);
    redo = true;
    j = 0;
    }

    if (skip == false)
    {
    do
    {
      switch (buf[i])
      {
        case '\n':
        {
          skip = true;
          redo = false;
          break;
        }
        case '|':
        {
          BBCC = atoi(fin);
          //Serial.print(BBCC);
          i++;
          redo = false;
          break;
        }
        default:
        {
          fin[j] = buf[i];
          i++;
          break;
        }
      }
      j++;
    }while(redo);
    redo = true;
    j = 0;
    }

    if (skip == false)
    {
    do
    {
      switch (buf[i])
      {
        case '\n':
        {
          skip = true;
          redo = false;
          break;
        }
        case '|':
        {
          R = atoi(fin);
          //Serial.print(R);
          i++;
          redo = false;
          break;
        }
        default:
        {
          fin[j] = buf[i];
          i++;
          break;
        }
      }
      j++;
    }while(redo);
    redo = true;
    j = 0;
    }

    if (skip == false)
    {
    do
    {
      switch (buf[i])
      {
        case '\n':
        {
          skip = true;
          redo = false;
          break;
        }
        case '|':
        {
          G = atoi(fin);
          //Serial.print(G);
          i++;
          redo = false;
          break;
        }
        default:
        {
          fin[j] = buf[i];
          i++;
          break;
        }
      }
      j++;
    }while(redo);
    redo = true;
    j = 0;
    }

    if (skip == false)
    {
    do
    {
      switch (buf[i])
      {
        case '\n':
        {
          skip = true;
          redo = false;
          break;
        }
        case '|':
        {
          B = atoi(fin);
          //Serial.print(B);
          i++;
          redo = false;
          break;
        }
        default:
        {
          fin[j] = buf[i];
          i++;
          break;
        }
      }
      j++;
    }while(redo);
    redo = true;
    j = 0;
    }

    if (skip == false)
    {
    do
    {
      switch (buf[i])
      {
        case '\n':
        {
          Bright = atoi(fin);
          //Serial.println(Bright);
          i++;
          redo = false;
          break;
        }
        default:
        {
          fin[j] = buf[i];
          i++;
          break;
        }
      }
      j++;
    }while(redo);
    redo = true;
    j = 0;
    }
  }
}

As Majenko already mention, use a separate power supply.

Use that power to power the LED strip(s).
Use the MCU to control the data and clock lines.
Connect grounds together.

MCU? I'm really new so I don't know what that is. I'm using the SCK and MISO pins. Is that the same thing?

An MCU is a Micro Controller Unit, your Arduino is one (example of an ) MCU.  The SCK is the clock line (Serial Clock) and MISO (Master In Slave Out) are data lines. If you google for SPI  you will find out what SCK and MISO are meant for.

Managing your power budget is a normal part of electronics projects. You can only draw about 500 mA total from the USB port, and less than that from the 5V line if your Arduino is powered from USB. If you drive your Arduino with ≈7V into the barrel connector you might be able to pull a full amp from the 5V rail, but it depends on how hot the voltage regulator gets. The higher the input voltage into the regulator, the more heat you generate for a given amount of current. On a genuine Arduino board the voltage regulator should have an overheat protection circuit, which will cause it to shut off when it gets too hot. Cheap knockoffs may just burn out.
When you start using higher current devices like motors or LED strips, it's usually a good idea to switch to a separate (regulated) power supply for those devices. Tie the ground lines together, and since you use separate power supplies for the Arduino and your other devices, they don't affect each other's supply voltages.

So am I right in this assumption?

Yep.

and If so, what can I do to increase the amount of pixels I can power at full range?

Simple: don't power it from the Arduino. Add a proper external power supply that is capable of providing the current you require.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Why Won't my Serial Read value stay the same
I am trying to write to serial to control the brightness of an LED. When I initially type in a value such as '50' or '100', the LED lights up, but then the 'ppm' value drops down to '10' and just stays there (regardless of what I enter in initially. Any idea why this is occurring?

int ledpin1 = 3;
int pwm = 0;

void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  pinMode(ledpin1, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // reads input to serial monitor
  if (Serial.available() > 0) {
    pwm = Serial.read();
  }

  analogWrite(ledpin1, pwm);
  Serial.print("PWM value is: ");
  Serial.println(pwm);
  delay(1000);

}

When you type "100" you aren't sending the number 100. You're sending the characters "1", "0", "0", and whatever selected line ending you have (CR, LF, or CR and LF).
So if you have CR+LF for your line ending you're reading the numbers 49, 48, 48, 13 then 10.
You need to read the characters as they arrive and group them into a representation of the number (up until you get the line ending), then convert that representation into an actual number.

Reading Serial on the Arduino

"You need to read the characters ..., then convert that representation into an actual number." - Or send just a single byte of value 100 over the serial port, effectively moving the conversion from the arduino to the PC. Which is more appropriate depends on the situation.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Create an a message from two inputs[Programming Help]
I'm a bit new to this and I have the following function that I'm having trouble getting it to compile. The intent is to create a message to write out to a software serial port. Inputs are two int values of Function address and the data passed to the device while the output is a series of char characters
void Create_Message(int Address, int Data)
{
  byte S1Add = 1;
  byte FuCode = 2;
  byte AddHi = Address>>8;
  byte AddLo = Address;
  byte DatHi = Data>>8;
  byte DatLo = Data;
  byte AdDa[] = {AddHi,AddLo,DatHi,DatLo};
  unsigned int crc=CRC(AdDa,4);
  byte CrcHi = crc >> 8;
  byte CRCLo = crc & 0xFF;
 /*U8 Slave Address, U8, Function Code, U16 Address, U16 Data, U16 CRC
 * to
 *[U8 Address Split High, U8 Address Split Low, U8 Data Split High, U8 Data Split Low, U8 Function Code]
 */
 unsigned char cmd[]={S1Add,FuCode,AddHi,AddLo,DatHi,DatLo,CrcHi,CRCLo};

  digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit
  for (int i=0; i< clen; i++)
  {
    RS485Serial.write(cmd[i]);   // Send string someplace
    Serial.write(cmd[i]); //echo back
  }
  digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
}

byte CRC(byte AdDa, int Size )
{
unsigned int crc16 = 0xFFFF;
int pos = 0;
int i = 0;

/*Write CRC*/
  for (pos = 0; pos < Size; pos++) {
    crc16 ^= AdDa[pos];          // XOR byte into least sig. byte of crc

    for (i = 8; i != 0; i--) {    // Loop over each bit
      if ((crc16 & 0x0001) != 0) {      // If the LSB is set
        crc16 >>= 1;                    // Shift right and XOR 0xA001
        crc16 ^= 0xA001;
      }
      else                            // Else LSB is not set
        crc16 >>= 1;                    // Just shift right
    }
  }
  /*Note, this number has low and high bytes swapped,
  so use it accordingly (or swap bytes)*/
  byte crc[]={crc16>>8,crc16};
  return crc;
}

Any help with optomizition would also be greatly appreciated :)

What errors and warnings does the compiler give? Which lines are we looking at?

I downvoted this question because it does not incorporate suggestions from  comments and answer at byte Array to CRC calculation,  your previous question.

I'm voting to close this question as off-topic because it is not an Arduino specific question, it is asking for basic optimisation pointers that would be better answered elsewhere.

This question is better suited for the code review SE site.

If you want help with optimisation then "Code Review" would be the better forum.
Its very difficult to optimise code that's hard to read.  You have used an inconsistent formatting style (which might be because of the post but your failure to fix it indicates a lack of interest in the answers.
You passed all you function arguments by value, you should pass them by constant reference.
You are doing a number of implicit casts, because you have mismatched types.
You are sending a byte to serial.write, what happens if the value is outside of the printable range, it would be better to print this as a hex number.
I assume someone has already pointed out CRC should return a byte*.
As for the algorithm, the code isn't readable enough to comment on that.

Ok, I'll check there, Also I guess I missed something from my previous question as well. In terms of formatting, where can I find style guidelines that would improve my code readability?

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
How to Create a reference to an External Print object
Right now I have an object:
class Dog
{
  public:
    Dog(uint8_t I2c, Stream& feedback);
    void Speak();
  private:
    uint8_t _I2c;
    Stream& _output;
};

Dog::Dog(uint8_t I2c, Stream& feedback):_output(feedback),_I2c(I2c){}

Dog::Speak(){
_output.println("Hi There.");
}

That is currently constructed in my sketch via:
Dog Dug([I2cPort], Serial);
How can I modify my class so that to be compatible with taking either a Serial object or an LCD display (using Adafruit's RGB LCD library )?
Eg:
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();
Dog Dug([I2cPort], Serial);
Dog Sam([I2cPort], lcd);

Additional info:
The LCD in question is mostly used as a UI display in its own library this library refreshes the display every 1.5 sec. As information from speak(); and the UI have similar priority, it is acceptable if one instantly overwrites the other.
I am open to solutions that involve modifying the construction of Dog the only requirement is that I need to be able to indicate print("[something]"); in the Dog.cpp
I'm interested in asking this question on the Arduino SE as I believe there are differences in how you would approach this if the problem was on a traditional computer.

it is not a buffer. only a reference

Noted, edited the question for clarity.

nice. now you put the answer into the questions title :-)

And just like that, it works. Thanks for the magic.

If your class is only writing to the stream you probably want to have your class take a Print object instead of a Stream object.
The Adafruit library inherits from Print.

That can change, I only need this line for feedback to either my COM port (Serial) or to the LCD.

both are derived from Print class. https://arduino.stackexchange.com/questions/52563/syslogappender-for-log4esp/52575#52575


text:
Adding null character to char array
I have this code written and functioning that will write out the chars in cmd to a serial port for an input of ASCII text representing byte values.
void SendCTRL (String &input)
{
  //Adjust Data
  const char *hin = input.c_str();    // Get character array
  int clen = input.length()/2;
  unsigned char cmd[clen+1]; // Leave a byte for null terminator
  for (int i=0; i < 2*clen; i+=2)
  {
    cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1]);
  }

  //Send Data
  cmd[clen] = 0;                     // Null-byte terminator
  digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit
  for (int i=0; i< clen; i++)
  {
    RS485Serial.write(cmd[i]);   // Send string someplace
  }
  digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
}

As the majority of the byte values fed are constant, I'm trying to create similar output for the following code when I feed the function below only the byte values that change frequently:
void Create_Message(int Address, int Data)
{
  //Adjust Data
  Address--;
  byte SvAdd = 1;
  byte FuCode = 6;
  byte AddHi = Address>>8;
  byte AddLo = Address;
  byte DatHi = Data>>8;
  byte DatLo = Data;
  byte AdDa[] = {SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo};
  unsigned int crc=CRC(AdDa,sizeof(AdDa)/sizeof(AdDa[0]));
  byte CrcHi = crc & 0xFF;
  byte CrcLo = crc >> 8;
  /*U8 Slave Address, U8, Function Code, U16 Address, U16 Data, U16 CRC
  * to
  *[U8 Address Split High, U8 Address Split Low, U8 Data Split High, U8 Data Split Low, U8 Function Code]
  */

  //Send Data
  unsigned char cmd[9]={SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo,CrcHi,CrcLo};
  cmd[8]=0; //Null-byte terminator
  digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit
  lcd.setCursor(0, 1);
  for (int i=0; i< sizeof(cmd)/sizeof(cmd[0]); i++)
  {
    RS485Serial.write(cmd[i]);   // Send string someplace
  }
  digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
}

I'm reading the Values written by RS485.write() and, in both cases, the data is good. However, for the 2nd section of code, the Arduino seems to write out the null-byte while it does not write the byte out in the 1st block. If I remove the allocation for the null-byte in the second code, it does not get a response from my device.
I'm guessing that the issue is that I am not setting my null-byte terminator correctly or otherwise missing something (I'm pretty new here XD )
Update: it seems like using sizeof(cmd)/sizeof(cmd[0]) to determine the send length interfered with data transmission when I set this to a constant the code works just fine.

In the second code example, the value of sizeof(cmd)/sizeof(cmd[0]) is 9, due to the declaration unsigned char cmd[9] ...
Thus, the for loop will write out 9 bytes, with indices 0, 1, ... 8.  Due to cmd[8]=0; earlier in the code, the last byte will be zero.  To prevent that, one might instead use the expression  sizeof(cmd)/sizeof(cmd[0])-1 in the for loop:
for (int i=0; i< sizeof(cmd)/sizeof(cmd[0])-1; i++)
   RS485Serial.write(cmd[i]);

Note, this doesn't explain why it should be so that “If I remove the allocation for the null-byte in the second code, it does not get a response from my device”, although practically anything can happen if you say cmd[8]=0; after allocating only 8 bytes of storage.

I was under the impression that cmd[9]={SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo,CrcHi,CrcLo} would make the cmd array equal to {SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo,CrcHi,CrcLo,[unallocated]} so that when I said cmd[8]=0; Cmd would be {SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo,CrcHi,CrcLo,0} Is that not the case?

To clarify, I also removed the cmd[8]=0 line as well (sorry for the confusion)

Perhaps you meant [uninitialized] where you wrote [unallocated].  But no matter, both are wrong.  cmd[9]={SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo,CrcHi,CrcLo} initializes cmd to {SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo,CrcHi,CrcLo,0} because it uses the default initializer for unspecified elements, and the default initializer is 0. See eg an answer to Is there a better way to initialize an array? and also see  C++ array initialization,

In addition to James's answer, to print (or send) a null terminated string you do not have to know the length of the string. Just print the characters till you find the null. So this code works better.
for (int i=0; cmd[i] != 0; i++)
{
    RS485Serial.write(cmd[i]);   // Send string someplace
}

//or

int i=0;
while(cmd[i] != 0)
{
    RS485Serial.write(cmd[i++]);   // Send string someplace
}

Ok, I'll do that

@ATE-ENGE you should have not edited your question. New readers are going to get confused :)

Ok, I'll undo that XD

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Printing the messages having problem in SIM 900A to Arduino
I have added my Arduino code for reading messages from GSM SIM900A using Arduino. But the output is showing something different. Please help me.
#define SERIAL_BUFFER_SIZE 256

char msg;
void setup() {
  Serial.begin(9600);   // Setting the baud rate of GSM Module
  delay(60000);
  Serial.println("AT");
  delay(1000);
  Serial.println("AT+CREG=1");
  delay(1000);
  Serial.println("AT+CMGF=1"); // set SMS mode to text
  delay(1000);
  Serial.println("AT+CMGR=\"ALL\"");
  delay(1000);
  Serial.println("AT+CMGR=\"ALL\"");
  delay(1000);
  while ( Serial.available() > 0) Serial.read();  // removing serial buffer values
  Serial.println("AT+CMGR=1");
  delay(2000);
}

void loop() {
  while (Serial.available() > 0) {
    msg = serial.read()
    Serial.print(msg);
  }
}

This is the output:
+CMGR: "REC READ","+91xxxxxxxxxx","","16/07

Hello Guys i found the issue. Serial.read() function reads only 62bytes. After i have update the serial buffer size in library file C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino\HardwareSerial.H ... It shows the messages which is stored in serial buffer.

Please note that you may want to check/handle the responses on these commands.


text:
ESP01 connected to Arduino can't read from UART while connected from external power source
I have an Arduino Uno connected to a NodeMCU ESP01 module, communicating via serial pins. The NodeMCU is powered from the Arduino's 3.3V pin. My idea is that the ESP01 receives MQTT messages, sends them to the Arduino via serial and wait for the Arduino to reply and then publish MQTT messages back.
If I power the Arduino from my computer's USB, everything works fine.
If I use an external power supply 12V/1A, the ESP01 can publish and receive "standard" MQTT messages (meaning, it does not send messages to the Arduino and does not expect a reply). It just receives and directly replies (no Arduino involved).
The problem occurs if the ESP needs to query the Arduino for a result.
The Arduino is able to read and write (I see the correct text in the console) to the serial port, but the NodeMCU ESP01 has problems publishing MQTT messages. Sometimes it does not publish anything (the ESP probably is unable to read what Arduino sends over serial), sometimes it publishes destroyed characters (random text).
It looks like the current needed by the ESP module is not high enough, but it does not make sense for me, since the external power supply should be able to provide more current than USB. Any ideas?
This is my schematic:

Code:
In my ESP01 I have the following MQTT onMessage listener, If the topic is a query for the Arduino (topic is validated by the handleQuery function), then the topic is sent by UART to the Arduino, which listens for specific strings in the loop function. When the Arduino receives a string, it does some logic and writes a reply back to the ESP via UART (Serial.print()).
After the ESP sends a message to the Arduino, it sets listeners for strings, that end with character %. If the reply from the Arduino is received, then it publishes an MQTT message with the result.
function onMessage(client, topic, message)
    if handleQuery(topic.."+"..message) then
        uart.write(0,topic.."+"..message)

        uart.on("data","%", function(data)
            if data=="quit%" then
                uart.on("data") -- unregister event
            end

            if data ~= "quit%" then
                client:publish(topic.."/response","REPLY:"..data,0,0)
            end
        end,0)
    else
        client:publish(topic.."/response","REPLY: Invalid query",0,0)
    end
end

The reply from the Arduino has the following message format:
 REPLY:<value>%
 quit%

This solution works if the Arduino is connected to my desktop computer's USB. It does not work if it is powered from an external power supply. It seems like the ESP is not able to read what the Arduino wrote to UART with Serial.println() if powered from an external power source.
I have no idea why, because power supply should be able to deliver more current.
Edit:
I use the following Arduino clone: eBay link
I tried to connect the ESP01 to the Arduino's 5V output with a voltage regulator (5V should deliver more current), and again, if the USB is connected, the ESP reads UART messages with no problem. If the Arduino is powered from an external power source, the ESP reads damaged characters. The only difference is that those damaged characters seems to be always the same. So perhaps some coding problems(?) or something like that.
So far it looks like a low current value is not a problem.
Edit 2
I removed from my code print() statement from the ESP/LUA code that I used for "debbuging". It printed to serial some messages for me. It seems that it cleaned traffic on Serial line a little bit.
Now I get most of the time correct characters, but the first character is missing, so instead of:
LOW% I get OW%
HIGH% I get IGH%
29.53% I get 9.53%
And from time to time I get String =]�quit%.
Perhaps some input buffer has a problem(?).

Please post a circuit diagram or schematic. Also include your code.

3.3v pin on the Uno is only rated for 50mA. You should provide a power supply that can provide at least 200mA.

@gre_gor but why it works when Arduino is powered from USB?

As @gre_gor mentioned, the Arduino UNO is incapable to provide more than 50mA The fact that it is working on most of USB-TTL is that those one can deliver more than 300mA.

You cannot electrically connect Arduino pins 0 and 1 to both the ESP8266 and the serial monitor at the same time.  You'll have to chose on or the other, or move the ESP8266 to other pins.

@ChrisStratton I dont want to use serial monitor regularly, only for "debuging". Then I see at serial monitor only what Arduino prints to ESP01, I do not enter any commands there.

The arduino outputs and should receive a 5v I/O signal.  The esp8266 uses 3.3V i/o signals.  The 3.3 v output from the esp8266 may not be adequate for this.  I also agree with others that the arduino 3.3v supply to the 8266 is not sufficient. The wifi seems to draw quite a bit of juice. In my latest project I used a esp8266 adapter that I found on amazon.  It converts the supply 5V to 3.3 as well as the i/o voltage to and from the 8266, as well as giving breadboard compatible pins.  Look for esp01 adapter.  Around $5 if I remember correctly.

Another thought....  on the esp8266 I had to change the baud rate to get it do get proper data.  After you can see esp8266 in the serial monitor at 115200, command to change baud is: AT+UART_DEF=9600,8,1,0,0

Can I just check when you plug your 3.3V ESP into a 12V power supply it stops working?  Is there a burning smell when you do this?  Are you using anything to drop the voltage to 3.3V?
You also say you are connecting the ESP to the Arduino's 5V supply.  Normally that's not a good idea either.
Also have you tied the ground of the Arduino to the ESP/12V PSU?  If the two devices don't share a common ground then they won't agree what 0V and so won't be able to talk to each other over serial.  Just run a wire from the Gnd on the Arduino to the Gnd on the ESP and they will jump into life.

Use a proper level shifter on the RX and TX lines. You probably are marginal as far as signal level.
The problem is not the voltage into the ESP8266. It is the level out of the TX of the ESP8266 not being high enough for the Uno CPU. This marginal voltage can cause messed up characters. Often we can get away with it at this level but it is really a marginal situation. It is not a reliable thing to do.
Specification for Vin high is 0.7xVcc. 0.7 x 5.0v = 3.5 volts !!!!
Using a 3.3 volt level signal will often work into 5 volt logic but not always. I had learned this the hard way. I designed a medium run product that used a 3.3v derived TX signal into the 5 volt logic RX input. Worked fine in 30 prototypes. But about 20% failures when running a production order. Different batch of chips resulted in different high trip point.
Just because the practice of using 3.3volt logic into 5 volt CPUs is common it is NOT guaranteed to work. Read the spec sheet! Do the math.

there is a voltage divider to esp8266 RX pin on fritzing in Question. it is enough

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review

Uno will read 3.3 V as HIGH. always. official shields use it. for example Ethernet Shield for Wiznet chip and for SD card SPI MISO

@Juraj  It does NOT always work. It often works. It is a very poor practice that marginally works.

sorry, you are right. and the Ethernet shield has level conversion for MISO lines


text:
FastLED int + float problem
I'm working on a code based on PaletteCrossfade.ino example. But I found the motion speed too fast. It's stated in this:
  static uint8_t startIndex = 0;
  startIndex = startIndex + 1; /* motion speed */
  FillLEDsFromPaletteColors(startIndex);
  FastLED.show();
  FastLED.delay(1000 / UPDATES_PER_SECOND);
}

void FillLEDsFromPaletteColors( uint8_t colorIndex) {
  uint8_t brightness = 255;
  for( int i = 0; i < NUM_LEDS; i++) {
    leds[i] = ColorFromPalette( currentPalette, colorIndex + sin8(i*16), brightness);
colorIndex += 3;

Since the startIndex defined in uint8_t, it cant be lower than 1. So I used float and set it to 0.2 in my code. Which seems to work, and animation slowed down. However I'm not sure how is that float value added into the ColorFromPalette function.
Its documentations states:

CRGB  ColorFromPalette (const CRGBPalette16 &pal, uint8_t index,
  uint8_t brightness=255, TBlendType blendType=LINEARBLEND)

To my understanding it accepts only integer, and also int based sin8 being added to float value. So, what exactly happens there? Is this method viable, or is there any better way to slow down the animation?
I'm thinking about adding a millis() based delay and only increasing the colorindex every 2-3 seconds or so.

Why don't you just use lower UPDATES_PER_SECOND?

I've tried, but even at 30 its faster than setting the index to 0.1, and also prevents faster animations.

"But i found the motion speed too fast. its stated in this:" "and also prevents faster animations. " I'm confused what do you want?

Change FastLED.delay(1000 / UPDATES_PER_SECOND); to FastLED.delay(1000); and tell me what happens or change #define UPDATES_PER_SECOND 100 to #define UPDATES_PER_SECOND 1

The code you have seems to fill the lights with a colour and change every nth of a second.  You could control that to change every 1ms to 2^16ms (which is 65 seconds) just by changing the FastLED.delay() value.
sin8() might return a float or I suspect an int, but colourIndex is an uint8_t so that is a whole number.  All it is doing is picking a colour, based on some scheme.  If the value passed to the function is a float i.e. 1.611 then it will be converted to an int by taking just the whole number part, in this case 1.  It does not round up.
Its not clear what you are trying to do.
If you are trying to slow the rate that the LEDs change colour, you need to change the delay statement.
If you want to smooth the transition between colours you need to change in the area of the sin8 statement, but what you change it to will depend on what your palette is loaded with.
Hope that helps, if not please can you try and describe what it is you are tying to achieve.

In order to change the update rate you have to change it.
You have two choices in ColourPalette example:
1st:
LINE 10
#define UPDATES_PER_SECOND 100 // higher number means more frames a second

2nd:
LINE 58
FastLED.delay(1000 / UPDATES_PER_SECOND); // change it to:
FastLED.delay(2000); //2000ms means 0.5 frame per second or 1 frame every two seconds


text:
Can you output to D+ and D- so that Arduino Uno can be used as a USB device?
My project is basically a set of 5 audio signals (analog) that get altered slightly by Arduino Uno. I convert to MIDI and would then output it to USB, so that it can be used in a program of my choice on the computer. I found a vaguely similar project online with a guide. In that project they write a serial to a MIDI out, and then plug that into a computer. I'm fairly sure I can't just use the TX and run that into the USB, that wouldn't work. So I'm looking for an alternative method.

Not directly, and not in the way you're thinking of.

Would it be better to use the digital output to connect to a midi connection, or do you need it to connect to USB?

Look into V-USB.

Andy, I can not figure out what you are trying to do.  Are you going from an Arduino to a computer using the computer's USB port?  If so, why are you converting to MIDI?  Also, USB is really complex.  Most people do not realize there are many protocols inside a USB signal.   Simply having a USB device is in no way a guarantee that any given program will even work with that device.

Why not just use the Uno's USB port?  The same one used for programming.  I use them all the time to communicate measured values back to Raspberry Pis and to receive commands that trigger output pins...  And the best part is that I can WiFi into the Rpi with RDP and run the IDE to preprogram them out in the field.  In other words, why reinvent the wheel?  That USB-to-serial port works fine bidirectionally already using the Serial functions.

Not with an Uno, no. You can only use USB Serial (CDC/ACM) through the on-board USB chip[1].
Your best bet is probably with a Teensy 3 (or 3.1 or whatever they are up to now) which has built-in support for USB MIDI emulation.

1: I believe there is MIDI firmware for the USB chip on the Uno, but installing that requires a hardware programmer and then breaks the normal sketch upload.

Actually, you can come "close enough" with an Uno by using a V-USB.

@ChrisStratton If you are masochistic enough, sure. Personally I wouldn't touch it even with someone else's barge pole.

It's not without concerns, but it seems to be rather exactly what the question is asking about.

I refuse to endorse it or ever tell anyone to use it.

As noted in Majenko's answer, an Uno would require some non-trivial modifications before it would be usable as you want.
Some Arduino models – Leonardo and early Pro Micros – were based on ATmega32U4 chips instead of ATmega168 or ATmega328 chips.  The 32U4 has USB support built in.  The Mouse and Keyboard libraries allow interacting with a host computer such that from the host the Arduino looks like a mouse or keyboard.

Its rather odd for you to call these "old" as they were all released after the Uno.  Also the Due did not use an ATmega/AVR but rather an Atmel ARM Cortex-M3 while the Zero has a Cortex M0+.

The simpler thing would be to output the MIDI through the serial port, and then convert that into MIDI voltage levels like this:

Then plug that into a suitable MIDI-to-USB adapter. However I would have thought that that extra step (converting to MIDI voltage and back again) would be unnecessary. Can't your computer read MIDI directly from serial? I mean, the Uno has a USB interface. If you send MIDI data at 31250 baud, how is the program on the PC going to know it isn't a real MIDI device on the USB port?

Operating systems expect midi-over-USB devices to identify themselves as such, not as serial or modem devices.

@ChrisStratton  Yes but a MIDI to USB adapter would surely do exactly that? I wasn't talking about putting serial straight into the computer. I mean, that's what they are made to do.

"Can't your computer read MIDI directly from serial?" does rather imply getting it to treat an everyday serial stream as midi data - something that is possible, but outside of typical software configuration, ie, it probably needs a custom or obscure driver, or to skip any operating system MIDI support entirely and just take the data into the application that wants to use it.

@ChrisStratton Oh, OK. My suggestion of the MIDI to USB adapter would not have that issue. You are probably right about the drivers. I see such adapters are available on eBay for around $US 7 to $15.

Yes, something that's USB information presents itself as a MIDI device should work for the host meaning the challenge is electrical.  While something that presents as a serial device (and has a TTL inteface) is Arduino-friendly electrically, but would require atypical host drivers or software to be treated as a source of midi data.


text:
Cannot connect Mega to COM 9 but okay with other COM ports
I previously had issue updating code to Arduino Mega (clone). This is a continuation of this issue, but I think it should be made as separate thread.
After some time spending with it. Turns out if I change my USB port and connect it another USB port, the Mega is detected in port COM 6. I can upload code to the Mega using this COM port (COM6), although it shows an error sometimes. But if I change it back to the previous USB port (here the Mega detected as connected in COM9), I can't upload anything. You can see the error message in the above link.
I also have a Uno and tried uploading code to it through the same USB port (here it is detected as COM8), I can upload code.
I used the working COM (COM6) to upload Marlin FW to the Mega and I can connect my printer through the same COM port, but if I try it through COM9 I can't connect.
So why can't I use COM 9?
PS: I've been COM9 being used to communicate with the same Mega.

disconnect the arduino from your computer .... go to device manager in windows ... click view ... show hidden devices ... find COM9 and delete it .... plug the arduino back in and test the upload

Did that, i even uninstalled COM9. Still can't work with COM9

this is not an Arduino issue ..... i would say that it is some weird windows issue .... possibly something to do with the USB controller ... the two USB ports may be on different controllers .... you may also have an invalid device install file that windows is using to set up COM9 on that particular USB port

Is there anything I can do about this?

Install Unix on your PC?

This isn't really an Arduino question, it's more of a Windows question.

Check to see if you have !!! In your code. This will fail the upload.
More details here:  http://net-forces.blogspot.ca/2017/08/arduino-upload-timeout-and-in-string.html?m=1

It happens with whatever code I use (I tried arduino example codes). Like I said in the post, If I change COM port same code can be uploaded. but not with COM9.


text:
Linkit One- Connect rc522 rfid with linkit one
Linkit One is a board based in Arduino by mediatek.
I am trying to connect a rfid reader with it link
I am trying from past 3 days to get it working, checked my code wiring but nothing seems to get it working.
The reader is perfectly working because i tested it on raspberryPi and it worked flawlessly.
In my linkit board i am able to detect the reader but card is not getting scanned.
I am using this library GitHub
and my code is fairly simple one
#include <SPI.h>
#include <MFRC522.h>
#define RST_PIN 9   //
#define SS_PIN  10  //
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance
void setup() {
Serial.begin(9600); // Initialize serial communications with the PC
while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522
ShowReaderDetails(); // Show details of PCD - MFRC522 Card Reader details
Serial.println(F("Scan PICC to see UID, type, and data blocks..."));
}
void loop() {
// Look for new cards
if ( ! mfrc522.PICC_IsNewCardPresent()) {
return;
}
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial()) {
return;
}
// Dump debug info about the card; PICC_HaltA() is automatically called
mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
}
void ShowReaderDetails() {
// Get the MFRC522 software version
byte v = mfrc522.PCD_ReadRegister(mfrc522.VersionReg);
Serial.print(F("MFRC522 Software Version: 0x"));
Serial.print(v, HEX);
if (v == 0x91)
Serial.print(F(" = v1.0"));
else if (v == 0x92)
Serial.print(F(" = v2.0"));
else
Serial.print(F(" (unknown)"));
Serial.println("");
// When 0x00 or 0xFF is returned, communication probably failed
if ((v == 0x00) || (v == 0xFF)) {
Serial.println(F("WARNING: Communication failure, is the MFRC522 properly connected?"));
}
}

This program in theory should detet reader and when card is scanned should display the UID.
I am getting msg that my card is v2, so its detecting the reader but not reading the card.

Same problem here. It seeems there is a problem writing to registers. the self test of the chip returns false.

This link worked for me:
http://www.grantgibson.co.uk/blog/wp-content/uploads/2012/04/ggrfid_en_ino.txt
Found it in a forum:

Please have a look at this ino file
  http://www.grantgibson.co.uk/blog/wp-content/uploads/2012/04/ggrfid_en_ino.txt
  this ino file works with my reader  but this rc522 library does not
  https://github.com/miguelbalboa/rfid  I want to know the difference as
  i was not able to spot any, one works and another does not.
Please let me know if there is any editing to be done so to get
  https://github.com/miguelbalboa/rfid this working

my friend, i have some problems with version 2.0 trying to read some cards. i think that the problem when  u cant read the card is this version . i have both version 1.0 and 2.0, version 1.0 detect all card type, and 2.0 some not.
for me is a big problem because, here in argentina i only found version 2.0. maybe change on library some.

This is not even an answer, its just going along with question.


text:
Reading from SD and save it in an array
I have a text file with an IR raw code that I need to read from the SD in order to send it and I don't know how to do it. I tried to use the read file function from the specific SD library but it didn't work.

irsend.sendRaw(irSignal, sizeof(irSignal) / sizeof(irSignal[0]), khz);

I want to save the code from the SD in the irSignal so I can sent it. Any ideas?
The code I've tried
#include <SPI.h>
#include <SD.h>

#include <IRremote.h>

IRsend irsend;

File myFile;

int k=0;
unsigned int irSignal[227];

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

  Serial.print("Initializing SD card...");

  if (!SD.begin(53)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  myFile = SD.open("sc_17.txt");
  if (myFile) {
    while (myFile.available()) {
      int val = myFile.parseInt();
      Serial.println(val);
      irSignal[k]={val};
      k++;
    }
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening dc_17.txt");
  }
}

void loop()
{
  int khz = 38;
  irsend.sendRaw(irSignal, sizeof(irSignal) / sizeof(irSignal[0]), khz); //Note the approach used to automatically calculate the size of the array.
  sendSignal();
  delay(2000); //In this example, the signal will be repeated every 5 seconds, approximately.
}

The problem is when I try to implement it in a separate function, because I need to call it for more files, it doesn't work.

What is the code you used for reading from the SD card (the read file function), and what exactly means ' it didn't work' ?

I will add the code to the question and modify it

shouldn't it be: irSignal[k]=val; ?

show the not working code

I added to the question. I put the code from the setup and the one from the loop in a separate function and it worked. Thanks !


text:
How to actually concatenate two Strings?
I'm using the SPISlave library, and I have the following code snippet:

String arg;

SPISlave.onData([arg](uint8_t *data, size_t len) {
  data[len] = 0;
  arg += String((char *)data);
  // ...
}

The compiler doesn't like my string concatenation, though:

/home/lars/sketch_apr01a/sketch_apr01a.ino: In lambda function:
  sketch_apr01a:65:12: error: passing 'const String' as 'this' argument
  of 'String& String::operator+=(const String&)' discards qualifiers
  [-fpermissive]
         arg += String((char *)data);

I've tried other versions as well, with similar results:

arg.concat((char *)data)
arg = arg + String((char *)data)
arg += String((const char *)data)

So how exactly do I write this unusual operation?

Funny, on avr-g++ it's fine (with warnings about store duration). Anyway, you are capturing the arg variable by value, so it won't affect variable outside lambda function.

Your lambda is capturing arg by copy, which is most certainly not what
you want. And since it doesn't have the mutable qualifier, the
captured parameters are not modifiable. Hence the compiler error.
You could get rid of the error by qualifying the capture as mutable,
but you would then be modifying the captured copy of arg, not the
original one. The correct solution would be to capture the String by
reference instead of capturing by copy. See Lambda
expressions.
But then, I concur with Michel Keijzers that avoiding Strings altogether
is a better option.

Makes perfect sense, thanks!

Thanks for the insight and correct answer too (upvoted)

Actually for such string concatenation (which is in a function that may be called a lot), this could result in memory fragmentation, an on most Arduinos the memory will be soon too scattered that no useful memory is left.
Instead, it's better to create beforehand a buffer with the maximum size of the string you want to handle, like:
static const int MAX_BUFFER_LENGTH = 256;

char buffer[MAX_BUFFER_LENGTH];

And use the function strcat or strncat for concatenating two strings; there are generic C functions.

Fair enough, and good advice in general.  But I'd still like to know the answer to my question. :-)

I wonder what error you get when using concat (cannot be a String passing operation error). Maybe some casting to const.

#include <stdio.h>

static const int MAX_BUFFER_LENGTH = 32;
char buffer[MAX_BUFFER_LENGTH];

sprintf(buffer, "%s%s", string1, string2);


text:
can't power up arduino from dc jack
Yesterday I was working on Arduino based bluetooth car. I was using adafruit motor shield v1. Arduino and shield were on same power supply(11v li-ion cell battery). Every thing was fine. I decided to add some leds to my car. I connected two leds with 5v on shield pins(leds were in series and were multi-colored so 5v was okay). It worked for sometime but later it stopped working. Green led on arduino was on while other were off. I disconnected shield and supplied arduino from dc jack, same result. Then I connected arduino with usb cable then everything was fine. Now it works because I supply arduino from usb and shield is working too either from usb supply or external supply. What could possibly go wrong?

it was 11.70 as measured with multi-meter

i tried but voltage on shield 9v header was okay

bad voltage regulator probably

Thanks for adding the image of your Arduino Uno R3.

It would appear that the output of the power regulator pin has been vaporized.

From the Arduino R3 schematic we see this part as U1 which is an NCP1117ST50T3G power regulator.  Here is that data sheet for that part. From that data sheet we see the physical image of the part.

It appears that pin 2 has been vaporized.  If we look at the schematic of the Arduino R3 we see where pin 2 supplies the regulated power to the rest of the Arduino board and likely any connected electronics.  Note the red "X" indicating the vaporized pin 2.

The schematic and the data sheet both indicate the regulator's TAB is also an output.  If true it is difficult to explain why pin 2 vaporized.  Perhaps this particular version of the regulator does not use the TAB as an output.  Or perhaps the Arduino R3 PCB and schematic do not agree.
Added later...
There has been a comment that U1 (the NCP1117ST50T3G power regulator) may sometimes be manufactured with out the center pin.  Still, if you can power the Arduino R3 using the USB port and unable to power the Arduino R3 using power through the barrel jack, the likely suspects are U1 and D1.  However, to be sure, you would have to check the voltage before D1 and after U1.

I'm confused. How are you posting images of the OPs Arduino? Or are you describing a failure you have seen? Your post is unclear.

@DuncanC, It appears the person asking the question has posted twice.  The second time with a picture.  I advised him in the other post that he should have edited his original post.  I was hoping he would follow through and delete his second post and move his picture to his original post.

how can i delete question asked before

Your second question has been closed so the option to delete it may no longer be available (there are a number of options following your question just left of your avatar).  Every stackexchange web site has slightly different rules tailored for that group.  There are dozens of stackexchanges sites ranging from Arduinos to Law to Physics.


text:
reference to 'File' is ambiguous. Why am I getting this error?
The program is supposed to take photo and store the picture into the SD card with the timestamp.
My Program Code:

#include <SdFat.h>
#include <Adafruit_VC0706.h>
#include <SPI.h>
#include<JPEGDecoder.h>
#include <SoftwareSerial.h>
#include <RTClib.h>
#include <Wire.h>
#include <SD.h>

#define SD_CS D8    //For NodeMCU Kit Set version 1
#define DS3231_ADDRESS  0x68  ///< I2C address for DS3231

SoftwareSerial mySerial (D4, D3); //D4-RX, D3 TX For NodeMCU Kit Set version 1
Adafruit_VC0706 cam = Adafruit_VC0706(&mySerial);
File myFile;  // test file
RTC_DS3231 RTC;  // define the Real Time Clock object

char timestamp[30];
char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
void setup()
{
  pinMode(SD_CS, OUTPUT);

  Serial.begin(115200);
  Wire.begin ( D1, D2); //D1=SDA D2=SCL
  if (!SD.begin(SD_CS))
  {
    Serial.println("SD card is not inserted");
    return;
  }

  Serial.println("SD Card Present");

  // Try to locate the camera
  if (cam.begin()) {
    Serial.println("Camera Found:");
  } else {
    Serial.println("No camera found?");
    return;
  }

  if (!RTC.begin()) {
    Serial.println("RTC failed");
    while (1);
  }

  snapshot();
  //  ESP.deepSleep(0);  //deep sleep mode until RESET pin is connected to a LOW signal
}

void loop() {

}
//------------------------------------------------------------------------------
void snapshot() {
  // Set the picture size - you can choose one of 640x480, 320x240 or 160x120

  cam.setImageSize(VC0706_320x240);        // medium

  //cam.setImageSize(VC0706_160x120);          // small

  // You can read the size back from the camera (optional, but maybe useful?)
  uint8_t imgsize = cam.getImageSize();
  Serial.print("Image size: ");
  Serial.println(imgsize);
  // Serial.println("640x480");
  Serial.println("320x240");
  // Serial.println("160x120");

  Serial.println("Snap");
  delay(2500);

  if (!cam.takePicture())
  {
    Serial.println("Failed to snap!");
  }
  else
  {
    Serial.println("Picture taken!");
  }
  // Create an image with the name IMGxxxx.JPG
  char filename[13];
  strcpy(filename, "IMG0001.JPG");
  for (int i = 1; i < 10000; i++) {
    filename[3] = '0' + i / 1000;
    filename[4] = '0' + i % 1000 / 10;
    filename[5] = '0' + i % 100 / 10;
    filename[6] = '0' + i % 10;
    // create if does not exist, do not open existing, write, sync after write
    if (! SD.exists(filename)) {
      break;
    }

  }
  // Open the file for writing
  File imgFile = SD.open(filename, FILE_WRITE);
  SdFile::dateTimeCallback(dateTime); //Timestamp for file
  // Get the size of the image (frame) taken
  uint16_t jpglen = cam.frameLength();
  Serial.print("Storing ");
  Serial.print(jpglen, DEC);
  Serial.print(" byte image.");

  int32_t time = millis();
  //pinMode(D8, OUTPUT);
  byte wCount = 0; // For counting # of writes
  while (jpglen > 0) {
    // read 32 bytes at a time;
    uint8_t *buffer;
    uint8_t bytesToRead = min(32, jpglen); // change 32 to 64 for a speedup but may not work with all setups!
    buffer = cam.readPicture(bytesToRead);
    imgFile.write(buffer, bytesToRead);
    if (++wCount >= 64) { // Every 2K, give a little feedback so it doesn't appear locked up
      Serial.print('.');
      wCount = 0;
    }
    //Serial.print("Read ");  Serial.print(bytesToRead, DEC); Serial.println(" bytes");
    jpglen -= bytesToRead;
  }
  imgFile.close();

  time = millis() - time;
  Serial.println("done!");
  Serial.print(time); Serial.println(" ms elapsed");
  Serial.println("Storing Time in Textfile");
  myFile = SD.open("DATES.txt", FILE_WRITE);
  DateTime now = RTC.now();
  myFile.print(filename);
  myFile.print(' ');
  myFile.print(now.year(), DEC);
  myFile.print('/');
  myFile.print(now.month(), DEC);
  myFile.print('/');
  myFile.print(now.day(), DEC);
  myFile.print(" (");
  myFile.print(daysOfTheWeek[now.dayOfTheWeek()]);
  myFile.print(") ");
  myFile.print(now.hour(), DEC);
  myFile.print(':');
  myFile.print(now.minute(), DEC);
  myFile.print(':');
  myFile.print(now.second(), DEC);
  myFile.println();
  myFile.close();
  Serial.println("Done");
}
//------------------------------------------------------------------------------
// call back for file timestamps
void dateTime(uint16_t* date, uint16_t* time) {
  DateTime now = RTC.now();
  sprintf(timestamp, "%02d:%02d:%02d %2d/%2d/%2d \n", now.hour(), now.minute(), now.second(), now.month(), now.day(), now.year() - 2000);
  // return date using FAT_DATE macro to format fields
  *date = FAT_DATE(now.year(), now.month(), now.day());

  // return time using FAT_TIME macro to format fields
  *time = FAT_TIME(now.hour(), now.minute(), now.second());
}
//------------------------------------------------------------------------------

The error message is too long so I can only copy paste some parts which I think might be relevant:
    In file included from C:\Users\ACER\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\libraries\SD\src/SD.h:25:0,

                     from C:\Users\ACER\Documents\Arduino\libraries\JPEGDecoder-master\src/JPEGDecoder.h:56,

                     from C:\Users\ACER\Desktop\Arduino IDE\Snapshot NodeMCU with RTC\Snapshot_NodeMCU___RTC\Snapshot_NodeMCU___RTC.ino:4:

    C:\Users\ACER\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\libraries\SDFS\src/SDFS.h:190:5: error: 'sdfat' does not name a type

         sdfat::SdFat* getFs()

         ^

    C:\Users\ACER\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\libraries\SDFS\src/SDFS.h:215:5: error: 'sdfat' does not name a type

         sdfat::SdFat _fs;

         ^

    C:\Users\ACER\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\libraries\SDFS\src/SDFS.h: In member function 'virtual bool sdfs::SDFSImpl::exists(const char*)':

    C:\Users\ACER\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\libraries\SDFS\src/SDFS.h:98:27: error: '_fs' was not declared in this scope

             return _mounted ? _fs.exists(path) : false;

                               ^

    C:\Users\ACER\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\libraries\SDFS\src/SDFS.h: In member function 'virtual bool sdfs::SDFSImpl::rename(const char*, const char*)':

    C:\Users\ACER\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\libraries\SDFS\src/SDFS.h:104:27: error: '_fs' was not declared in this scope

             return _mounted ? _fs.rename(pathFrom, pathTo) : false;

                               ^

    C:\Users\ACER\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\libraries\SDFS\src/SDFS.h: In member function 'virtual bool sdfs::SDFSImpl::info(fs::FSInfo&)':

    C:\Users\ACER\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\libraries\SDFS\src/SDFS.h:113:26: error: '_fs' was not declared in this scope

             info.blockSize = _fs.vol()->blocksPerCluster() * 512;

reference to 'File' is ambiguous

    //There are a lot of '???' not declared in this scope and 'sdfat' does not name a type error.

At first, there was a different error that states that SdFile::dateTimeCallback(dateTime); is not declared. After doing some research online, I tried to install SdFat library here to see if it helps
and after installing I got more error as shown above.
How can I solve these errors?

Are these the very first errors reported by the compiler? Anything that follows the first ones may be noise.

Why are you trying to use both SdFat and SD?

Before, I was using SD only but the error SdFile::dateTimeCallback(dateTime); is not declared comes out. I when online to see if there are only solution and I ended up downloading the SdFat library and use it. It got rid of the error but now I have all the other errors coming out.


text:
Make Sure \n is the last character in serial string
I have an Arduino that I've put between a computer and an RS485 device. The job of the Arduino now is just to transmit data but will eventually do data logging and have a small user interface as time goes by.
So far, this serial read code has worked for me to communicate to the Arduino from the computer:
 void serialEvent()
 {
  while(Serial.available())
  {
    // get new byte
    char inChar = (char)Serial.read();
    if (inChar == '\n')
    {
      stringComplete = true;
    }
    else
    {
      inputstring += inChar;
    }
  }
 }

The downside here is that I cannot send the '\n' char to my RS485 unit. Is there a way I can refine the code so I can send an arbitrary string of chars while still having a termination [thing] to turn on the stringComplete flag?
EDIT To clarify this the process by how my message string is being created:
Input: U16 Address, U16 Data, U8 Function Code
U16 Address -> U8 Address Split High, U8 Address Split Low
U16 Data -> U8 Data Split High, U8 Data Split Low

U8 Array of [U8 Address Split High, U8 Address Split Low, U8 Data Split High, U8 Data Split Low, U8 Function Code]

U8 Array -> Message String

Output: Write Message String

Is it just strings of ASCII characters (codes 32 to 127 + \n) that you want to send?

No, I'm sending n number of u8 ints (words?) that are represented as \code characters put together to form a string.

But the actual string content that is sent over the wire only consists of printable characters? You're sending such things as \024\075\216\030\777\000\123 etc?

Or are you sending the actual 8 bit values that you have put into the string using '\whatever`?

Right now, I'm sending and receiving the actual 8bit values the entire process is as follows:
Computer
Input: U16 Address, U16 Data, U8 Function Code
U16 Address -> U8 Address Split High, U8 Address Split Low
U16 Data -> U8 Data Split High, U8 Data Split Low
U8 Array of [U8 Address Split High, U8 Address Split Low, U8 Data Split High, U8 Data Split Low, U8 Function Code]
U8 Array -> Message String
Output: Message String

Since you are using all 8 bits of the serial data for your data there is nothing "in band" that you can use for a delimiter.
Instead you will have to think outside the box somewhat and create some form of "out of band" data that can signal the end of a packte.
One option (probably the simplest) would be to include the concept of time into your protocol.  If you go more than X milliseconds (X is to be determined by you) without receiving a byte then you are at the end of your packet. This has the disadvantage that it slows down your maximum packet rate, since each packet has to have a suitable delay between them.
Another option may be to use a serial break character between packets. This is a special event where the UART output is held low for at least 10 symbol lengths, which results in an framing error (the STOP bit is wrong) and a flag being set. It would mean though that you have to implement all the UART code yourself since the Arduino's UART code doesn't support breaks.
A third option, which also would require you to write your own UART code, or alter the Arduino UART code, would be to operate the UART in 9-bit mode. You then have 0-511 instead of 0-255, so you can send your 8-bit data as per normal (with the 9th bit set to 0) and any control and protocol characters with the 9th bit set, so between 256 and 511.
Finally, you could halve your overall transmission speed by sending the data as ASCII-encoded HEX digits. That would be two characters (0-9,A-F) for each byte sent, leaving all the other characters (including \n) available for you to use as you wish.

Normally strings end with a '/0' item ... than /n is part of the string and can be handled as normally.
So you have to change the check to
if (inchar == '\0')

Also consider not adding a character every time to the string, since it will cause the string to be replaced/copied every time, which is not good for both performance and memory gaps resulting.
Instead make a predefined buffer if possible (if you know the maximum string length, don't forget to add +1 for the ending '0' character). In that case you can add the '\0' yourself or even better:
char inputString[101];
uint8_t inputStringLength = 0;

while(Serial.available())
{
    // get new byte
    char inChar = (char) Serial.read();
    inputString[inputStringLength++] = inChar;

    stringComplete = (inChar == '\0')
}

Serial.avilable() returns the number of bytes available in the buffer. One solution could be to try reading that many bytes at a time. This assumes that the buffer contains only entire strings.
Note: If your RS485 device sends multiple, non-delimited strings between buffer reads then this may not work as desired.
void serialEvent()
{
  int bytes = Serial.available();

  if ( bytes == 0 ) // empty buffer, bail
    return;

  for (; bytes > 0; bytes-- )
  {
    // get new byte
    char inChar = (char)Serial.read();
    inputstring += inChar;
  }
  stringComplete = true;
}


text:
Recursive list of files on SD card with indexing
I'm trying to create a way to make a recursive list of the long name of files from an SD card with an index so that I call the file I'd like. Right now, I'm having trouble getting the files to list (!CFile.open() is always returning true regardless of the number of files on the card)
#include<SPI.h>
#include "SdFat.h"
#include "FreeStack.h"

// SD card chip select pin.
const uint8_t SD_CS_PIN = 10;

SdFat sd;
SdFile file;
SdFile dirFile;

// Number of files found.
uint16_t numberOfFiles = 0;

// Position of file's directory entry.
uint16_t dirIndex[300];
//**Is there a way I make an array without allocating the size here?
//------------------------------------------------------------------------------
void setup()
{
  Serial.begin(38400);
  while (!Serial) {}

  // Initialize at the highest speed supported by the board that is
  // not over 50 MHz. Try a lower speed if SPI errors occur.
  if (!sd.begin(SD_CS_PIN, SD_SCK_MHZ(50)))
  {
    sd.initErrorHalt();
  }
  if (dirFile.open("/", O_READ))
  {
  Serial.print("Reading: ");
  Serial.println();
  printDirectory(&dirFile, 0);
  }
}
void printDirectory (SdFile* CFile, int numTabs)
{
  while (file.openNext(CFile, O_READ))
  {
    if (file.isHidden()||file.)
    {
      //file hidden, skip
    }
    else
    {
      for (uint8_t i = 0; i < numTabs; i++)
      {
        Serial.print('\t');
      }
      if (file.isSubDir())
      {
        file.printName(&Serial);
        Serial.println();
        printDirectory(&file, numTabs++);
      }
      else
      {
        // Save dirIndex of file in directory.
        dirIndex[numberOfFiles] = file.dirIndex();
        // Print the file number and name.
        Serial.print(numberOfFiles++);
        Serial.write(' ');
        file.printName(&Serial);
        Serial.println();
      }
    }
  file.close();
  }

If someone could help me catch what I've got wrong, I'd like to get a second opinion.
Edit: Updated Code
Edit 2: I'm now getting the first level, but the second level is not printing I think I may be doing something wrong with pointers?

dirFile.open("/", ...) opens the root directory which always exist, even if there are no files.
You can check if there are files by checking openNext. If the first call returns false, there are no files or folders.
Some unrelated remarks:

Name variables you use, with more than 1 character (so e.g. numberOfFiles instead of n)
Do not increase a variable inside a Serial.print statement .. if you remove the 'test/debug' code, your sketch behaves differently.

Update:
I now see your question about the array. 300 is probably what you assume is the maximum number of files. Note that if 300 is passed, the sketch will crash.
What you can do to prevent this:

Easy solution: stop storing files after 300. In this case, make 300 a constant.
Solid solution: do not use a predetermined length array. However, this means some disadvantages:

You have to create a list structure and dynamically change the code.
This is slower (probably not an issue since SD card communication is much slower)
It can result in memory gaps, resulting in hard to solve memory problems later if the code is extended and more memory is needed.

I suggest you add some code, to stop storing at 300.

Ok, changing if (!CFile.open("/", O_READ)) to if (!CFile.openNext(&dirFile, O_READ)) has no effect. There seems to be something wrong with the printDirectory function

Hey, I think I updated the code to reflect what you were saying. Can you let me know if you see something else I'm missing?

It's a bit hard to easily see if it's complete ... the best way is to create several empty/non empty sub directories and iterate through them (e.g. running the sketch) and check against the output on Serial.

At least the comment "// THIS is returing true regardless of if there are files on the card should be removed now :-)

Ok, I've updated the code to something that is working better. I think there's still something that needs to be fixed though. XD

@ATE-ENGE if you think there should be fixed something, it's better first to find out what exactly is the problem (of there is no problem found, there is nothing to be fixed).

I saw your additional questions about arrays and updated my answer accordingly


text:
Optimizing Arduino File Selection from SD card
the following code will display the files on an SD card in an Arduino and allow the user to open a file of their choosing. Here's the code with a walkthrough of what it does.
In the Init state, I call the libraries needed to run the code
// Example use of lfnOpenNext and open by index.
#include<SPI.h>
#include "SdFat.h"
#include "FreeStack.h"

// SD card chip select pin.
const uint8_t SD_CS_PIN = 10;

SdFat sd;
SdFile dirFile;
SdFile file;

// Number of files found.
uint16_t numberOfFiles = 0;

This is the area of the real problem, calling SdFile parIndex[50]; Takes a large amount of dynamic memory. For number of files on an SD card, this is a pretty small number, so I need to get at something better
// Position of file's directory entry.
uint16_t dirIndex[50];
SdFile parIndex[50];
//------------------------------------------------------------------------------

In the Setup phase, we make sure the SD card is plugged in and, if it is, we call the function to give the files on the SD card.
void setup()
{
  Serial.begin(38400);
  while (!Serial) {}

  // Initialize at the highest speed supported by the board that is
  // not over 50 MHz. Try a lower speed if SPI errors occur.
  if (!sd.begin(SD_CS_PIN, SD_SCK_MHZ(50)))
  {
    sd.initErrorHalt();
  }
  if (dirFile.open("/", O_READ))
  {
  printDirectory(dirFile, 0);
  }
}

The printDirectory function (This is the part most open to edits, if there's any way to improve performance here, please let me know as well).
void printDirectory (SdFile CFile, int numTabs)
{
  SdFile file;
  while (file.openNext(&CFile, O_READ))
  {
  if (file.isHidden()||false)
    {
      //file hidden, skip
    }
    else
    {
      for (uint8_t i = 0; i < numTabs; i++)
      {
        //create tabs for spacing
        Serial.print('\t');
      }
      if (file.isSubDir())
      {
        SdFile SubDirFile;
        printDirectory(SubDirFile, numTabs+1);
      }
      else
      {
        // Save dirIndex of file in directory.
        dirIndex[numberOfFiles] = file.dirIndex();
        parIndex[numberOfFiles] = CFile;
        // Print the file number and name.
        Serial.print(numberOfFiles);
        Serial.write(' ');
        file.printName(&Serial);
        Serial.println();
        numberOfFiles++;
      }
    }
  file.close();
  }
}

This is the user interface portion, it was largely slapped together as a proof of concept for the above code. As it's written, the code only accepts index values 0-9, but my actual program could call any index value.
void loop() {
  int c;

  // Read any existing Serial data.
  do {
    delay(10);
  } while (Serial.available() && Serial.read() >= 0);
  Serial.print(F("\r\nEnter File Number: "));

  while (!Serial.available()) {
    SysCall::yield();
  }
  c = Serial.read();
  uint8_t i = c - '0';
  if (!isdigit(c) || i >= numberOfFiles) {
    Serial.println(F("Invald number"));
    return;
  }

After making sure that the input value exists, it calls up the arrays that contain the parent's directory SdFile object and the index of the desired file.
  Serial.println(i);
  if (!file.open(&parIndex[i], dirIndex[i], O_READ)) {
    sd.errorHalt(F("open"));
  }
  Serial.println();

  char last = 0;

  // Copy up to 500 characters to Serial.
  for (int k = 0; k < 500 && (c = file.read()) > 0; k++)  {
    Serial.write(last = (char)c);
  }
  // Add new line if missing from last line.
  if (last != '\n') {
    Serial.println();
  }
  file.close();
  Serial.flush();
  delay(100);
}

The main issue I have is that SdFile parIndex[50]; uses 22% of my dynamic memory vs the rest of the program using 12%. How can I rewrite my code to not require keeping the SDFile objects in dynamic memory?
For anyone unfamiliar, documentation for the SdFat library can be downloaded from that link.

Edit:
In terms of use: The SD files are .csv files that store speed and time parameters for running a motor test. Each test lasts for a few minutes to hours.

Do not store the file object. You can find the file again (albeit inefficiently) from its number by starting at the root and doing the same recursive traversal you did in printDirectory().

You have several possibilities:

Do not store the names of all files, but use the index and iterate through all files again. Disadvantage: this takes a lot of time (every time you need the file name)
Add SRAM to the Arduino (e.g. 23LC1024, 23K256), depending on your memory needs. Disadvantage: you have to 'manage' this memory yourself.
If you know something about the file names, you might generate the name. Probably it's not the case, but just to add another option. E.g. if you know that file nr 10 will always be called 'File10.txt', you can 'generate' the name.
I don't know exactly how you want to use the file names, but you might store only the latest x files used, to prevent having to iterate again reading the SD card. Of course, this only helps if there is a high chance the last x files are used more than the non recent files.

Update:
If you need to read the files while leaving the Arduino unblocked, you have to incorporate it in your loop, but don't read all the files in a loop. Something in pseudo code like:
bool readingSd = false; // True between reading first and last file
uint16_t lastTimeRead = 0; // Last time read
void loop()
{
   // Check if file read needed (initial or one hour past, I don't take
   // overflow into account
   if (lastTimeRead == 0 || (lastTimeRead + 1000 * 60 < millis())
   {
      checkReadFile();
   }

   // Perform your normal code... this will run between processing/reading
   // one file/dir.
   ...
}

void ProcessSingleFile()
{
   readingSd = true; // Within reading first/last file
   "read/process ONE file or dir (without containing files)";
   if ("last file read")
   {
       readingSd = false;
       lastTimeRead = millis(); // Move to top to prevent reading time
         // between first/last to take into account
   }
}

Given these options, I think I'd like to use the index and iterate through the files again. I'll only pull a new file from an SD card once every hour or so so as long as it appears to the user to be fairly quick, this sounds like a good way to go for me.

Also ... of course when the SD card content changes meanwhile it will take the newest file names. If really needed, you should not block the sketch while reading, but maybe this is not needed for you.

Ahh! I hadn't thought of that, for this function I think I'll be ok since writing to a file will be rare. Out of curiosity, is there a good way to do the equivalent of a while loop without blocking the sketch? I'm decently new to programming at this level XD

About blocking, that might get tricky. I will mention it (in a rough form) in my answer

Thanks for the edit. I think I'll look to implement something akin to it depending on how long it takes to read the SD card in full (I don't see there ever being more than 1GB of files so it may be alright to have it blocked during reading)

It's much simpler with blocking ... also 1 GB does not matter (unless you really want to READ the file content), but the AMOUNT of files do matter for iterating through them.
(Please acknowledge (make green) my answer if you think it has solved your question).


text:
serialEvent only read 63Bytes and this is not the complete data incoming
hi everybody im working in a software for a pcb based in the chip ATmega2560
im use this with Xbee in API MODE, so im driving short string data and long string data.
with the short data i dont have any problem but my long data is of 78bytes.
so the serial event only show me 63 bytes and i dont find reason for it.
this is the complete block:
void serialEvent2(){
while (Serial2.available()){
    frameReceived[n] = Serial2.read();
    Serial.print("  ");
    Serial.print(frameReceived[n], HEX);
    n++;
    //Serial.print("\t" + String(n));
   /* if (n == (frameReceived[1]+frameReceived[2]) + 4){
        Serial.println();
        Serial.println((frameReceived[1]+frameReceived[2])+4);
        Serial.println("IF");
    }*/
    if ( n == 3 ){
        lfr = frameReceived[2] + 4;
    }

    if (n == lfr){
        receivedDone = true;
        Serial.println();
        Serial.print("[INFO] N: ");
        Serial.println(n);
        Serial.print("[INFO] LFR: ");
        Serial.println(lfr);
    }

    if (receivedDone){
        clearValuesToReceiveFrame();
        processFrame();
        receivedDone = false;
    }
}

Serial.println();
Serial.println("[While]n:");
Serial.println(n);
Serial.println("[While]LFR: ");
Serial.println(lfr);
n=0;
lfr=0;

}
in this block i learn to the programe that the posion 2 in my array is the lenght of the frame in API MODE:
        if ( n == 3 ){
        lfr = frameReceived[2] + 4;
    }

here i learn to the programe that the n number of bytes have to equal lfr (lengh of the data). if this is true my flags gonna work.
        if (n == lfr){
        receivedDone = true;
        Serial.println();
        Serial.print("[INFO] N: ");
        Serial.println(n);
        Serial.print("[INFO] LFR: ");
        Serial.println(lfr);
    }

    if (receivedDone){
        clearValuesToReceiveFrame();
        processFrame();
        receivedDone = false;
    }
}

the problem is that the program only rad 63 n number and my LFR is diferent so the flags never going true, n numbers ever is 63 from 78 real bytes :(
please help me.

serialEvent is called after the loop(). if your loop() takes time, the Serial receive buffer overflows

ok i read about it and yeah it is called to the final row in the loop, but any solution for it?look an another way to get the data?

write the code so that the loop() can loop. slow nested loops can always be integrated into the main loop. function can remember the last state of their work in static variables. If I am not mistaken, your sketch has a function which draws to a display in some for loop. remove the for loop, make the incremental variable static and return from the function after every increment. this way the sketch will multitask, drawing to display and reading Serial in time.

thank you bro, is a little bit hard to implement because i dont see a sample, but i'll try, thankk you


text:
What are the purposes of the different LED lights on a Arduino UNO board?
The LEDs namely L, TX and RX on the board.
Furthermore, whenever the board is connected, the L LED blinks to the frequency of the delay that I set. [Eg: delay(1000);]
If I miss any other LED, do mention their purposes as well!
Thank you

'L' shows the state of pin13 which is programmable by you for any purpose, whether to read or write to an external device, or just for turn the LED on and off as you have done.
'RX' and 'TX' show the states of the Receive and Transmit pins, respectively, and allow you see when serial communication is taking place.

And lastly there is an 'ON' LED, which shows, that the board is powered.

What if I don't use the pin13 and instead use pin12?

You could wire your own LED & resistor to pin12 or any other pin, to get a similar result. But the 'L' LED is hard-wired to pin 13 so that is the only pin it responds to.


text:
Nano clone not working over USB, no data, no power, but can power via Vin (CH340 chip? schottky diode?)
My quite new Nano clone (ATmega328P + CH340G) suddenly stopped working. Plugging it in with USB did not light up the LED(s) nor did it get detected by my machine. I looked it up, and found some how-to's (such as this one: Repair Arduino Nano (no power on USB)), which suggested at least some diagnostics.
So I plugged the Nano in to a 5V breadboard power source using the Vin and GND pins, and the power LED lights up, but connecting via USB cable to my machine does not detect it.
So then I used some of the methods mentioned in the link, and used just a normal jumper cable (without soldering) to check if that could magically make it detectable by my machine. No luck. I tried bypassing the voltage regulator by "jumping" over it, and the power LED gets brighter, and "pin 13" LED flashes for just an instant. The same occurs if I "jump" the voltage regulator all the way to either end of what I am guessing is the "Schottky diode".
In all cases, still nothing in terms of being detected by my computer. The cable is fine because I tested with another nano clone, and it gets detected right away.
So, how do I properly diagnose what is going on here? Specifically how do I fix my poor board? How do I find which component is in need of replacing?

Update:
I found some online guides on how to have another Arduino board talk to this one over SoftwareSerial and found that I could get some data flowing through. However, the text was garbled, such that, for example if I was expecting it to say:

"Please enter some input"

It might read instead:

"Ulease XYZter some [][]put"

Often with the same characters being garbled in the same way. I tested the Schottky diode the way it was suggested in the video (with some guessing as to the multimeter setting I had to use was, since I have a different model than the one in the video), and it seems the diode is fine. So at this point I am guessing it is the ch340g chip that is toasty, either that, or the ATmega chip itself, which I don't know, but that sounds less likely.
So, could it be that it is the CH340G chip, since I get no power over USB, and the TX/RX over serial is being interfered with? Is there anything else I can do to figure out if it is the CH340G that's damaged before I go about trying to replace it?

First you (and we) need a schematic of the board. Without that you're just stabbing in the dark.

If you can't get one, then you will have to trace the flow of power around the circuit using a DMM.

Splash out as spend another $2 on a new clone. The same happened to one of my clones and it is still programmable via ICSP. (NOTE before I get any comments no official "Distributor" in Australia stocks genuine Nano.)

Some clones do not ship with a bootloader. They are basically unusable from the perspective of USB-based programming, until a bootloader is flashed. The only way to do flash a bootloader is to do spi programming, either with a ready-made programmer or with another arduino properly setup. The basic SPI programmer is 5-8 bucks on ebay.

Of course you can use another working one as an ISP to flash the bootloader and fuses.  Checking the voltage on both sides of the diode is a good idea.  Also make sure there are no hairline cracks in the soldering of the surface mount mini-USB connector.  The irony is these are often sold for less than the per-piece price of the ATmega!

@Majenko, I found this: https://www.arduino.cc/en/uploads/Main/ArduinoNano30Schematic.pdf but it would be a ch340g instead of a FT232RL, I believe.

@IgorStoppa I was able to use this board no problem, uploaded several sketches etc, just as I could the other nano clone, and my UNO clone. There should already by a sketch in there from the last time I uploaded one, unless even that got somehow fried off.. is your SPI programming suggestion applicable to this situation?

@ChrisStratton Do you have a link that details how to do that? I'm pretty new to all this stuff. I do notice the mini USB connector is just slightly different at the back than the other clone, but I'm not sure how to tell if this is what is causing the problem, or has anything to do with it.

The Arduino site has a tutorial using a Uno as an ICSP programmer. All you need in addition is a few jumpers and a capacitor. PS my fried Nano clone still powers from USB - using a plugpack, but won't from a PC - presumably because the ch340g is fried.

You could try pushing down on the back of the connector and seeing if that helps.  It's worth the $7 or so to get a 10x jouler's loop for inspecting solder joints.  You can also just try fluxing and resoldering it, but it can be hard to get an iron in there on some of the connector styles.  Resolder the mounting tabs first, in case those are loose.  With some mini-USB's you can carefully break off the back of the shield to get more room to access the pins with an iron.

I don't believe the CH340 is involved in the power situation except possibly for the secondary 3.3v supply which you don't mention using.  USB is 5V power, the board runs at 5V.  If your USB 5V input is not working, and the diode is fine, I would suspect either cracked soldering of the connector, a damaged connector, or a bad cable.  I would only be inclined to suspect the CH340 if the host complains about a USB device drawing excessive current and shuts down the port.  You could carefully measure the voltage on both sides of that diode with respect to ground while the USB is connected.

Either you have a cable problem or that board is just not working well.
What you call the CH340 chip - when they go bad you get power but NO communications, in my experience.  You can test voltages at the various points like 5V, 3.3V, etc., to see if it getting power.  If it is and you're still not communicating, then if it were me it would go on the shelf for the kids to see.
It no longer can trusted.
Rather than troubleshooting the board it would be worth getting another to compare with.
And if you have more than one cable on hand, try them and see if there are any differences.
But my prediction is that a new board will work and this one will continue to not work.


text:
Can I connect more than one IR receiver to an Arduino Uno?
I want to use #include <IRremote.h> to receive information from an infrared remote control. It works perfectly with one IR receiver.
But I want to put three or four IR receivers:
IRrecv irrecv6(pin6);
IRrecv irrecv7(pin7);
IRrecv irrecv8(pin8);
IRrecv irrecv9(pin9);
IRrecv irrecv10(pin10);

And:
void setup() {
  Serial.begin(9600);
  irrecv6.enableIRIn(); // Start the receiver
  irrecv7.enableIRIn(); // Start the receiver
  irrecv8.enableIRIn(); // Start the receiver
  irrecv9.enableIRIn(); // Start the receiver
  irrecv10.enableIRIn(); // Start the receiver
}

Inside the loop function, I am checking each pin to see if there is any data received. But only the last pin (which means pin 10 above) is receiving the data and others are not.

you can connect multiple receivers, but why?

But always only one of them, which is initialized last, is receiving the Data.

@jsotola you could use it to get a very coarse sense of the direction the signal came from.

did you find the solution, because i also want to put 4 ir receiver on Arduino in my fyp. if you have a solution plz help mee.

Try my link
https://github.com/gerivega/Arduino-IRremote I wanted to do the same thing. I modified the latest library to incorporate the changes done by a previous programmer neco777.

That library only supports one IR receiver at a time. Try this fork that seems to have added multiple receivers support.

Just add some delay between irrecv.decode()s and everything will work just fine.


text:
Arduino + nRF24L01 + ESP8266 mod
I was wondering if it is possible to connecting two Arduino boards with each other (Uno + Nano) using an ESP8266 mod on one of them and an nRF24L01 on the other board?
I have seen lots of details of connecting two nRF but couldn't find any about ESP talking to nRF.

No. That would be like trying to connect your TV to your microwave. Both RF devices, but both work different ways and do different things.
Just because they are both rectangular boxes with a window in the front doesn't mean they are the same.

No, that is not possible: the ESP8266 is a WiFi SoC, and the nRF24L01 uses a proprietary protocol.
The fact that they both operate in the same frequency range doesn't matter if the protocols are different.


text:
Reset as I/O pin
I'm looking to minimise the parts count and the power consumption as much as possible and I was wondering if is it possible to store a variable or execute a method when the 'reset' button is pressed?
I didn't find any docs or hints regarding this.
In theory, can it be done with an interrupt?
Edit
In a further research Atmel shows, that if you burn the 'RSTDISBL' fuse (still in theory for me) you can get hold of the reset button by transforming it in a I/O pin with "special" electric characteristics:

Also, if you look at the schematic the reset pin shows that it has what it needs to be an I/O pin:

I say in theory because I really don't know if arduino has the required constellation for this capability and if it comes whit the fuses already burned.

The MCUSR register shows whether there was an external reset (EXTRF bit). But I don't see how you can save power with this. I do see how you could use this instead of needing a button.

Well... MCUSR / EXTRF info in particular would not help a power save, but the answer to what I've asked will.

Yes, there are several possibilities here.
One is detecting state after reset and acting on it.  One of the reasons you might do that would be to shut the processor down all but completely, and let the reset wake it back up.
Another would be to program the reset disable fuse and repurpose it as an I/O pin - of course if you do that, you can only then reprogram the chip if you have implement working functionality to get back to the bootloader (or similar), or if you use a high voltage programmer.
These are in the category of things which make development a lot more difficult, but are sometimes worthwhile as they let you squeeze a little more capability out of the hardware.  If you are just starting a design, you might consider a different chip instead - but if you have existing boards or design investment, and this lets you get the last little bit of needed capability from it, it is possible.

Wait ... What do you mean by a high voltage programmer ?

High Voltage Parallel Programming is described in sections 25.6 & 25.7 of the ATmega48/88/168/328p data sheet.  It involves using a ~12v signal on the reset pin, which allows overcoming fuse settings that might prevent other sorts of programming.  You can buy HVPP programmers from Atmel and others.


text:
Solutions for displays?
I am trying to find cheap options for displays about 3 x 6 inches to display time, weather, simple clip-art type images, and other marquee messages.  What are my best options to work with arduino if my goal is cost-cutting?

2" x 4" or greater in size
40 dpi minimum
readable from 15 feet in normal indoor conditions
everything else is unimportant to me at this point: RGB, pitch, power draw, etc.

Are we talking a LED or LCD display here?

@NickGammon All options are on the table. I just want to keep costs down and have something readable across the room that will work with Arduino. LED displays will always be cheaper, no?

How about just a computer monitor? That would be reasonably large, have high resolution, and could display whatever you want it to. That would only be a few hundred dollars (if that). You could drive it from a cheap PC, or from an Arduino using something like the MicroVGA board. That has 800x600 pixels resolution.
That would be cheaper, and less fiddly, than putting together a lot of LED display modules.
Also see http://playground.arduino.cc/Main/MicroVGA

I would be surprised if a small LCD monitor + MicroVGA board would be cheaper than a dot-matrix or LED display (your other answer).  But your point about it being less fiddly is a good one.

One possible option would be these 8x8 pixel displays.

I got that from eBay for $8.50 (for the 4 modules).
They come pre-assembled, this is the back:

Notice the data direction. You can connect them together like this:

That one (3 lots of 4 modules) is 25.4 cm long (10 inches) and 3.2 cm high (about 1.25 inches).
That's 96 pixels (8 x 4 x 3) in 10 inches, which is a lot less than 40 DPI, but really, if you want to read them from 15 feet away, that is probably OK.
Note: These were single-colour only.

If you want 40 DPI x 6 inches that means you must want 240 pixels horizontally and 120 pixels vertically. That would be 240 / 8 modules horizontally (30 modules) and 120 / 8 vertically (15 modules). That's a total of 450 modules. Since they come in lots of four that would be 116 in total (rounded up). 116 x $8.50 = $US 986.
I don't know if that is what you have in mind by "cost cutting" but that is one option.
You would need to assemble them yourself, connect them together, supply power, and have a suitable driver. I have some code that drives those boards, although I certainly have not tested it with 450 of them at once.
As you can see those boards come with mounting holes on the back, and are designed to be physically adjacent to each other. Mounting 450 of them could be quite tedious. The LED modules on the front pull off to give access to the mounting holes, but it would be a long job.

You can get larger modules, as mentioned in another reply, I expect they would be more expensive, but you would of course get more pixels.
Example: 64x32 RGB LED Matrix - 4mm pitch. That one is 64x32 pixels for around $US 80.
You would probably need 4 of those horizontally (256 pixels) and 4 vertically (128 pixels). Thus, a total of 16 which would cost you around $US 1280. However for that at least you get RGB. Note that the Adafruit page mentions you cannot drive that many pixels with a Uno.

Wow, these are cheap indeed!  I found some for $1 per panel.  Thx for thinking outside of the box.

Also, great link to code.

www.aliexpress.com would be your first go for cheap stuff.
You can always chat with the guys and bargain a bit on the price. Do remember that the free shipping option means that it will take nearly a month to arrive