I am working on a sketch that will allow me to control the Arduino from a computer using serial. I have written a program written in Processing that is going to provide the control interface, so I have full control over the Serial link. I have also written a simple sketch in Arduino to test. This sketch is based on the Blink and Serial.available examples. Basically I am just trying to change the blink delay rates using serial commands. Everything works great (I stuck a couple of println() calls in there so I could see what was going on) except when I try to convert my char array (string) to an int. I did some research on the atoi() function, and realize I need to insert a null character at the end of the array for it to be a valid string, and allow atoi() to convert it into an int. I did that - but the function is still returning zero, which from my research means that it is trying to convert an invalid string.
I am stumped...What am I missing?
#define greenLed 7
#define yellowLed 6
String inputString = ""; // a string to hold incoming data
boolean stringComplete = false; // whether the string is complete
int greenDelay = 200;
int yellowDelay = 1000;
char tempChar[10];
int i;
void setup() {
// initialize serial:
Serial.begin(9600);
pinMode(greenLed, OUTPUT);
pinMode(yellowLed, OUTPUT);
}
void loop() {
// print the string when a newline arrives:
if (Serial.available()>0) serialEvent();
if (stringComplete) {
Serial.println(inputString);
switch (inputString.charAt(0)){
case 'A':
for(i=1 ; i<inputString.length() ;i++){
tempChar[i] = inputString.charAt(i);
Serial.println(tempChar[i]);
}
tempChar[inputString.length()] = '\0';
greenDelay = atoi(tempChar);
Serial.print("New Green Delay Value:");
Serial.println(greenDelay);
break;
case 'B':
for( i=1 ; i<inputString.length() ; i++){
tempChar[i] = inputString.charAt(i);
}
tempChar[inputString.length()] = '\0';
yellowDelay = atoi(tempChar);
Serial.println(tempChar[0]);
Serial.print("New Yellow Delay Value:");
Serial.println(yellowDelay);
break;
default:
Serial.println("Invalid Command");
}
inputString = "";
stringComplete = false;
}
blinkGreen(greenDelay);
blinkYellow(yellowDelay);
}
void serialEvent() {
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
// add it to the inputString:
inputString += inChar;
// if the incoming character is a newline, set a flag
// so the main loop can do something about it:
if (inChar == '\n') {
stringComplete = true;
}
}
}
void blinkGreen (int x){
digitalWrite(greenLed, HIGH); // set the LED on
delay(x); // wait for a second
digitalWrite(greenLed, LOW); // set the LED off
delay(x); // wait for a second
}
void blinkYellow (int x){
digitalWrite(yellowLed, HIGH); // set the LED on
delay(x); // wait for a second
digitalWrite(yellowLed, LOW); // set the LED off
delay(x); // wait for a second
}