Input & output

Input & output

handles all input and output. An (environment call) asks the operating system or the simulator to perform a service for your assembly code. The screen and the keyboard are two of the services available this way.

Put the service number in a7, any argument in a0, then trigger . The services this simulator knows:

Services (a7)
1 # print integer (a0 = number)
4 # print string (a0 = address of text)
5 # read integer (result returned in a0)
10 # exit program
32 # sleep (a0 = milliseconds)
Service call
program
a71
a0value
ecall
systemprints a number

a7 = 1 selects the print service.

Every service shares the same two-register handshake. a7 says which service to run, and a0 carries whatever that service needs: a value to print, an address to read from, a duration to wait. The list is fixed and short, five entries, so learning this handshake once covers every way this simulator talks to the outside world. A real operating system extends the same idea to a much longer list.
Read a number, double it, print it
li a7, 5 # read integer -> a0
ecall
add a0, a0, a0 # double it
li a7, 1 # print integer
ecall
li a7, 10
ecall

selects read-integer and pauses for input, returning your number in a0. adds a0 to itself, doubling it in place. Then and print the result, and and exit. When you Run it, the simulator pops up an input box. Type a number and watch it come back doubled.

Printing text

Two new words first. A section is a labeled region of your program: instructions live in the .text section, while fixed data like text lives in the .data section. And an address is just a number that identifies one slot in memory. Instead of carrying a whole string around, a register can carry the address where the string begins, and the print service reads from there.

Text goes in the data section. You attach a label to it, then use ("load address") to load the address of that label and service 4 to print it.

Hello, RISC-V
.data
msg: .string "Hello, RISC-V!\n"
.text
la a0, msg # a0 = address of the text
li a7, 4 # print string
ecall
li a7, 10
ecall

In .data, the directive reserves space for the text and attaches the label msg. .string stores the characters and appends \n, a newline. In .text, puts the address of the text into a0, chooses the print-string service, and prints characters from that address until it reaches the end of the string. Then the program exits as usual.