Thursday, June 03, 2010

AVR ASM First Steps

Hey Gang,

I finally got some time to get my AVR ASM tool chain up and running on Mac OSX. I'm posting my first hand written ASM code for making an LED blink, using a Mega8 (PD4, aka pin 6 on the meaga8). Let me know if you have any questions about getting your toolchain up and running. It is a bit of work to get it all set up, but it can be very satisfying to see your first program run on a $2 computer!

.include "" 

.def temp = r16
.def delay1 = r17
.def delay2 = r18
.def delayv = r19
.equ led = 4 ; PORTD bit number to blink LED on

.org 0x0000 ; the next instruction will be written to 0x0000
rjmp main ; jump to main:

clr delay1 ; set delay1 to 0
clr delay2 ; set delay2 to 0
ldi delayv, 10 ; set delayv to 50

dec delay2 ; decrement delay2, if 0, dec will set delay2 back to 255
brne delay_loop ; delay_loop: again if delay2 is not 0
dec delay1 ; decrament delay1, if 0, dec will set delay1 back to 255
brne delay_loop ; delay_loop: again if delay1 is not 0
dec delayv ; decrament delayv
brne delay_loop ; delay_loop: again if delayv is not 0
ret ; go back to where we came from

ldi temp, low(RAMEND) ; initiate the stack in the build in SRAM. Stack operations
out SPL, temp ; are always necessary when subroutines or interrupts are called.
ldi temp, high(RAMEND) ; By calling the subroutine or interrupt handling routine the actual adress
out SPH, temp ; is written to the stack in order to later jump back to the code where the
; interrupt or call occurred.

sbi DDRD, led ; connect PORTD pin 4 to LED

cbi PORTD, led ; turn PD4 high
rcall delay ; delay for an short bit
sbi PORTD, led ; turn PD4 low
rcall delay ; delay again for a short bit
rjmp loop ; recurse back to the start of loop:

Many thanks to leon, theusch, and srinivasandelta over at AVR Freaks for helping me get started.


Labels: , , , ,