tumbleweed
- Joined Jun 27, 2023
- 19
There are two issues with that code...
First, the variables red_timer, green_timer, and yellow_timer should be declared as 'volatile unsigned long' so that the compiler will know they are being modified outside the main loop. Otherwise it may optimize the code out.
Secondly, the three xxx_timer variables are unsigned longs (32-bits). On an 8-bit processor reading/writing them will be non-atomic and require manipulating four bytes. When you access them outside the ISR you have to account for the fact that you might get interrupted right in the middle of reading/writing to them in the main loop. Either disable interrupts around the accesses or write functions to repeat the operation until you get the desired result, ie when writing to the variable repeat setting it until the value reads what you're attempting to write, and when reading read it multiple times until two successive reads are equal.
That way you know you were not interrupted during the operation.
First, the variables red_timer, green_timer, and yellow_timer should be declared as 'volatile unsigned long' so that the compiler will know they are being modified outside the main loop. Otherwise it may optimize the code out.
Secondly, the three xxx_timer variables are unsigned longs (32-bits). On an 8-bit processor reading/writing them will be non-atomic and require manipulating four bytes. When you access them outside the ISR you have to account for the fact that you might get interrupted right in the middle of reading/writing to them in the main loop. Either disable interrupts around the accesses or write functions to repeat the operation until you get the desired result, ie when writing to the variable repeat setting it until the value reads what you're attempting to write, and when reading read it multiple times until two successive reads are equal.
That way you know you were not interrupted during the operation.
