U23 2008/Beispiele Abend1

From C4 Wiki
< U23 2008
Revision as of 20:01, 18 August 2008 by Fd0 (talk | contribs) (Loesung in C)
Jump to: navigation, search

Aufgabe

Die Led an Pin PD7 soll im Sekundentakt blinken.

Loesung in Assembler

Zum kompilieren im Makefile noch einfuegen:

CFLAGS += -nostdlib

test.S:

#include <avr/io.h>
#define __SFR_OFFSET 0


.ORG 0
	jmp main 	/* reset vektor */

.ORG _VECTORS_SIZE

main:
	/* config PD7 as output */
	ldi r16, 128
	out DDRD, r16

loop:
	/* 0 OR 0 = 0
	   1 OR 0 = 1
	   0 OR 1 = 1
	   1 OR 1 = 1 */

	/* 0 XOR 0 = 0
	   1 XOR 0 = 1
	   0 XOR 1 = 1
	   1 XOR 1 = 0 */

	/* ZIEL: PORTD = PORTD XOR 128 */

	/* toggle bit for PD7 */
	in r17, PORTD
	ldi r18, 128
	eor r17, r18 /* toggle bit 7 */
	out PORTD, r17

	/* burn 19999996 cycles */

	ldi r19, 0
	ldi r20, 0
	ldi r21, 0
	
loop2:
	inc r19
	brne compare
	inc r20
	brne compare
	inc r21

compare:
	ldi r22, 0
	cpi r21, 30
	cpc r19, r22
	cpc r20, r22
	breq escape

	rjmp loop2

escape:
	rjmp loop

Loesung in C

test.c:

#include <avr/io.h>
#include <util/delay.h>

void main(void) {
	/* config PD7 as output */
	DDRD = _BV(PD7); /* == 1<<7 == 128 */

	while(1) {
		PORTD ^= _BV(PD7);

		uint8_t i;
		for (i = 0; i < 76; i++) {
			/* wait 4 * 65536 cycles */
			_delay_loop_2(0);
		}
	}
}