Skip to content

Instantly share code, notes, and snippets.

@leyyce
Last active May 15, 2024 17:25
Show Gist options
  • Save leyyce/42d87e175ebb6586debb92ad5ec51c23 to your computer and use it in GitHub Desktop.
Save leyyce/42d87e175ebb6586debb92ad5ec51c23 to your computer and use it in GitHub Desktop.
LED-Blink AVR Assembly
;
; Blink.asm
;
; Created: 03/05/2024 19:59:06
; Author : Leya Wehner
;
; Output pin that the LED is connected to (Port D)
.equ output_bit = 2
; Blink frequency in Hz
.equ blink_frequency_in_Hz = 1
; Blink frequency scale factor
; Can be used to set non-integer values
; E.g. a frequency of 5 and scale factor of 10 results in a frequency of 0.5
.equ blink_frequency_scale_factor = 1
; Clock frequency in Hz
.equ clk_frequency_in_Hz = 16000000
; Cycles the CPU has to wait between turning the LED on and off to archive the wanted blink frequency
.equ cycles_to_wait = ((0.5 / (1. * blink_frequency_in_Hz / blink_frequency_scale_factor)) / (1. / clk_frequency_in_Hz)) / 6
; Mapping registers to names that carry more meaning
.def loop_pass_count_b1 = r17
.def loop_pass_count_b2 = r18
.def loop_pass_count_b3 = r19
.def i = r20
.def j = r21
.def k = r22
start:
sbi DDRD , output_bit ; Set port as output
; cbi PORTD, output_bit ; Clear output to make sure the LED is turned off after startup
ldi loop_pass_count_b1, byte1(cycles_to_wait)
ldi loop_pass_count_b2, byte2(cycles_to_wait)
ldi loop_pass_count_b3, byte3(cycles_to_wait)
blink_loop:
sbi PORTD, output_bit
rcall wait
cbi PORTD, output_bit
rcall wait
rjmp blink_loop
wait:
; Save original register values to stack
push i
push j
push k
; Make sure i, j and k registers are set to 0
clr i
clr j
clr k
cpi loop_pass_count_b3, 0
breq skip_byte3_loop
wait_byte3_loop:
inc i
cpi i, 0xFF
brne skip_carry_b3
clr i
inc j
cpi j, 0xFF
brne skip_carry_b3
clr j
inc k
cpse k, loop_pass_count_b3
skip_carry_b3: rjmp wait_byte3_loop
skip_byte3_loop:
cpi loop_pass_count_b2, 0
breq skip_byte2_loop
wait_byte2_loop:
inc i
cpi i, 0xFF
brne skip_carry_b2
clr i
inc j
cpse j, loop_pass_count_b2
skip_carry_b2: rjmp wait_byte2_loop
skip_byte2_loop:
cpi loop_pass_count_b1, 0
breq skip_byte1_loop
wait_byte1_loop:
inc i
cpse i, loop_pass_count_b1
rjmp wait_byte1_loop
skip_byte1_loop:
; Restore original register values from stack
pop k
pop j
pop i
ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment