What you learn today
- Ring buffer in the stack
- Average of the last values
- Show the trend
A single temperature value says little. Is it rising right now? Is that spike just an outlier? For that the chip remembers the last values in a ring buffer: ten fixed slots in the stack that are overwritten in turn.
The ring
A pointer pos says where the next value goes. After every write it moves on by one and jumps back to 0 after the last slot:
poke pos temp
add pos pos 1
mod pos pos SIZE # 9 -> 0
So the newest value sits at pos − 1, the oldest at pos once the ring has been full. Until then the oldest sits at 0. A counter count remembers how many slots are already filled, at most SIZE.
Milestones
- Average of the first values: the LED “Mittel” shows the average of the temperatures stored so far in °C, even if the ring is not full yet.
- Only the last ten: once the ring is full, every new value overwrites the oldest. The average always refers to the last ten values.
- Trend: the LED “Trend” shows newest minus oldest value in K. The light “Steigt” lights up if the trend is above 0.5 K.
- Sensor failure: if the gas sensor “Halle” is missing, nothing is stored, the flashing light “Sensorfehler” lights up and the displays keep their last value.
Average over the filled slots
move total 0
move i 0
summing:
get value db i
add total total value
add i i 1
blt i count summing
div mean total count
Because the ring is filled from 0, the first count values always sit at addresses 0 to count − 1. Once it is full, count equals SIZE, and the loop runs over all slots.
In the test a value is stored every tick. In the game one value per minute is usually enough. For that you put a counter in front that only lets a value into the ring every 120 ticks.
Never store NaN in the ring. A single NaN makes the sum and thus the average useless for ten passes. Check the reading before you put it down with poke.
Diagram
Project task
Task
Build the ring buffer for the gas sensor “Halle” with ten slots at addresses 0 to 9. Outputs: LED “Mittel” (°C), LED “Trend” (K), wall light “Steigt”, flashing light “Sensorfehler”. The milestones are listed above the editor.
Milestones
- Milestone 1: average of the first values
- Milestone 2: only the last ten count
- Milestone 3: trend
- Milestone 4: sensor failure
Hints
Hint 1
On NaN: warning lamp on and back with bnez missing start before anything is stored.
Hint 2
Ring: poke pos temp, advance pos and wrap with mod, cap count at SIZE with min.
Hint 3
Newest value at pos − 1 (with mod), oldest at pos when the ring is full, otherwise at 0.
Quiz
2 questions. You pass from 60 % – the server does the grading.
Complete the day
- Passed all milestones of the project
- Passed the quiz with at least 60 %
Without an account progress is saved in this browser only.
Report a mistake in this lesson
Please sign in to report. Sign in