Hi. I have been making a program for reading a string in the serial port, and I got some very rare results.
When I use the Serial in this program, the variable incomingByte was modified propperly when I get some data in the serial port buffer, but when I put the process in a function, and try to change the global variable incomingByte, using pointers or the variable, the value in the variable doesn’t change. Its very weird.
I was using an Arduino Nano V3 and Arduino 1.5.7 IDE (I tried too with 1.0.5 with the same results).
I put the example code and the modified code.
Thanks for the help in advance!!
This is the example, works like a charm…
int incomingByte = 0; // for incoming serial data
void setup() {
Serial.begin(115200); // opens serial port, sets data rate to 9600 bps
}
void loop() {
// send data only when you receive data:
if (Serial.available() > 0) {
// read the incoming byte:
incomingByte = Serial.read();
// say what you got:
Serial.print("I received: ");
Serial.println(incomingByte, DEC);
}
}
The first sketch prints what is received (also the LineFeed and CarriageReturn).
The second sketch keeps printing, no matter if something is received or not.
Why do you feel the need to pass a global variable to a function? If there is a reason for the variable to be global, you don't need to pass it to functions. If the variable is to be local to a function, but shared by another function, it shouldn't be global.
Okay, I try it again, and the results are the same. I try the mod as PaulS said, and here is again. I made a Python program who sends a byte to the serial port and read the answer. The output for this program:
And that should print two lines with the result, right? But never enter in the function if! the output is: " I received: 0" ; " I received: 0" ;" I received: 0" ;" I received: 0" .
Why is that?? Is the same input!
This will wait until it gets something. The while loop is "empty" meaning it doesn't do anything while its waiting. This is usually not a good thing because you might want the Arduino to be able to do other tasks while its waiting.