-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathusart.c
81 lines (69 loc) · 1.75 KB
/
usart.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
/*
* usart.c
*
* Created on: 19.05.2015
* Author: dode@luniks.net
*/
#include <stdio.h>
#include <string.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/setbaud.h>
#include "usart.h"
#include "utils.h"
static volatile bool usartReceived = false;
static char usartData[USART_LENGTH];
/**
* Called when data was received via USART.
*/
ISR(USART_RX_vect) {
if (bit_is_set(UCSR0A, RXC0) && !usartReceived) {
char data = UDR0;
size_t length = strlen(usartData);
if (length < USART_LENGTH - 1 && data != '\n' && data != '\r') {
usartData[length] = data;
} else {
usartData[length] = '\0';
usartReceived = true;
}
}
}
void initUSART(void) {
UBRR0H = UBRRH_VALUE;
UBRR0L = UBRRL_VALUE;
UCSR0B = (1 << TXEN0) | (1 << RXEN0);
UCSR0C = (1 << UCSZ01) | (1 << UCSZ00);
// enable USART RX complete interrupt 0
UCSR0B |= (1 << RXCIE0);
}
bool isUSARTReceived(void) {
return usartReceived;
}
void getUSARTData(char *data, size_t size) {
if (size > 0) {
data[0] = '\0';
strncat(data, usartData, size - 1);
memset(usartData, 0, USART_LENGTH);
usartReceived = false;
}
}
void printString(const char *data) {
uint8_t i = 0;
char c;
while ((c = data[i++]) != '\0') {
loop_until_bit_is_set(UCSR0A, UDRE0);
UDR0 = c;
}
}
void printUint(uint8_t data) {
char buf[6];
snprintf(buf, sizeof (buf), "%d\r\n", data);
printString(buf);
}
void printByte(uint8_t byte) {
char string[] = {'0', 'b', '?', '?', '?', '?', '?', '?', '?', '?', '\r', '\n', '\0'};
for (uint8_t i = 8; i-- > 0; ) {
string[9 - i] = byte & (1 << i) ? '1' : '0';
}
printString(string);
}