Assignment 1: Program Code and Direction State

Here is the program for Assignment 1, along with a note on tracking the direction of movement.

Assignment 1 program

# First configure every pin as a GPIO output
_start:
    # 1. Base address of the PB GPIO registers
    lui  a0, 0x2000

    # 2. Configure PB0 through PB7 as outputs
    lui  a1, 0x11111
    addi a1, a1, 0x111
    sw   a1, 0x30(a0)

    # 3. Set the initial PB_DAT value / light position
    addi a1, zero, 1

    # 4. Set the turning thresholds and track the current direction
    # Avoid bouncing only between PB7 and PB6 on the return journey
    addi t0, zero, 1
    addi t1, zero, 128
    addi t2, zero, 0       # 0 = go_right, 1 = go_left

loop:
    # 5. Write each new state to PB_DAT
    sw   a1, 0x40(a0)

    # 6. Delay so the movement is visible
    lui  a2, 0x3f00

delay:
    addi a2, a2, -1
    bne  a2, zero, delay

    # 7. Turn at endpoints; otherwise keep the current direction
    beq  a1, t0, go_right
    beq  a1, t1, go_left
    bne  t2, zero, go_left

go_right:
    addi t2, zero, 0
    slli a1, a1, 1
    j    loop

go_left:
    addi t2, zero, 1
    srli a1, a1, 1
    j    loop

Transcription note: the go_right and go_left labels, clipped at the left edge of the screenshot, have been completed. The screenshot has a line through addi t1, zero, 128; the copyable version above retains it because the upper-bound comparison still uses t1.

Why does t2 need to remember the direction?

The key register to notice in this program is `t2`: it remembers the light's current direction of movement.

Without tracking and checking that direction, using only the two endpoint checks can appear to work while moving from PB0 toward PB7. On reaching PB7 and returning, however, the light can get stuck bouncing between PB7 and PB6.

When the light state is 10000000, a1 equals t1. The instruction beq a1, t1, go_left branches to go_left, which shifts the state right to 01000000. The program then returns to loop and writes that state to PB_DAT.

On the next iteration, 01000000 is neither the PB0 endpoint nor the PB7 endpoint. Without the direction check bne t2, zero, go_left, neither beq branches, so execution falls through to go_right and shifts the state left again to 10000000.

The light then keeps alternating between 10000000 and 01000000.

The endpoint checks decide when to turn; `t2` remembers which way to keep moving afterward.

Original screenshot

Original November 16 Assignment 1 program screenshot, including the Chinese comments and the explanation of direction register t2.