What you learn today
- Batch instead of loops
- Cache values
- Avoid unnecessary writes
Yesterday you counted what a tick costs. Today it is about using less. Three patterns bring the most – and two of them make the code shorter at the same time.
Batch instead of loops
If twelve corridor lights should do the same thing, you need no loop over twelve names. Give them one name, and one sbn switches them all:
sbn LIGHT HASH("Flur") On dark # all lights called Flur
One instruction instead of twelve passes of five steps each. A loop only pays off if each device should get something different – like the tank lights from the day before yesterday.
Caching values
Device values only change once per tick. Whoever reads the same value three times with lbn gets the same number three times and pays three steps. Read it once into a register and keep working there. That saves steps and makes sure all calculations of a tick work with the same value.
Avoiding unnecessary writes
Many chips write the same value to the same devices every tick. That costs steps – and with some LogicTypes more: command types like Harvest, Plant or Activate trigger their action on every write. Better: remember the last state in a register and only write on a change.
beq dark state start # nothing changed: do not write
move state dark
sbn LIGHT HASH("Flur") On dark
state starts at −1, a value dark never takes. That guarantees one write on the first pass.
Whoever only writes on changes relies on the device keeping its value. If somebody rebuilds a light or switches it by hand, the chip learns nothing of it. For safety functions you would rather write every tick.
A counter of switching operations is a good probe: if it keeps rising, a condition is fluttering somewhere – for example a missing hysteresis.
Diagram
Exercise
Task
Control the corridor lights “Flur” by the daylight sensor “Aussen”:
- dark when
SolarIrradianceis below 100 or the sensor is missing - switch all lights with one batch instruction
- only write when
darkchanges, and count every write on the display “Schaltungen”
Hints
Hint 1
sge dark dark THRESHOLD, then seqz – that turns NaN into “dark”.
Hint 2
beq dark state start skips everything if nothing has changed.
Hint 3
On a change: remember state, sbn, count up, display.
Quiz
3 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