Need help understanding atoi()

Hey Guys,

Ive already looked at a couple examples and the Documentation but i cant wrap my head around it..

I want to send the positions for 3 Servo motors in Degrees to my Arduino uno seperated by "," using the strtok function which works fine. The problem Im running into is that the conversion from char to int using atoi works in the Serial.println but wont work if i want to copy the value into my int array.

Thank you guys in advance!

#include <Arduino.h>
#include <Servo.h>
#include <string.h>

Servo firstServo;
char Grad[25];
char moveTo[3];
bool OnMove = false;

void setup() {
  
  Serial.begin(9600);
  firstServo.attach(3,500,2400);

  delay(1000);
  firstServo.write(90);
  Serial.println("Booted!");


}

void loop() {
  
  if(Serial.available()){
    Serial.readBytesUntil('\n', Grad, 25);
    
    handleText();
    OnMove = true;
  }
  
}
 
void handleText(){
  
  char delimitor[] =",";
  int i=0;
  char buffer;

  Serial.println("Got Data");
  Serial.println(atoi(strtok(Grad, delimitor)));
  buffer = atoi(strtok(Grad, delimitor));
  moveTo[0] = buffer;
  
  Serial.println(moveTo[0]);

}

The output im getting looks as following:

19:16:32.424 -> Booted!
19:16:34.136 -> Got Data
19:16:34.136 -> 1
19:16:34.136 -> ☐
19:16:34.954 -> Got Data
19:16:34.954 -> 2
19:16:34.954 -> ☐

1 Like

atoi() returns an int, not a char.

1 Like

Instead, try

  Serial.println(atoi(strtok(Grad, delimitor)));
1 Like

Keep in mind that strtok modifies the input string, by replacing the separator character with '\0'. So you can ONLY parse the string from the beginning ONE time. You are doing this once for the Serial.print, and a second time to (incorrectly) set buffer. After the first call, strtok will "see" only the first token in the buffer. Since you are using ',' as a separator, I assume your goal is to parse a string containing multiple integer values separated by commas. To do that, the first call to strtok must contain a pointer to the input string (as you are doing), and all subsequent calls must pass a NULL instead. On each call to strtok you should SAVE the pointer returned by strtok to process each token. If you call strtok passing the input string a second time, it will find ONLY the first token, and any other tokens will not be found.

void handleText(){
  
  char delimitor[] =",";
  int i=0;
  int buffer;
  char *token = strtok(Grad, delimitor);

  while (token)
  {
    Serial.println("Got Data");
    Serial.println(token);
    buffer = atoi(token);
    Serial.println(buffer);
    token = strtok(NULL, delimitor);
}
3 Likes

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.