Hardware Reference
In-Depth Information
void loop2()
{
i++;
Serial.print("loop2()");
Serial.println(i, DEC);
delay(1000);
}
void loop3()
{
if (i == 20)
{
Serial.println("Yay! We have reached 20! Time to celebrate!");
}
}
The new function, loop3() , is called in the setup() function and has a single
task; to monitor the value of i and print a message when i reaches the value 20.
Except it doesn't. If you run the program and open a serial monitor, you'll see
there is no output from this sketch, and nothing is displayed on the serial port.
loop1() and loop2() do not print any values, and loop3() does not celebrate
the arrival of the value 20. What happened?
The code is valid; there is no syntax error. Because the code ceased to work
when loop3() was added, it is safe to say that the problem lies within this func-
tion. Time to take a closer look.
It starts with an if statement: if i equals 20, then a message is printed. And
if i doesn't equal 20? Nothing, it just loops. It should work, and on most multi-
tasking systems, it would. Most multitasking systems have a kernel that gives
control to functions and then takes control away after a set period of time, or
number of instructions, or whatever algorithm the system uses. On coopera-
tive multitasking, it is up to the programs (or functions) to play nice with the
other functions and to give control back. The problem with loop3() is that it
continues to run but never gives control back to the other functions. It keeps on
looping waiting for i to reach 20, when i can never be incremented. The other
two functions are still waiting for their turn. To tell loop3() to give control back
to other functions, use yield() .
void loop3()
{
if (i == 20)
{
Serial.println("Yay! We have reached 20! Time to celebrate!");
}
yield();
}
Search WWH ::




Custom Search