Yahoo Groups archive

AVR-Chat

Index last updated: 2026-04-28 22:41 UTC

Message

RE: [AVR-Chat] Re: Mixing C and assembly with special requirements.

2012-03-27 by Tim Mitchell

I'm a bit of an assembly nut and have had good results mixing asm and c. (But not reserving registers, that just ties the compiler in knots)

I create an asm.s file in the project and define any variables I need in one of the c files. Then using .extern in the asm file you can use that variable.

If it's not an assembly routine you pass parameters using register pairs, there is a good AVRGCC help page listing which registers are used.

For example this is a timer interrupt handler for pulse width modulating an RGBW LED in assembler

#include <avr/io.h>

#define xl r26
#define xh r27
#define zl r30
#define zh r31

;timer 2 interrupt handler
.global TIMER2_OVF_vect

.extern RGBW0 ;4 bytes giving RGBW levels - declared globally in a C file
.extern LedPwmct

TIMER2_OVF_vect:
	push zl
	push zh
	in zl,_SFR_IO_ADDR(SREG) ;sreg
	push zl
	push r16
	push r17
	
	;-----led pwm--------------------------
	lds r16,LedPwmct
	dec r16
	sts LedPwmct,r16

	lds r17,LedPwmct
	tst r17
	brne t2_ledpwmnz
	;pwm zero - turn all off
	sbi _SFR_IO_ADDR(PORTB),1
	sbi _SFR_IO_ADDR(PORTB),2
	sbi _SFR_IO_ADDR(PORTB),3
	sbi _SFR_IO_ADDR(PORTD),3
	rjmp t2_ledend

t2_ledpwmnz:
	lds zl,RGBW0
	cp r16,zl
	brsh t2_led_nr
	cbi _SFR_IO_ADDR(PORTB),1
	rjmp t2_led_nro
t2_led_nr:
	sbi _SFR_IO_ADDR(PORTB),1
t2_led_nro:
	lds zl,RGBW0+1
	cp r16,zl
	brsh t2_led_ng
	cbi _SFR_IO_ADDR(PORTB),2
	rjmp t2_led_ngo
t2_led_ng:
	sbi _SFR_IO_ADDR(PORTB),2
t2_led_ngo:
	lds zl,RGBW0+2
	cp r16,zl
	brsh t2_led_nb
	cbi _SFR_IO_ADDR(PORTB),3
	rjmp t2_led_nbo
t2_led_nb:
	sbi _SFR_IO_ADDR(PORTB),3
t2_led_nbo:
	lds zl,RGBW0+3
	cp r16,zl
	brsh t2_led_nw
	cbi _SFR_IO_ADDR(PORTD),3
	rjmp t2_led_nwo
t2_led_nw:
	sbi _SFR_IO_ADDR(PORTD),3
t2_led_nwo:


t2_ledend:
	pop r17
	pop r16
	pop zl
	out _SFR_IO_ADDR(SREG),zl ;sreg
	pop zh
	pop zl
	reti

-- 
Tim Mitchell

Attachments

Move to quarantaine

This moves the raw source file on disk only. The archive index is not changed automatically, so you still need to run a manual refresh afterward.