-
Notifications
You must be signed in to change notification settings - Fork 0
/
uart.c
111 lines (92 loc) · 2.05 KB
/
uart.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*
* uart.c
*
* Asynchronous UART example tested on ATMega328P (16 MHz)
*
* Toolchain: avr-gcc (4.3.3)
* Editor: Eclipse Kepler (4)
* Usage:
* Perform all settings in uart.h and enable by calling initUART(void)
* Compile:
* make all
*
* Functions:
* - First call initUART() to set up Baud rate and frame format
* - initUART() calls macros TX_START() and RX_START() automatically
* - To enable interrupts on reception, call RX_INTEN() macros
* - Call functions getByte() and putByte(char) for character I/O
* - Call functions writeString(char*) and readString() for string I/O
*
* Created on: 21-Jan-2014
* Author: Shrikant Giridhar
*/
#include "uart.h"
// Debug Mode; comment out on Release
#define _DEBUG 0
/*! \brief Configures baud rate (refer datasheet) */
void initUART(void)
{
// Not necessary; initialize anyway
DDRD |= _BV(PD1);
DDRD &= ~_BV(PD0);
// Set baud rate; lower byte and top nibble
UBRR0H = ((_UBRR) & 0xF00);
UBRR0L = (uint8_t) ((_UBRR) & 0xFF);
TX_START();
RX_START();
// Set frame format = 8-N-1
UCSR0C = (_DATA << UCSZ00);
}
/*! \brief Returns a byte from the serial buffer
* Use this function if the RX interrupt is not enabled.
* Returns 0 on empty buffer
*/
uint8_t getByte(void)
{
// Check to see if something was received
while (!(UCSR0A & _BV(RXC0)));
return (uint8_t) UDR0;
}
/*! \brief Transmits a byte
* Use this function if the TX interrupt is not enabled.
* Blocks the serial port while TX completes
*/
void putByte(unsigned char data)
{
// Stay here until data buffer is empty
while (!(UCSR0A & _BV(UDRE0)));
UDR0 = (unsigned char) data;
}
/*! \brief Writes an ASCII string to the TX buffer */
void writeString(char *str)
{
while (*str != '\0')
{
putByte(*str);
++str;
}
}
const char* readString(void)
{
char rxstr[RX_BUFF];
char* temp;
temp = rxstr;
while((*temp = getByte()) != '\n')
{
++temp;
}
return rxstr;
}
#if _DEBUG
int main(void)
{
initUART();
while(1)
{
writeString(readString());
putByte('\r');
putByte('\n');
}
return 0;
}
#endif