Build a class pack
Choose the parts and tools for your class. Print the worksheets together or share one link with your students.
Choose the class setup
Applied to every activity you add. You can change any activity afterwards. If an activity cannot use this setup, it is flagged and the closest supported setup is used.
Choose activities
Lab 1 · The Nios V computer
Lab 2 · Logic instructions
Lab 3 · Polling, timers and I/O
Lab 4 · Stack and subroutines
Lab 5 · Interrupts in assembly
Lab 6 · Programming in C
Lab 7 · Interrupts in C
Lab 8 · Graphics
Share or print
Computer Organization · Class activities
Your assigned activities
Your instructor chose these activities and how to build each one. Open an activity to start, or download its worksheet and files.
Watch the FPGAcademy introduction to CPUlator. Open the RISC-V DE1-SoC simulator, load stride.s with File → Open, then choose Compile and Load. Find the highlighted instruction in Disassembly and the a0 register on the left.
Predict the next register value
The program computes a byte distance for words four bytes apart. Read the three instructions before hold. Write down the value you expect in a0 after each instruction. Press Step Into once per row. Record the PC before each step and the actual value in a0 afterward.
| Instruction | PC before | Predicted a0 | Observed a0 |
|---|---|---|---|
| li | |||
| slli | |||
| addi |
Change one assumption
Change the initial word index from 3 to 5. Compile and load again. At hold, explain how you got from the index to the byte distance. Check whether taking one more step at hold changes a0 or the PC.
For a physical follow-on, try the signed-maximum exercise in Lab 6 and read the value returned by the real board.
Adapted from FPGAcademy · Computer Organization 24.1 · Lab 1, I. Original LabsLand assembly and worksheet. MIT
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
Load trace.s and choose Compile and Load. The five samples are signed 32-bit measurements. Before execution, predict the greatest value and its hexadecimal representation. If you initialized the candidate to zero, what would happen with this particular list?
Stop on each comparison
In Disassembly, go to inspect by entering its label in the address field. Click the gray breakpoint margin next to its first instruction and choose Continue. Record a0 and t0. Continue to the same breakpoint until the pointer reaches end_samples. Which comparison changes a0? Why does an equal value leave it alone?
Remove the breakpoint, continue to hold and press Stop. Open Memory (Ctrl-M), enter result in its address field and read the stored word. Compare it with the register. Use Restart, take two single steps, then double-click the PC value and enter the address of _start from Disassembly. Step again and describe which instruction executes.
Hand in
Submit the sequence of candidates, the final word from memory and one observation linking a source instruction to its effect. Replace the first sample by 24 and repeat. Distinguish the address of result from the value stored there.
Adapted from FPGAcademy · Computer Organization 24.1 · Lab 1, II. Original LabsLand assembly and worksheet. MIT
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
Complete large in largest.s. On entry a0 contains the number of words, at least one, and a1 the address of the first word. On return a0 must contain the greatest signed sample. The caller saves it at result. Use temporary registers for scratch values.
Test the interface
Set a breakpoint at large and inspect a0, a1 and ra. Predict the address to which ret will return. Step through the first load and check that its address is word-aligned. Use Step Out to return to the caller. Run the store and inspect result in Memory.
Test the supplied all-negative list, a single sample of −71 and a list whose largest value is last. Update the count every time you change the number of samples. Submit the argument values and observed return for each case. Explain why ret uses ra and why an unsigned comparison would fail on a mixture of signs.
Adapted from FPGAcademy · Computer Organization 24.1 · Lab 1, III. Original LabsLand assembly and worksheet. MIT
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
Load mirror.s. In Memory (Ctrl-M), go to label_text and find the six ASCII bytes, the zero terminator and the following guard byte 5a. Predict the order after reversal. Save a copy of the memory row before execution.
Watch a swap
Set a breakpoint at swap_pair. Record the two pointer values and identify the characters they address. Step until both stores have executed. Inspect the same row of memory, then continue through the remaining swaps. At hold, check the text, terminator and guard again.
Replace ROTOR7 with a five-character word, then an empty string. Recompile between runs. Submit the before and after rows for all three inputs. Explain how the loop treats a middle character and why the guard byte must survive unchanged.
Adapted from FPGAcademy · Computer Organization 24.1 · Lab 1, IV. Original LabsLand assembly and worksheet. MIT
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
Complete slen and srev in labels.s. The first takes a string address in a0 and returns the byte count in a0, excluding the terminating zero. The second takes the first and last character addresses in a0 and a1, both inclusive. The caller already handles an empty label.
Follow two calls
Set a breakpoint at slen. For SCOPE, predict the returned length and the address of its final character before letting the caller compute it. At srev, compare the actual pointers with your prediction. Continue and repeat with VGA2. Inspect first, second and empty in Memory before and after execution. Each label starts on its own 16-byte boundary.
Hand in the two subroutines, the original and final byte rows, and the value of the guard after the empty label. If the caller passed the address of the terminator as the last character, what would a C program see at the start of the resulting string?
Adapted from FPGAcademy · Computer Organization 24.1 · Lab 1, V. Original LabsLand assembly and worksheet. MIT
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
Load bit_trace.s. The assembly shifts a 32-bit word right and ANDs the shifted result with the previous word. Before running it, sketch what one pass does to 00111100. Predict the number of passes until that pattern disappears.
Inspect a loop
Set a breakpoint at shrink. Continue to it and record t0 and t1. Repeat until t0 reaches zero. Mark the longest original run in the full 32-bit sample. How many times did the counter advance? Why do two runs that start separated never become a single run?
Replace the sample with zero, a word with only bit 31 set, then all ones. Assemble and load again after each edit. Hand in the three counts and a short trace of the supplied word. A logical right shift fills from the left with zero. Explain how an arithmetic right shift would affect termination for the all-ones input.
Adapted from FPGAcademy Computer Organization 24.1 · Lab 2, I. Original LabsLand assembly and worksheet. MIT
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
Complete ones in ones.s. It receives one 32-bit word in a0 and returns its longest run of ones in a0. The caller examines ten nonzero words and stops at the zero sentinel. Register s0 contains the largest result seen so far.
Trace the call boundary
Stop at ones on the first word. Predict its return before stepping out. Continue until s0 changes; record the input, the returned count and the new maximum. Check one word with the longest run at a boundary and one with its longest run in the middle.
Put 0xffffffff at the end of the data, just before the sentinel. After running that case, place the sentinel first. Submit the final s0 for both runs and explain why scanning bytes in memory order could accidentally merge runs from different words.
Adapted from FPGAcademy Computer Organization 24.1 · Lab 2, II. Original LabsLand assembly and worksheet. MIT
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
Complete zeros in zeros.s. Count runs across all 32 positions, including leading and trailing zeros. The caller still treats a zero word as the end of the list. That word does not take part in the maximum.
Predict before stepping
For 0x00001000, count the zeros on both sides of the one. Predict the result for 0x80000007. How can complementing the input let you reuse the shrinking loop? At zeros, record the argument before complementing it and the value passed to the loop afterward.
Replace the first data word with 0x00000001 and then with 0xffffffff. Distinguish the maximum in s0 across the entire list from the return in a0 for an individual word. Submit both values for each experiment and explain why the sentinel must be tested before calling zeros.
Adapted from FPGAcademy Computer Organization 24.1 · Lab 2, III. Original LabsLand assembly and worksheet. MIT
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
Complete alt in alt.s. A run can start with either zero or one. Count bits in the run. For example, 1010 contains four alternating bits and three transitions.
Build a transition mask
Compare neighboring bits with XOR. A word of 32 bits has only 31 neighboring pairs. Sketch the mask for an eight-bit example before extending it to a full word. Decide what to do with the bit that has no higher neighbor. A word with no transitions still has a run of length one.
Test 0xaaaaaaaa and 0x55555555 separately. Inspect the mask and compare the two answers. Include a solid word of all ones and the supplied list. Record the per-word return in a0 and final list maximum in s0. Hand in a counterexample for an implementation that counts a transition beyond bit 31.
Adapted from FPGAcademy Computer Organization 24.1 · Lab 2, IV. Original LabsLand assembly and worksheet. MIT
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
A row of LEDs and a seven-segment digit receive the same number. Predict what each will show when switch 7 alone is on. Then test your prediction on the simulated DE1-SoC.
Trace the three ports
Open switch_ports.s in CPUlator. Find the load from the ten switches at 0xFF200040 and the stores to the red LEDs at 0xFF200000 and HEX3…0 at 0xFF200020. Read the starter before you change it. Which output can respond to the switches as written?
Compile and load, then select Continue. Under Devices, change the numbered switches. Note what the starter does with switch 0 alone. Stop, correct the source register in the second store, recompile and repeat. Set a new switch word for each row, clearing the switches left on from the previous row.
| Switches on | Red LEDs on | Illuminated bars on HEX1 and HEX0 |
|---|---|---|
| None | ||
| 0 | ||
| 1 and 2 | ||
| 7 | ||
| 8 | ||
| 9 | ||
| All ten |
On each digit, bits 0 through 6 control the top, upper right, lower right, bottom, lower left, upper left and middle bars. Each digit occupies one byte. Explain why switch 7 and switch 8 give different results. Submit the corrected loop, your table and a sketch for switch 8 alone.
Adapted from FPGAcademy Computer Organization, Lab 3, Part I. LabsLand wrote the assembly and activities. MIT notice
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
Build a polled input loop for a Nios V processor. A press on KEY0 clears the digit. KEY1 counts up to F and KEY2 counts down to zero. KEY3 blanks the display. From blank, pressing any of the other three buttons returns to zero. Only the rightmost display should light.
Predict and assemble
Download keypad.s, open it in the CPUlator RISC-V DE1-SoC editor and complete the two digit updates. Compile and load, step once, then continue. Locate Push buttons and Seven-segment displays under Devices. The simulator represents each button with a checkbox. Check it to press, uncheck it to release. Operate one button at a time.
Test a sustained press
Hold KEY1 for at least one second. Record the digit while held and after release. Press KEY1 a second time and explain why it counts again. Find the instruction that prevents a held button from repeating. Compare an input poll at 0xFF200050 with a display write to 0xFF200020.
| Action | Predicted HEX0 | Observed HEX0 |
|---|---|---|
| Press KEY2 when the digit is zero | ||
| From zero, press and release KEY1 ten times | ||
| Count up to F, then press KEY1 again | ||
| Press KEY3, then KEY2 | ||
| Press KEY1 twice, then KEY0 |
On the simulator, lowercase b and d distinguish hexadecimal digits from 8 and 0. Describe how the program represents blank internally, and how its byte differs from the pattern for zero. Submit one observation at each limit and the register or instruction you would inspect if the display repeated a held press.
Adapted from FPGAcademy Computer Organization 24.1, Lab 3, Part II. LabsLand wrote the assembly and activities. MIT notice
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
How long does a loop take on the processor in your browser? Make HEX1 and HEX0 count from 00 to FF, then return to 00. A short press on KEY0 pauses the count. The next press resumes it.
Design and calibrate
Open loop_counter.s in CPUlator's RISC-V DE1-SoC editor. The display table maps a hexadecimal digit to illuminated segments. Find the instruction that limits the counter to four bits and change its mask so that it retains a full byte. Compile and load, step once, then continue. Use the rightmost two digits of Seven-segment displays.
Time five successive display changes and divide the elapsed time by five. The starter uses 20,000,000 loop iterations. Make a prediction before doubling that count. Record both measured intervals. A browser instruction loop is a useful timing experiment; calibrate it on the machine where you take the measurement.
Test wrap and a short press
Change the initial byte from 0 to 254 (FE hex), compile and reload. Record the first four values. While the counter runs, briefly check and uncheck button 0 in the Push buttons panel. Hold off for at least two expected changes, then press and release again. Record the value held and the first value after resuming.
| Delay iterations | Time for five changes | Seconds per change | First four values from FE |
|---|---|---|---|
| 20,000,000 | |||
| 40,000,000 |
Explain why polling the button's current level only after a long loop can miss a press. Identify the load that reads the captured edge and the store that acknowledges it. Restore the initial value and delay before submitting your table.
Adapted from FPGAcademy Computer Organization 24.1, Lab 3, Part III. LabsLand wrote the assembly and activities. MIT notice
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
Keep the same two-digit hexadecimal display and button controls. This time the processor polls a timer that counts independently of the instructions in the waiting loop. Find the difference between the running count, mtime, and its compare value, mtimecmp.
Time the previous counter
Download the delay-loop checkpoint. In CPUlator choose File → Load ELF… and press Continue. Start a stopwatch when HEX1–HEX0 first changes and stop it five changes later. Press and release KEY0 to pause the count, then repeat to resume. Keep your elapsed time for comparison on the same computer. Press Stop before loading the timer source.
Configure the comparison
Open timer_counter.s in CPUlator for RISC-V DE1-SoC. The two 64-bit timer registers each occupy two 32-bit words. Draw their addresses starting at 0xFF202100. Read the stored low word of mtimecmp during polling instead of using the starter's fixed immediate value. Complete the eight-bit wrap mask. Compile and load, step once, then continue.
In Devices, open RISC-V Machine Timer and Seven-segment displays. The program writes 100,000,000 timer ticks into mtimecmp. Record the compare value shown by CPUlator and time five display changes. Compare the two methods on the same machine.
Observe and explain
Predict the result of each trial. For the first two, time five changes. For the last two, describe what the digits showed.
| Trial | Ticks in mtimecmp | Result |
|---|---|---|
| Default compare value | ||
| Compare value halved | ||
| Initial byte FE | ||
| Short KEY0 press and release, then a second press |
When testing FE, record each value across FF. When pausing, check whether mtime and the displayed byte behave the same way. Explain why the software reads the high word of mtime before using an unsigned comparison on the low word. Restore the original compare value before submitting.
Adapted from FPGAcademy Computer Organization 24.1, Lab 3, Part IV. LabsLand wrote the assembly and activities. MIT notice
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
The DE1-SoC model has a JTAG UART. The program sends a prefix, a hexadecimal digit and a newline. Predict the line for 0x0b. In CPUlator choose Compile and Load, then Continue. Stop once the line appears in the JTAG UART terminal.
Restart and set a breakpoint on the call to uart_byte inside uart_string. Record sp, ra and s0 on entry to uart_string and again after its return. Locate the saved return address in the stack frame. Explain why the routine must save it before calling another routine.
Repeat with 0x09, 0x0a and 0x0f. Hand in the three output lines and a short trace of one nested return. Which bits in the UART control register tell the program it can write?
Adapted from FPGAcademy Computer Organization 24.1 · Lab 4, Part I. LabsLand wrote the assembly and worksheet. MIT
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
Complete hex_word. It receives a 32-bit value in a0 and calls hex_digit once for each nibble, starting with the most significant. Keep leading zeros. Preserve each saved register you use, and save the return address before the first nested call. Keep sp aligned to 16 bytes.
Run the starter first. Identify the missing part of the terminal line. Predict the complete line for 0x00b30e04 and for zero. Test those values, 0x80000000 and 0xffffffff. Write the eight-digit field exactly as the terminal produced it.
Single-step one iteration. Which copy of the input survives the call to hex_digit? Submit the four observations and account for each word you stored on the stack.
Adapted from FPGAcademy Computer Organization 24.1 · Lab 4, Part II. LabsLand wrote the assembly and worksheet. MIT
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
Complete dec_word. The caller passes a 32-bit unsigned integer in a0. Print its base-ten digits without leading zeros. Zero itself needs one digit. Repeated unsigned division by ten yields the digits in reverse order. Design how the routine will keep them until they can be printed from left to right.
Test 0, 10, 0x00b30e04, 0x80000000 and 0xffffffff in CPUlator. For the largest value, predict the length and first and last digits before running. Compare the terminal output with an independent unsigned conversion. Explain what would change if you used signed division.
Submit the displayed values and a stack diagram for one call. Mark where the return address and any temporary digits live.
Adapted from FPGAcademy Computer Organization 24.1 · Lab 4, Part III. LabsLand wrote the assembly and worksheet. MIT
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
In CPUlator, SW selects a saved register from s0 to s11. Releasing KEY0 prints its current value in hexadecimal. Releasing any other KEY prints it in decimal. The example initializes the twelve registers with distinct values. The I/O loop and terminal routines are supplied.
Check your terminal before debugging
Download the hexadecimal checkpoint and the decimal checkpoint. Each runs a formatter from an earlier part. In CPUlator choose File → Load ELF…, select one file and press Continue. Look for Sample = 0x00B30E04 or Sample = 11734532 in the JTAG UART. Press Stop before loading the other file.
Both files print the same number. Once you can see both formats, load register_console.s in the Assembly editor and compile it to start your register exercise.
Read the selected register
Complete get_reg. On entry, a0 contains the register number. Save the twelve current values on a 16-byte-aligned stack, index the snapshot by word offset and return the selected value in a0. Restore sp. Identify the bounds check in the caller before you write code.
Select s5, press and release KEY0, then repeat with KEY1. Compare both lines with the s5 value in the Registers pane. Repeat for s0, s10 and s11. Select 12 and press a key. The terminal should keep its previous contents. Select s2 and press again to show that the loop is still running.
Change the initialization of s5 to 0xffffffff and repeat both formats. Submit two pairs of terminal lines, the result of the invalid selection and the stack address used for s11 relative to the snapshot base. Explain why printing hexadecimal must preserve saved registers.
Adapted from FPGAcademy · Computer Organization 24.1 · Lab 4, IV. Original LabsLand assembly and worksheet. MIT
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
The main loop copies ten switches to the red LEDs. A separate routine takes a snapshot of the switches when a pushbutton triggers an interrupt. Predict which output will change immediately and which will keep an earlier value.
Trace the two paths
Open interrupt_snapshot.s in CPUlator for the RISC-V DE1-SoC. Locate the store in mirror and the two stores in snapshot_trap. One acknowledges the pushbutton, the other updates the display. Run the starter with switches 1 and 2 on, press and release button 0, and compare the LEDs with HEX0. Correct the display store to write the sampled switch word. Compile and load again.
| Action | LED word | Segment bars on HEX0 |
|---|---|---|
| Turn on switches 1 and 2 | ||
| Press and release button 0 | ||
| Change the switches to bit 6 alone | ||
| Press and release button 3 | ||
| Clear the switches |
Step through the interrupt
Stop, reload, and search for snapshot_trap in Disassembly. Click the breakpoint gutter at its first instruction and continue. Briefly toggle a pushbutton in Devices. Read mcause, mepc and sp before stepping. Step into the handler until the stack pointer changes. What does its new value tell you about the stack frame? Find the store to the edge-capture register. Remove the breakpoint, continue and check that changing the switches still updates the red LEDs.
Submit the completed table and the low-order interrupt number decoded from mcause. Explain why the LED loop can continue to use its original registers after mret.
Adapted from FPGAcademy Computer Organization, Lab 5, Part I. LabsLand wrote the assembly and activities. MIT notice
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
Drive a binary counter from the machine timer. The foreground loop only displays a word from memory. In the background, one source of interrupts advances that word and another lets you stop or restart it.
Set up the sources
Open interrupt_count.s in CPUlator for RISC-V DE1-SoC. Locate setup_keys, setup_timer and the two comparisons with mcause. Calculate the compare value for a quarter of a second using a 100 MHz timer. Compile and load, step once, then continue. Time at least four LED changes. Read the ten LEDs as one binary word, with bit 0 on the right.
Test the run flag
Press and release button 0. What happens to the LEDs two seconds later? Find the instruction that should toggle the one-bit run flag and correct its immediate operand. Recompile and repeat. Try a different button to resume.
| Observation | LED word or measured interval |
|---|---|
| Five successive LED words | |
| Time from the first to the fifth word | |
| Two readings about one second apart while paused | |
| First change after resuming |
Explain why the timer still needs acknowledging while the LED word is held. Describe what would happen if the program waited for a button inside the timer handler.
Adapted from FPGAcademy Computer Organization, Lab 5, Part II. LabsLand wrote the assembly and activities. MIT notice
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
Keep the foreground loop and timer handler from the quarter-second counter. Make the pushbutton interrupt change how fast the LEDs advance. KEY0 pauses or resumes, KEY1 doubles the rate, KEY2 halves it and KEY3 leaves it alone.
Compare the periods
Open interrupt_rate.s in CPUlator for RISC-V DE1-SoC. Find the two shifts in key_event. The starter can slow the counter down but pressing KEY1 has no effect on the period. Correct that branch. Leave the time base and the foreground code unchanged. Compile and load, then select Continue.
Open RISC-V Machine Timer and the red LEDs. Press and release one button per row. Read mtimecmp and time the LEDs over several changes. A shorter period gives more changes per second.
| Sequence from a fresh run | Compare value in ticks | What happened to the LEDs? |
|---|---|---|
| No button | ||
| KEY1 | ||
| KEY1 again | ||
| KEY1 a third time | ||
| KEY2 | ||
| KEY3 | ||
| KEY0, wait one second, then KEY0 |
Choose Compile and Load to restore the initial period in data memory, then press KEY2 three times and record the slowest compare value you can reach. Explain the two limits and why pausing the display count does not change the stored period.
Adapted from FPGAcademy Computer Organization, Lab 5, Part III. LabsLand wrote the assembly and activities. MIT notice
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
Plan a one-minute stopwatch. HEX3 and HEX2 show seconds. HEX1 and HEX0 show hundredths. The timer generates one interrupt per hundredth. While any switch is on, the display must hold its current reading. The stored time must keep advancing.
Check the time limit
Open interrupt_clock.s in CPUlator for RISC-V DE1-SoC. Count the hundredths from 00.00 through 59.99 inclusive. Use that number to correct the wrap comparison. Follow the interrupt from clock_trap into encode_time. Explain the purpose of the four byte shifts in the packing loop.
Temporarily change the initial elapsed word to 5998. Compile and load. In Disassembly, search for record_time, set a breakpoint on its first instruction and continue three times. Record a0 each time. This gives you a repeatable reading at a boundary that passes too quickly to see in the browser.
Read the two clocks
Remove the breakpoint, restore the initial value to zero and reload. Select Continue. Turn on switch 0 and record the four digits twice, about two seconds apart. Turn on switch 9 before lowering switch 0. What happens while switch 9 remains on? Lower switch 9, then read the display as soon as it updates.
| Test | Prediction | Observation |
|---|---|---|
| First three interrupts from 5998 | ||
| Two readings while switch 0 is on | ||
| Switch 9 alone remains on | ||
| All switches return to zero |
Explain how the recovered reading tells you whether the timer itself paused. Include the machine timer compare value in ticks and the values from the breakpoint.
Adapted from FPGAcademy Computer Organization, Lab 5, Part IV. LabsLand wrote the assembly and activities. MIT notice
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
Computer Organization · Lab 6, Part I · C on the DE1-SoC Computer
You will translate a RISC-V list traversal into C, inspect the generated instructions and run it on a physical Nios V processor. Open Figure 1 of the original handout. Trace the first two loop iterations on paper. Which register counts the words still to inspect? Which register holds the largest data value so far?
Predict
Each list begins with a length. That first word is metadata. The remaining words are signed data. Predict both outputs before you run the program.
| List in memory | Your predicted maximum | Reading from the board terminal |
|---|---|---|
| 5, −12, 4, 17, −3, 5 | ||
| 4, −11, −7, −18, −7 |
Build and run
Open the Nios V C editor and put the starter into main.c. It prints two answers but only inspects the first data word in each list. Implement the loop in largest. Use the count when deciding where to stop. Both supplied lists contain at least one data word.
Select Build ELF, then Upload to FPGA. Wait for the board to report that the program is ready. Read the two lines in its Console and complete your table. Move the largest positive value to the last position in the mixed list and run again. Explain what an off-by-one error would print.
Inspect the implementation
Use the GDB or CPUlator instructions in the handout to inspect the RISC-V disassembly at main. Locate a load and the comparison or branch used to update the maximum. If optimization folds a constant example or inlines the function, compile the same source with debug information and optimization disabled for this inspection. Distinguish the startup routine from your C code.
Hand in
Submit your two observed terminal lines, your changed input and result, and a short annotated disassembly excerpt. Explain why starting the maximum at zero gives the wrong answer for the negative list.
Based on FPGAcademy Computer Organization 24.1, Lab 6, Part I. LabsLand wrote the programs, test cases and remote instructions. Original handout · FPGAcademy MIT notice
Open the LabsLand DE1-SoC lab: https://labsland.com/en/labs/fpga-de1-soc-niosv/
In CPUlator choose C in Language. Open main.c with File → Open, choose Compile and Load (F5), then Continue (F3). Keep the count in word zero separate from the signed data that follow.
Before changing the starter, predict the two lines it will print. Find the JTAG UART panel and compare its output with your prediction. Complete largest so that it visits every data element, then rebuild and run again. Move 17 to the final position in the mixed list and repeat. Record the three pairs of results. In Disassembly, go to largest and find the load and branch used to update the maximum. What happens to the negative list if best starts at zero?
Based on FPGAcademy Computer Organization 24.1, Lab 6, Part I. LabsLand wrote the programs, test cases and remote instructions. Original handout · FPGAcademy MIT notice
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
Computer Organization · Lab 6, Part II · Nios V C
Replace the terminal output from Part I with one memory-mapped store. You will read the answer from ten physical LEDs, then measure how the choice of output changes your program's machine code.
Predict the light pattern
The starter contains a count followed by five signed values. Circle the largest data value. Convert it to ten bits. Label your drawing from LEDR9 on the left to LEDR0 on the right. Repeat with the list {4, −11, −7, −18, −7}. For a negative result, display the low ten bits of its two's-complement representation.
Build and observe
Open the DE1-SoC Nios V C editor and put the starter in main.c. Finish the signed comparison loop. The volatile store writes the answer to the LED data register at 0xff200000. Build the ELF, upload it and read the row of red LEDs from the board camera. Rebuild with the negative list. Record both readings and explain how you recovered the signed answer in the second run.
| Input | Prediction (10 bits) | Observed LEDR9…0 | Signed result |
|---|---|---|---|
| Mixed list | |||
| Negative list |
Compare executable code
Build two versions from the same corrected source using the same RISC-V toolchain, startup, linker script and optimization. Keep the volatile input list identical. In the first version replace the LED store with a printf that prints best using %d and includes a newline. In the second keep the LED store. Use riscv32-unknown-elf-size on the two uncompressed ELF files and compare the text column. If doing this step with a local course toolchain, record its version. Explain the cost of formatted output and why the length of a compressed download cannot answer the question.
The activity ZIP contains the LabsLand runtime and compare.py in de1-runtime. Save the two versions as led.c and print.c. Run python3 de1-runtime/compare.py led.c print.c in a terminal with the RISC-V tools on your path. If your compiler is riscv-none-elf-gcc, add --prefix riscv-none-elf-. Include stdio.h in the printf version.
Hand in
Submit two LED readings, the two text-section sizes in bytes, the build options, and one explanation of the difference.
Adapted from FPGAcademy Computer Organization 24.1, Lab 6, Part II. Programs, input lists and remote procedure by LabsLand. Original handout · MIT notice
Open the LabsLand DE1-SoC lab: https://labsland.com/en/labs/fpga-de1-soc-niosv/
In CPUlator choose C in Language. Open main.c with File → Open, choose Compile and Load (F5), then Continue (F3). Keep the count in word zero separate from the signed data that follow.
Predict the ten simulated red LEDs when the starter processes {5, −12, 4, 17, −3, 5}. Read LEDR9 on the left and LEDR0 on the right. Complete the signed comparison loop and repeat. Replace the list with {4, −11, −7, −18, −7}, then rebuild. Record each ten-bit pattern, decode its signed value, and explain which ten bits of the 32-bit result the volatile store preserves. Compare these predictions with the physical camera when you run the board worksheet.
Adapted from FPGAcademy Computer Organization 24.1, Lab 6, Part II. Programs, input lists and remote procedure by LabsLand. Original handout · MIT notice
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
Computer Organization · Lab 6, Part III · Nios V C
A stream of binary data can contain long stretches of the same bit or an alternating pattern. Find the longest run of each kind within a single 32-bit word. Your program must show its three results simultaneously on the simulated displays.
Work one word by hand
Write 0x80000001 as 32 binary digits. Count the longest run of ones, of zeros and of alternating bits. A single bit counts as an alternating run of length one. Adjacent words in the array are separate measurements. What would happen if a run could cross the boundary?
Implement the measurement
In CPUlator, select C in the Language menu. Open the starter main.c with File → Open. Choose Compile and Load (F5), then Continue (F3). Find Seven-segment displays in Devices. What does the unfinished program show? Complete measure. Process exactly 32 bits for each unsigned word, including its leading zeros. Reset the current lengths when you start a new word and retain the three maxima for the entire array. You can scan the bits or apply repeated shifts and masks. The starter handles decimal conversion and the display registers.
The display is read from left to right in pairs. HEX5–4 show alternating bits, HEX3–2 show zeros and HEX1–0 show ones. Write each pair with two decimal digits. The DE1-SoC Computer peripheral uses a set bit to illuminate a segment.
Read the simulated displays
Use Compile and Load and then Continue after each edit. For each new array, predict all six digits before rebuilding. Read the six rightmost displays. The two unused positions on their left remain dark. Enter a zero word as real data in the last trial. Use an explicit word count so the zero cannot stop the scan early.
| Words in the array | Predicted HEX5…0 | Observed HEX5…0 |
|---|---|---|
| 0xfffffff0, 0x80000001, 0x33333333 | ||
| Same array plus 0xaaaaaaaa | ||
| Same array plus 0xaaaaaaaa and 0x00000000 |
Hand in
Submit your code, the three pairs of predicted and observed readings, and the word responsible for each maximum in the last run. Explain what mistake would give a zero count for a completely zero word.
Adapted from FPGAcademy Computer Organization 24.1, Lab 6, Part III. Programs and test arrays by LabsLand. Original handout · MIT notice
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
Build a stopwatch in C for the simulated DE1-SoC Computer. Its six digits show minutes, seconds and hundredths. A button release pauses or resumes the stopwatch. You will look for two different boundaries: the end of one minute and the end of an hour.
Set the interval
The processor's machine timer advances at 100 MHz. Calculate the ticks in one hundredth of a second and the hundredths in one hour. In CPUlator choose C in Language, then File → Open and select main.c. Find TICKS_PER_UPDATE, INITIAL_HUNDREDTHS and HUNDREDTHS_PER_HOUR. Which constant would make the clock restart after every minute?
Run and pause
Choose Compile and Load (F5), then Continue (F3). Read the six rightmost digits in Seven-segment displays. Press and release KEY0 in Push buttons. Record two readings a second apart. Press and release KEY3 and collect a third reading after a second. Why does resuming ignore the time spent paused?
Catch both rollovers
Set INITIAL_HUNDREDTHS to 5998u and rebuild. In Disassembly, go to the function show and put a breakpoint on its first instruction. Continue four times. Each stop occurs before the display update. Read a0, the function argument, as an unsigned number. Convert each count into MM:SS.DD.
| Start count | Four arguments to show | Which digit pair changes? |
|---|---|---|
| 5998 | ||
| 359998 |
Correct the wrap constant and repeat both trials. The 5998 trial should cross a minute; the 359998 trial should cross an hour. Restore the initial count to zero before submitting. Include both traces and explain why continuously comparing the timer for exact equality could miss an update.
Original LabsLand activity following FPGAcademy Computer Organization Lab 6, Part IV. FPGAcademy PDF · MIT
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
The simulated DE1-SoC Computer has room for six characters. Your C program holds an eight-character message, including one blank. Move the viewing window one character at a time, keeping the digits in their left-to-right order.
Draw the window
Copy the message dE1-SoC followed by a blank into eight boxes. Mark the six characters visible when the first box is at the left of the display. Shift the window by one box. At which starting index will your six-character window first cross the end of the array?
Build and observe
In CPUlator choose C in Language, open main.c with File → Open, then choose Compile and Load (F5) and Continue (F3). Read the six rightmost digits in Seven-segment displays. The starter repeatedly draws the first window.
Find where show selects a character for each column. Include the starting index in the lookup and wrap it at the length of the message. Keep the two high digits and the four low digits in the registers already supplied. Rebuild and follow an entire turn.
| First character index | Six characters, including blanks | Observation |
|---|---|---|
| 0 | ||
| 1 | ||
| 6 | ||
| 7 | ||
| Back to 0 |
Press and release KEY0 to freeze a window. After at least one second, check all six positions again. Press and release KEY3 to resume. Submit your table and the time between identical windows. Predict what happens to that period if you halve TICKS_PER_UPDATE, then try it.
Original LabsLand activity following FPGAcademy Computer Organization Lab 6, Part V. FPGAcademy PDF · MIT
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
Use an FPGA peripheral to provide a 10 ms tick for the six-digit scrolling message. Every fifty timeouts should advance the display by one character. The starting program displays the first window and then stays there.
Program the peripheral
In CPUlator select C, open main.c and choose Compile and Load (F5). Locate the Interval Timer peripheral at 0xff202000. At 100 MHz, a 10 ms interval takes one million ticks. The inclusive countdown starts at 999999. Split that value into its low and high 16-bit halves and compare them with the writes in start_timer. Locate the START and CONT bits in the control word.
Diagnose the frozen display
Press Continue (F3). Record whether Interval Timer shows Once or Cont. and Run or Stop. Why can the timeout flag be clear even when the device has already expired? Change the control value to produce repeated timeouts. Leave interrupts disabled; the program polls and clears the flag.
Measure the output
Write down the eight successive six-character windows, marking blanks with a dot. Press and release KEY0, wait one second and check that the same window remains. Press and release KEY3 to resume. Finally change HUNDREDTHS_PER_STEP from 50u to 25u, recompile, and time a full cycle in both builds. Explain which timer settings stayed fixed while the scroll rate changed.
Original LabsLand activity following FPGAcademy Computer Organization Lab 6, Part VI. FPGAcademy PDF · MIT
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
Let the main loop copy the ten switches to the red LEDs. A separate pushbutton interrupt takes a snapshot of the seven lowest switches for HEX0. Moving a switch between button releases should affect only the LEDs.
In CPUlator select C in Language, open File → Open and choose main.c. Use Compile and Load (F5), then Continue (F3).
Follow two paths through the program
Find main and machine_event. Which function needs to read SWITCHES on every pass? Which should update HEX_LOW exactly once per button event? Inspect the bit mask for the four pushbuttons. Keep the write that acknowledges KEY_EDGES and fix the assignment to HEX_LOW.
Try two snapshots
Use the Switches and Push buttons panels. Set the switch word to 6. Press and release KEY0, switch to 64 without touching a key, press and release KEY3, then move all switches down. At every step record the LED word and sketch HEX0. Pattern 6 lights the two right bars. Pattern 64 lights the middle bar.
Return to the interrupted program
Restart. In Disassembly, go to machine_event and set a breakpoint on the first instruction. Continue and release a key. Compare pc with mtvec, read mcause and mepc, then step through the prologue and the final mret. Submit the five output pairs and show where the compiler restores the interrupted stack and program counter.
Original LabsLand activity following FPGAcademy Computer Organization Lab 7, Part I. FPGAcademy PDF · MIT
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
A machine timer asks for a count every quarter second. A pushbutton interrupt toggles a run flag. The starter handles both interrupts, yet pressing a button leaves the LEDs counting.
In CPUlator select C in Language, open File → Open and choose main.c. Use Compile and Load (F5), then Continue (F3).
Separate counting from display
Trace count, running and period from the handler into main. Convert 25,000,000 ticks at 100 MHz to seconds. Repair the timer branch so ticks honor the run flag. Keep the timer armed even while the count is paused.
Test a pause that lasts several ticks
Read five consecutive LED words. Press and release KEY0, record the word, wait more than one second, and read it again. Release KEY3 and observe the next change. In Machine Timer inspect mtimecmp. Repeat with the unmodified starter if your readings match in both states.
| Event | LED word | Did the timer keep requesting updates? |
|---|---|---|
| Before KEY0 | ||
| Just after KEY0 | ||
| One second later | ||
| After KEY3 |
Explain why the timer interrupt can still fire while the visible count is held. Include one observed transition and the period calculation.
Original LabsLand activity following FPGAcademy Computer Organization Lab 7, Part II. FPGAcademy PDF · MIT
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
KEY0 pauses a binary counter. KEY1 should double its rate, KEY2 should halve it and KEY3 should leave it alone. The quarter-second starting period must stay between 6,250,000 and 100,000,000 timer ticks.
In CPUlator select C in Language, open File → Open and choose main.c. Use Compile and Load (F5), then Continue (F3).
Repair one direction
Find the KEY1 branch. Derive the new compare value when the frequency doubles. Leave the bounds and the acknowledge operation in place. Observe mtimecmp in Machine Timer while the program runs. Use press-and-release gestures.
Exercise both limits
Starting from a fresh run, release KEY1 three times, then KEY2 and KEY3. Record mtimecmp after each event. Restart and release KEY2 three times to reach the opposite limit. For one recorded value calculate the expected time between consecutive LED words.
| Trial | Initial | First release | Second release | Third release |
|---|---|---|---|---|
| KEY1 × 3 | ||||
| KEY2 × 3 after restart |
Pause with KEY0 and compare two LED readings more than a second apart. Resume with KEY0. Submit both limit traces and indicate which press changes neither the period nor the count rate.
Original LabsLand activity following FPGAcademy Computer Organization Lab 7, Part III. FPGAcademy PDF · MIT
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
Turn the six rightmost displays into a clock that rolls over after an hour. The main loop displays one snapshot while a machine-timer handler advances the time every hundredth. The starter restarts too early.
In CPUlator select C in Language, open File → Open and choose main.c. Use Compile and Load (F5), then Continue (F3).
Read the running clock
Watch the six digits. Read two values at least a second apart and split each into minutes, seconds and hundredths. Find the compare interval in Machine Timer. Check that the interval agrees with the 100 MHz timer frequency.
Test a whole hour in four interrupts
In the source change INITIAL_HUNDREDTHS to 5998u. Recompile. In Disassembly, go to next_hundredth and set a breakpoint on its first instruction. Press Continue four times. Record a0 (current hundredths) and mcause on every stop. Repeat with 359998u after correcting the rollover limit.
| Initial hundredths | Four values of a0 | Interrupt cause |
|---|---|---|
| 5998 | ||
| 359998 |
Convert the final two values of each trace to clock readings. Explain why a breakpoint in the interrupt path advances once per tick even though main refreshes the display many times. Restore the initial count to zero.
Original LabsLand activity following FPGAcademy Computer Organization Lab 7, Part IV. FPGAcademy PDF · MIT
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
A graphics program draws six test shapes using integer coordinates. The red line should be on row 16, yet the starter draws it elsewhere. Fix the address calculation, then use the other five shapes to check that the repair works across the image.
In CPUlator choose C, use File → Open to load main.c, then Compile and Load (F5). Open the VGA pixel buffer device and use Continue (F3).

Six test shapes in the CPUlator framebuffer. The white diagonal reaches the lower-right corner.
Find the row pitch
A pixel holds one 16-bit RGB565 value. Each row has 320 visible pixels, but the next row begins 1,024 bytes later. Calculate the addresses of (0,1), (13,16) and (319,239) relative to the front-buffer address at 0xFF203020. Look at clear_frame and put. Which distance does each use to reach the next row?
Check more than one slope
In the VGA pixel buffer panel, locate the red horizontal line, green vertical line, blue steep line, yellow shallow line, white lower-right diagonal and isolated magenta pixel. In the Zoom menu enlarge the image to inspect endpoints. With the incorrect row pitch, where does the magenta point at (179,101) appear? Convert its faulty halfword offset back into a physical row and column.
| Shape | First and last pixel | How many pixels including endpoints? |
|---|---|---|
| Red horizontal | ||
| Green vertical | ||
| Blue steep | ||
| White corner diagonal |
Repair put and compare the panel with your predictions. Trace two iterations of line on paper. Explain why keeping an integer error allows a vertical line and a single point to use the same function.
Original LabsLand activity following FPGAcademy Computer Organization Lab 8, Part I. FPGAcademy PDF · MIT
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
Move a yellow line by one pixel per vertical refresh. It begins two rows from the top. The starter reaches the edge and stays there. Use both the VGA output and a breakpoint to find the faulty direction change.
In CPUlator choose C, use File → Open to load main.c, then Compile and Load (F5). Open the VGA pixel buffer device and use Continue (F3).
Stop on each frame
Go to next_row in Disassembly and place a breakpoint on the first instruction. Continue seven times. At each stop a0 is the row currently on screen. The previous frame has been erased. Check that the line still has the same two horizontal endpoints and that no colored trail remains. Clear the breakpoint to watch continuous motion.
Test the opposite edge
Repair the upper-edge condition. Run again from INITIAL_ROW equal to 2, then rebuild with INITIAL_ROW equal to 237. The starting direction points toward the nearer edge. Reapply the breakpoint after rebuilding.
| Start row | Seven row readings | First direction reversal |
|---|---|---|
| 2 | ||
| 237 |
Submit both sequences and a sketch of the line at an edge. Explain why a valid final row is 239 and why waiting for the vertical refresh improves the animation.
Original LabsLand activity following FPGAcademy Computer Organization Lab 8, Part II. FPGAcademy PDF · MIT
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
Four colored squares move along diagonals. A white line joins each neighboring pair. Even the starter can look convincing for several frames. Use the controller registers to decide whether it actually draws each new frame off screen.
In CPUlator choose C, use File → Open to load main.c, then Compile and Load (F5). Open the VGA pixel buffer device and use Continue (F3).

Four squares from one CPUlator frame. The white lines connect adjacent squares.
Inspect the buffer swap
Set a breakpoint on the first instruction of move. Each stop follows a completed presentation. In Memory, enter 0xff203020. The first two 32-bit words contain the front and back buffer addresses. Capture four successive pairs. In VGA pixel buffer follow the red square as it touches the top edge and then the left edge.
| Frame | Front | Back | Red square top-left (x,y) |
|---|---|---|---|
| 1 | |||
| 2 | |||
| 3 | |||
| 4 |
Repair the drawing order
Trace next between present and move. Make the program alternate between the two frame arrays. Find when the program waits for the controller to finish swapping. Confirm that after the first frame the previous front buffer becomes the back buffer on every swap. Compare the addresses and the red square's positions before and after the repair. Calculate how far apart the two buffers are in bytes using their allocated height and row pitch.
Original LabsLand activity following FPGAcademy Computer Organization Lab 8, Part III. FPGAcademy PDF · MIT
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
Give the user control of a moving chain of squares. KEY0 doubles the distance traveled per frame and KEY1 halves it. KEY2 adds a square and KEY3 removes one. Raising any switch should hide the white links while leaving the colored squares moving.
In CPUlator choose C, use File → Open to load main.c, then Compile and Load (F5). Open the VGA pixel buffer device and use Continue (F3).
Try every control
Set a breakpoint on move. The arguments a0 and a1 contain the number of squares and the steps per frame. Use a button press and release between two stops; then press Continue. The first run starts with four squares and two steps. Raise SW9, change the number of squares and take a screenshot. Lower SW9 and compare the same scene. Which condition in main controls the white links?
Find the limits
From a fresh run, release KEY2 three times, KEY0 three times, then KEY1 four times. Finally release KEY3 until only one square is left and try one more time. Collect a0 and a1 at the lower and upper limits. Compare the displacement of the red square on two consecutive frames at different speeds.
| Control | Smallest observed | Largest observed | What happens on one more press? |
|---|---|---|---|
| Squares | |||
| Steps per frame |
Repair the switch condition. Submit the table and two screenshots that isolate the link control. Explain why the program checks for collisions on every single-pixel step when a fast frame advances eight positions.
Original LabsLand activity following FPGAcademy Computer Organization Lab 8, Part IV. FPGAcademy PDF · MIT
Open CPUlator (DE1-SoC RISC-V): https://cpulator.01xz.net/?sys=rv32-de1soc
Practise breakpoints, single-stepping, register inspection and memory edits on a local emulated RISC-V processor. A program is supposed to find the largest of five signed readings. Work out where it loses the correct answer.
Start two terminals
This exercise was tested on macOS with xPack RISC-V GCC 15.2.0, GNU GDB 16.3, QEMU 11.1.2 and make. You need riscv-none-elf-gcc, riscv-none-elf-gdb and qemu-system-riscv32 on your command path. RISC-V tools · QEMU downloads
Extract the worksheet pack. In the first terminal enter its starter directory and run make run. QEMU waits for a debugger. In a second terminal change to the same directory and run make debug. These two processes communicate on your own computer.
Catch the first incorrect comparison
Enter these commands at the GDB prompt.
break inspect_sample
break finished
continue
x/5dw &samples
p/d (int)$t1
p/d (int)$t2
x/i $pc
stepi
x/i $pc
The first breakpoint stops just before a branch. Make a prediction before stepping. Continue to the comparison for each of the remaining three samples and record the saved maximum and the incoming value. At finished, inspect the stored answer with x/dw &result.
| Incoming sample | Saved maximum before branch | Should the sample replace it? |
|---|---|---|
| -4 | ||
| 12 | ||
| 7 | ||
| 3 |
Change an input without rebuilding
At finished, enter the following. The two breakpoints above were created in order, so number 1 is the comparison. Use info breakpoints to check.
set {int}((char*)&samples+8) = 25
set $pc = &_start
disable 1
continue
x/dw &result
Repair the comparison in probe.s. Use detach and quit, stop QEMU in the first terminal with Ctrl-C, then run make clean before repeating make run and make debug. Compare the original and changed inputs in both programs. Submit the first branch where signed and unsigned ordering disagree, the two result pairs and your one-instruction repair.
This LabsLand exercise prepares you for the debugger commands in FPGAcademy Computer Organization Lab 1, Part VI. That activity applies GDB to a physical Nios V processor on a DE1-SoC. Original handout · GDB remote debugging
