Serial.read string, number conversion

Dear all,
I would like to read from serial a string (a character followed by a X digits number) as this one for example: c123456.
The number can be between 2 or 6 digit.

void loop() {
...
  if (Serial.available() > 0) {
    
    if(Serial.read() == 'c')
    {   
      int output = intParse(6);
      Serial.print(output);
    }
int intParse(int length)
{    
  char BUFFER[length];
  delay(5);
  for(int i = 0; i < length; i++)
  {  
    BUFFER[i] = Serial.read();
  }   
  BUFFER[length] = '\0';
  return atoi(BUFFER);
}

This works with numbers with digit < 5 otherwise it will truncate.
Am I missing something from the atoi function?
Thank you for your support,
dk

d82k: Am I missing something from the atoi function?

Check the maximum value a 16-bit int can be.

Also BUFFER[length] = '\0'; is writing into never-never land.

You need to have

char BUFFER[length+1];

Right, I was missing something.

In order so solve I also had to add a delay:

unsigned long intParse(int length)
{    
  char BUFFER[length+1];
  delay(5);
  for(int i = 0; i < length; i++)
  { 
    BUFFER[i] = Serial.read();
    //Serial.println(BUFFER[i]);
    delay(5);
  }   
  BUFFER[length] = '\0';
  return strtoul(BUFFER, NULL, 0);
}

thank you,
dk

Read up on Serial.available() and Serial.flush()...you might be able to get rid of the delay() call.

econjack: Read up on Serial.available() and Serial.flush()...you might be able to get rid of the delay() call.

How would Serial.flush() help?