Search code examples
assemblymicrocontrollernios

How to loop in NIOS II Assembly


So what I am trying to accomplish is to get the LEDs on my micro controller to flash back and forth using a loop. So far I have been able to get the LEDs to flash from right to left using this code

.equ LEDS, 0x10000010
.text
.global _start
_start: movia r2, LEDS
        movi r3, 0b10000000
        movi r4, 0x7FFF
        slli r4, r4, 3
        add r4, r4, r4
load: movi r5, 0b00000001
loop: stw r5, 0(r2)
      mov r6, r0
count: addi r6, r6, 1
      bne r6, r4, count
      beq r5, r3, load
      roli r5, r5, 1
      br loop

and also flash from left to right using this code

.equ LEDS, 0x10000010
.text
.global _start
_start: movia r2, LEDS
        movi r3, 0b00000001
        movi r4, 0x7FFF
        slli r4, r4, 3
        add r4, r4, r4
load: movi r5, 0b10000000
loop: stw r5, 0(r2)
      mov r6, r0
count: addi r6, r6, 1
      bne r6, r4, count
      beq r5, r3, load
      roli r5, r5, -1
      br loop

The trouble I'm having is combining the two so that it flashes left to right, and then back right to left in a loop. Do i need to make changes in the loop registers or the count?


Solution

  • The current code branches to load when r5 is equal to r3. Instead, it should branch to the other set of code. In other words, after moving from right to left, branch to the code that flashes the LED from left to right, and vice versa. The resulting code looks like this:

    .equ LEDS, 0x10000010
    .text
    .global _start
    _start:  movia r2, LEDS
             movi  r4, 0x7FFF
             slli  r4, r4, 3
             add   r4, r4, r4
    
    goleft:  movi  r3, 0b10000000
             movi  r5, 0b00000001
    lloop:   stw   r5, 0(r2)
             mov   r6, r0
    lcount:  addi  r6, r6, 1
             bne   r6, r4, lcount
             beq   r5, r3, goright
             roli  r5, r5, 1
             br    lloop
    
    goright: movi  r3, 0b00000001
             movi  r5, 0b10000000
    rloop:   stw   r5, 0(r2)
             mov   r6, r0
    rcount:  addi  r6, r6, 1
             bne   r6, r4, rcount
             beq   r5, r3, goleft
             roli  r5, r5, -1
             br    rloop