Go Down

Topic: Char array to integer (Read 1 time) previous topic - next topic


I'm trying to send a command through serial in the format of "L1023" in order to move a motor to the left direction and 1023 speed. My approach is to store the command it to a char array, get the first element of array and then the remaining elements as integer using the atoi function but the results are not the expected. When I enter a sequence of "L100", L200, L300 the last one suppose to run faster but it doesn't. Do you know why? Its getting me crazy this.
Code: [Select]
void loop(){
  index = 0;
  i = 0;
  //Get the serial command and store it to the char array
  while (Serial.available()){ 
    cmd[index] = Serial.read();
  cmd[index] = 0;
  int i = atoi(cmd+1);
  if (index > 0){
    motorControl(cmd[0], i);

void motorControl(char dir, int spd){ 
    if (dir == 'L'){
      //turn left or counterclockwise at spd speed
      digitalWrite(pinA, LOW);
      digitalWrite(pinB, HIGH);
      analogWrite(pinB, spd);
    else if (dir == 'R'){
      //turn right or clockwise at spd speed
      digitalWrite(pinA, HIGH);
      digitalWrite(pinB, LOW);
      analogWrite(pinA, spd);
      digitalWrite(pinA, LOW);
      digitalWrite(pinB, LOW);


May 13, 2011, 10:58 pm Last Edit: May 13, 2011, 11:02 pm by robtillaart Reason: 1
Does the string get read in completely? if L300 gets cut of to L30 it would explain all

What is speed of your Serial? 9600? As at 9600 baud there is approx 1 char per millisecond, you might need to increase the delay(1) to delay(5) or make it adaptive

Code: [Select]
while (Serial.available() > 0)
 cmd[index++] = Serial.read();
 int t = 5;                                   // max 5 millis between chars
 while ((Serial.available() == 0 ) && (t-- > 0)) delay(1);
cmd[index] = 0;
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)


I've increased the delay but still the same problem. The baud rate is at 9600. Something else is the cause that I cannot figure out because when I enter L200 and then L500 then the motor goes quicker than before. How can be sure that the integer value is the right one? I've puted a println function in order to see the value but it doesn't make sense. The 300 speed is lower than the 200 which is not normal.


Isn't the normal PWM range 0 to 255? So, it could be overflow. Instead of 300 you get 45, while the 500 rolls over to 245. Try 255 and 256 and see what happens


It worked!!! The range is 0-255 and not 0-1024 as I thought. This was my confusing due to my little experience.
Thank you for your help.

Go Up