What you learn today
- Count up and reset a counter
- Loop with exit condition
- Count ticks
sleep makes the chip deaf. If you still want to measure time, you count yourself. The main loop with yield at the start runs exactly once per tick – a register that grows by one each time is a clock.
One count per tick
start:
yield
add r0 r0 1 # ticks since start
div r1 r0 2 # 2 ticks = 1 second
s db Setting r1 # seconds on the housing
j start
All registers are 0 when the chip is inserted. That is why r0 starts counting from zero without a start value of its own.
Resetting
A counter that is never reset grows forever. Two ways:
l r2 d1 Activate # button pressed?
beqz r2 next # no: carry on
move r0 0 # yes: counter to zero
next:
Or automatically after a fixed number: mod r0 r0 20 makes the counter run 0, 1, … 19, 0, 1 … That gives a beat that repeats every ten seconds.
Loop with an exit condition
A loop does not have to be the main loop. Within one tick the chip can repeat something until a condition is met – here the sum 1 + 2 + … + 10:
move r3 0 # sum
move r4 1 # running number
sum:
add r3 r3 r4
add r4 r4 1
ble r4 10 sum # up to and including 10
That is 30 instructions, they fit into one tick.
At most 128 instructions run per tick. If a loop needs more, the chip pauses in the middle of it and continues right there in the next tick. There is no error, but the main loop no longer runs once per tick – and every time measurement based on ticks is off.
Counter instead of sleep
With a counter you wait and still stay awake. If a light should stay on for ten seconds after a button press, the button sets a counter to 20 and every tick subtracts one. As long as it is above zero, the light stays on – and meanwhile the chip sees every further button press.
Diagram
Exercise
Task
Build a runtime counter: d0 is an LED display, d1 a button.
r0counts ticks, one per tick.- The display shows the runtime in seconds (ticks / 2).
- Pressing the button (
Activate= 1) resets the counter to 0.
Hints
Hint 1
Counting: add r0 r0 1 right after the yield.
Hint 2
Read the button, jump past the reset with beqz when it is not pressed.
Hint 3
Display: div r2 r0 2, then s d0 Setting r2.
Quiz
4 questions. You pass from 60 % – the server does the grading.
Complete the day
- Passed the simulator exercise
- 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