Mercurial > avr_jtag
comparison src/avriotools.c @ 0:a0ce8ebf2f18
LED on PINB0 & PINB1 and UART testing.
- LED flasing on PINB0 & PINB1.
- print 'hello' messages to UART for every flashing round.
author | Thinker K.F. Li <thinker@branda.to> |
---|---|
date | Sat, 21 Feb 2009 15:49:59 +0800 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:a0ce8ebf2f18 |
---|---|
1 #include "avriotools.h" | |
2 #include <avr/io.h> | |
3 | |
4 typedef struct _port_regs { | |
5 volatile uint8_t *port, *ddr, *pin; | |
6 } port_regs_t; | |
7 | |
8 static port_regs_t regs[] = { | |
9 { &PORTB, &DDRB, &PINB }, | |
10 { &PORTD, &DDRD, &PIND } | |
11 }; | |
12 #define NPORTS (sizeof(regs) / sizeof(*regs)) | |
13 | |
14 #define ERR -1 | |
15 #define OK 0 | |
16 | |
17 int pin_mode(volatile uint8_t * port, int pin, pin_mode_t mode) { | |
18 port_regs_t *preg; | |
19 int i; | |
20 | |
21 for(i = 0; i < NPORTS; i++) { | |
22 preg = regs + i; | |
23 if(preg->port == port) | |
24 break; | |
25 } | |
26 if(i == NPORTS) | |
27 return ERR; | |
28 | |
29 switch(mode) { | |
30 case PM_INPUT: | |
31 *preg->ddr &= ~_BV(pin); | |
32 *preg->port |= _BV(pin); | |
33 break; | |
34 | |
35 case PM_OUTPUT: | |
36 *preg->ddr |= _BV(pin); | |
37 break; | |
38 | |
39 default: | |
40 return ERR; | |
41 } | |
42 | |
43 return OK; | |
44 } | |
45 | |
46 /* To make setbaud.h no more complaint */ | |
47 #define BAUD 9600 | |
48 #include <util/setbaud.h> | |
49 | |
50 int uart_init(uint32_t baud) { | |
51 unsigned long ubrr_v; | |
52 long err; | |
53 | |
54 if(baud > (F_CPU / 8)) | |
55 return ERR; | |
56 | |
57 #define F_CPUx2 (F_CPU * 2UL) | |
58 | |
59 ubrr_v = (F_CPU + baud * 8UL) / (baud * 16UL) - 1UL; | |
60 /* Allow bias of baud rate in 2%, or use U2X clock. | |
61 * ATmega168 divides baud rate generator clock by 2, 8, or 16. | |
62 * Setting U2X bit makes the clock divided by 8 instead of 16. | |
63 * It makes more accurately output and higher max baud rate. | |
64 */ | |
65 err = 16L * 100L * (ubrr_v + 1) * baud - F_CPU * 100L; | |
66 if(err > F_CPUx2 || err < -F_CPUx2 || ubrr_v < 2) { | |
67 ubrr_v = (F_CPU + baud * 4UL) / (baud * 8UL) - 1UL; | |
68 UCSRA |= (1 << U2X); | |
69 } else { | |
70 UCSRA &= ~(1 << U2X); | |
71 } | |
72 | |
73 UBRRH = ubrr_v >> 8; | |
74 UBRRL = ubrr_v & 0xff; | |
75 return OK; | |
76 } |