Initially, the sketch was written to accept incoming serial data(0-255) and convert them to integers using atoi function. But it didn't work. So in an attempt to troubleshoot the problem; I have reduced it to the following
char val;
void setup()
{
// begin the serial communication
Serial.begin(9600);
}
void loop()
{
// check if data has been sent from the computer
if (Serial.available()) {
val='5';
Serial.println(val); // outputs value of val to make sure it is 5
int a = atoi(&val);
Serial.println(a);
Serial.flush();
}
}
The value in val should always be '5' no matter what serial data I send right?
I should get the output as
//sent 4
5
5
//sent 8
5
5
//sent any value
5
5
Instead I'm getting :
//sent 4
5
54
//sent 8
5
58
//sent 2
5
52
:-?
BUT, if I move char val; to inside the loop function, the code works correctly.
When I compiled the same code for windows, I get the correct output irrespective of the position on char val;.
The value in val should always be '5' no matter what serial data I send right?
Nope. atoi works on an array of characters not a pointer to a character.
Try this...
char val[glow][2][/glow];
void setup()
{
// begin the serial communication
Serial.begin(9600);
}
void loop()
{
// check if data has been sent from the computer
if (Serial.available()) {
val[glow][0][/glow] = '5';
[glow]val[1] = 0;[/glow]
Serial.println(val); // outputs value of val to make sure it is 5
int a = [glow]atoi(val);[/glow]
Serial.println(a);
}
}
Your code works but the code I posted worked fine when I compiled it for windows using tiny c compiler..
I did some more reading on atoi and, indeed it works on a string(array of chars).
Is there any way to explain how 5 was being concatenated with the number I sent through serial monitor when the variable declaration is outside loop() and not when it is inside loop()?
atoi keeps on reading memory until it reaches a 0. In other words it ignores your variable "boundaries". So after it reads your val variable, it will read whatever is after that. When val is defined outside, it just so happens that the serial buffer is the next variable. When inside, it just so happens that the next memory address contains a 0.
The effect is quite random: the atoi() function happily chewed through whatever random data it found in the memory just after the address you gave it, until it found a '\0'.
Congratulations are in order, as you have independently discovered what is known as the "C buffer overflow".