Hi, everyone. I'm writing a small demo program for practice (I'm still quite new to the Arduino). What it does is it lights an LED after a certain number of button presses, and it prints messages to the serial port when the button and/or LED state changes. What I'm trying to do is to enable the user to change the interval at which the LED lights by sending a number to the Arduino via the serial port. I've been partially successful:
Welcome to my State Changer Arduino demo!
LED interval is now 3
down
Number of presses: 1
LED unlit
up
down
Number of presses: 2
LED unlit
up
down
Number of presses: 3
LED lit
up
LED interval is now 2
down
Number of presses: 4
LED lit
up
down
Number of presses: 5
LED unlit
up
However, if I try sending a double-digit number, say 23, I get this:
LED interval is now 2
LED interval is now 3
In other words, it's reading the characters individually, rather than as a string.
Here's the function that I wrote to get a string from the serial port:
char* GetSerialString()
{
char string[256];
int index = 0;
while(Serial.available() > 0)
{
/*Read a character as it comes in:*/
char byteBuffer = Serial.read();
if(index < 255)
{
/*Place the character in the string buffer:*/
string[index] = byteBuffer;
/*Go to the index to place the next character in:*/
index++;
}
}
string[255] = '\0'; //Null-terminate the string;
return string;
}
And the section in loop() where I call it:
if(Serial.available() > 0)
{
char* serialInput = GetSerialString();
interval = atoi(serialInput);
Serial.print("LED interval is now ");
Serial.println(interval,DEC);
}
I'm guessing the problem lies in the implementation of GetSerialString(), but I don't know for sure. I thought that what it was supposed to do was to read each byte (character) into "string" and null-terminate it. All I know is that I suck at character manipulation
I apologize if this forum (as in the whole Arduino forums, not just this sub-forum) is a bad place to have this question; it's probably more of a C problem, not an Arduino API problem...