Go Down

Topic: atoi FAIL (Read 2416 times) previous topic - next topic

HALD

Hey everyone!

I am trying to recieve multiple bytes over serial, store in array, and use atoi to convert to int. However I am getting very different results from atoi :(

Using atoi like this:
if( Serial.available() >= 3 ) {
 rred[0] = Serial.read();
 rred[1] = Serial.read();
 rred[2] = Serial.read();
 char * thisChar = rred;
 int a = atoi(thisChar);
}

Attaching a pic of terminal, so you can se what it outputs.
gratisupload.dk/download/45675/

As you can see, it works after sending 000 command some times, but only once.

Please help!! :D

Best regards, Jonas Hald


lloyddean

Code: [Select]

char    buffer[4];
if ( Serial.available() >= 3 )
{
   char*   pbuffer = buffer;
   *pbuffer++ = Serial.read();
   *pbuffer++ = Serial.read();
   *pbuffer++ = Serial.read();
   *pbuffer++ = 0;

   int     n;
   n = atoi(buffer);
}


Groove

Or, if you're averse to explicit pointer arithmetic and extraneous variables:
Code: [Select]
char    buffer[4];
if ( Serial.available() >= 3 )
{
   buffer[0] = Serial.read();
   buffer[1] = Serial.read();
   buffer[2] = Serial.read();
   buffer[3] = '\0';

   int     n;
   n = atoi(buffer);
}
Per Arduino ad Astra

HALD

Thank you very much!! :D Both of you!

Scott Baker

The short answer is you can do:

char * thisChar = rred;

You'd have to use strcpy or something else to copy the array to the other one.

Groove

Quote
The short answer is you can do:

char * thisChar = rred;

He already is doing that - what's your point?

There's nothing wrong with the code in the OP, except there's no "rred[3] ='\0';" before the "char * thisChar = rred;"  (assuming "rred" is declared as having at least four elements.)
Per Arduino ad Astra

Go Up