stationeers.de Mod workshop · Dominik1199
DE Sign in
  1. Home
  2. IC10 academy
  3. Day 127

Day 127 of 365 · Advanced · Month 5: Memory and structure

Subroutines with jal and ra

Write code once, use it many times: a jump with a return ticket.

Lesson 10 min Week 19

What you learn today

  • jal and j ra
  • Agree on input and output registers
  • Subroutine behind the main loop

Two sensors, two displays, the same conversion twice – copying costs lines and characters. Better: write the calculation once as a subroutine.

jal: a jump with a return ticket

jal convert     # jumps to convert, ra = next line

jal jumps like j, but first stores the number of the next line in the register ra. At the end of the subroutine, j ra brings you right back there.

start:
yield
lbn kelvin SENSOR HASH("Labor") Temperature Average
jal convert          # celsius = kelvin in degrees C
sbn DISPLAY HASH("Labor") Setting celsius
lbn kelvin SENSOR HASH("Lager") Temperature Average
jal convert
sbn DISPLAY HASH("Lager") Setting celsius
j start

convert:
sub celsius kelvin CELSIUSOFFSET
j ra                 # back to the caller

Input and output travel through agreed registers: here convert expects the value in kelvin (r0) and returns the result in celsius (r1). The alias names make the agreement visible in the code.

Warning

The subroutine belongs after the j start. Otherwise the chip runs into it at the end of the main loop, and j ra jumps to wherever the last call left it.

Tip

If a subroutine calls another one, ra gets overwritten. Then do push ra first and pop ra before returning.

Diagram

Calling and returning from a subroutine Main loop 2 l r0 d0 Temperature 3 jal celsius 4 s d2 Setting r1 5 l r0 d1 Temperature 6 jal celsius 7 s d3 Setting r1 8 j start celsius: sub r1 r0 273.15 j ra ra = 4 back to line ra
jal jumps into the subroutine and remembers the following line in ra. j ra returns exactly there.

Exercise

Task

Two gas sensors “Labor” and “Lager” and two LED displays with the same names hang on the data network. Each display shows the temperature of its room in °C. If a sensor is missing, its display shows −1.

Write the conversion only once as a subroutine convert and call it twice with jal.

Hints

Hint 1

Inside the subroutine: sub celsius kelvin CELSIUSOFFSET, then insert the −1 with snan and select.

Hint 2

In the main loop: lbn into kelvin, jal convert, then sbn with celsius – for both rooms.

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

Esc
↑ ↓ selectEnter open/ opens search anywhere