source: avrstuff/libs/usart/usart.c@ e5dd493

main
Last change on this file since e5dd493 was e5dd493, checked in by Adrien Destugues <pulkomandy@…>, 5 years ago

usart: some cleanups.

  • Property mode set to 100644
File size: 1.7 KB
Line 
1/* AVR USART acces functions - stolen from Extreme Electronics */
2
3#include <avr/io.h>
4#include <inttypes.h>
5
6#ifndef BAUD
7 #error You must define BAUD to use libuart.
8#endif
9
10// FIXME there are two USARTs in this case and we should be able to drive either
11
12// Compatibility for devices with single USART only
13#ifdef __AVR_ATmega8__
14#define UBRR0H UBRRH
15#define UBRR0L UBRRL
16#define UCSR0A UCSRA
17#define UCSR0C UCSRC
18#define UCSR0B UCSRB
19#define UDR0 UDR
20#define UDRE0 UDRE
21#define RXC0 RXC
22#endif
23
24void USARTInit()
25{
26 //Set Baud rate
27 #include <util/setbaud.h>
28 UBRRH = UBRRH_VALUE;
29 UBRRL = UBRRL_VALUE;
30 #if USE_2X
31 UCSRA |= (1 << U2X);
32 #else
33 UCSRA &= ~(1 << U2X);
34 #endif
35
36 /*Set Frame Format
37 >> Asynchronous mode
38 >> No Parity
39 >> 1 StopBit
40 >> char size 8
41 */
42#ifdef __AVR_ATtiny2313__
43 UCSRC = (1 << UCSZ1) | (1 << UCSZ0);
44#elif defined __AVR_ATmega128__
45 UCSR0C = (2 << UCSZ0) | (2 << UPM0) ; /* 7 bits + even parity.
46 TODO make this configurable. */
47#else
48 UCSRC = (1 << URSEL) | (3 << UCSZ0);
49#endif
50
51 //Enable The receiver and transmitter
52 UCSRB = (1 << RXEN) | (1 << TXEN);
53}
54
55
56void USARTWriteChar(char data)
57{
58 //Wait untill the transmitter is ready
59 while(!(UCSR0A & (1<<UDRE0)))
60 {
61 //Do nothing
62 }
63
64 //Now write the data to USART buffer
65
66 UDR=data;
67}
68
69
70char USARTReadChar()
71{
72 //Wait untill a data is available
73 while(!(UCSR0A & (1<<RXC0)))
74 {
75 //Do nothing
76 }
77
78 //Now USART has got data from host
79 //and is available is buffer
80
81 return UDR0;
82}
83
84
85void USARTWriteHex(unsigned char i)
86{
87 unsigned char k = i>>4;
88 if (k <=9) k+='0';
89 else k+=('A'-10);
90
91 USARTWriteChar(k);
92
93 k = i&0xF;
94 if (k <=9) k+='0';
95 else k+=('A'-10);
96
97 USARTWriteChar(k);
98}
Note: See TracBrowser for help on using the repository browser.