I am using a Leonardo board and am testing the APIs in the Serial
type. The board is talking to a screen using serial.
The pseudo code is as follows (I show code relevant to Serial):
void setup(void) {
Serial.begin(115200);
}
void loop(void) {
if(Serial.available())
{
if (Serial.find(0x30))
{
func1();
}
if (Serial.find(0x31))
{
func2();
}
}
}
void func1()
{
// Serial.print() used multiple times
asm volatile (" jmp 0");
}
void func2()
{
// Serial.print() used multiple times
asm volatile (" jmp 0");
}
I test using the Arduino IDE (1.8.0) and its Serial Monitor. When I send 0x30 over serial, the first if case gets triggered to invoke func1
, but when I send 0x31, I cannot get the second if case (func2
) to get triggered. This even happens when I test 0x31 first; the second if case never gets triggered. Can someone tell what I am doing wrong here and what is the right way to use serial ?
Edit For testing, one can use the pseudo code itself; I tested using different number of LED blinks in func1 & func2, and the problem still holds.
Edit 2 Based on Dave's answer, I tried a test with serial using sample code from
I did another test where I used the sample loop code for read (https://www.arduino.cc/en/Serial/Read) and tried typing 0 or 1 through serial monitor. I observed the following:
// Typed 0
I received: 48
I received: 13
I received: 10
// Typed 1
I received: 49
I received: 13
I received: 10
1 Answer 1
It is looping faster than the serial is delivered, so each time there is a byte delivered, it tests it against 0x30 until nothing is left, and then drops out, leaving nothing .available() for the next if(), so it fails out as well and starts up the loop() again.
I'd read a byte at a time and work with that:
int incomingByte = 0; // for incoming serial data
void loop(void) {
if(Serial.available())
{
incomingByte=Serial.read();
if (incomingByte == 0x30)
{
func1();
}
if (incomingBute == 0x31)
{
func2();
}
}
-
I tried your approach. Now I can trigger either case, but only once. So after uploading the code, I can try 0 or 1, and either case run fine. But on second try, none of the cases get triggered.Jake– Jake2017年03月06日 19:17:32 +00:00Commented Mar 6, 2017 at 19:17
-
Check my edited question. I did another simple test to see behavior.Jake– Jake2017年03月06日 19:25:55 +00:00Commented Mar 6, 2017 at 19:25
-
I tried removing the
asm volatile
statements fromfunc1
andfunc2
, and the original pseudocode now works. But I need a way to reset the program to the beginning. So I guess my question is whether there is a more stable way to reset the program to PC 0.Jake– Jake2017年03月06日 19:34:55 +00:00Commented Mar 6, 2017 at 19:34 -
That's a different question. Maybe playground.arduino.cc/Main/ArduinoReset would help.Dave X– Dave X2017年03月07日 16:01:21 +00:00Commented Mar 7, 2017 at 16:01