Pages: [1]   Go Down
Author Topic: atoi FAIL  (Read 2243 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 3
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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 smiley-sad

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!! smiley-grin

Best regards, Jonas Hald
Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 3
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Logged

Des Moines, WA - USA
Offline Offline
God Member
*****
Karma: 25
Posts: 779
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
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);
}
Logged

UK
Offline Offline
Faraday Member
**
Karma: 17
Posts: 2884
Gorm deficient
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Or, if you're averse to explicit pointer arithmetic and extraneous variables:
Code:
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);
}
Logged

Per Arduino ad Astra

0
Offline Offline
Newbie
*
Karma: 0
Posts: 3
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Thank you very much!! smiley-grin Both of you!
Logged

Canby, OR
Offline Offline
Full Member
***
Karma: 1
Posts: 158
Arduino rocks
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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

UK
Offline Offline
Faraday Member
**
Karma: 17
Posts: 2884
Gorm deficient
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.)
Logged

Per Arduino ad Astra

Pages: [1]   Go Up
Jump to: