-
Notifications
You must be signed in to change notification settings - Fork 0
/
usart1.c
126 lines (101 loc) · 2.34 KB
/
usart1.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include "USART1.h"
//#include "GPIO.h"
#include <stdint.h>
#include <stdbool.h>
#include <avr/io.h>
#include <avr/interrupt.h>
static void (*rxHandler)(char);
static volatile bool isRXBusy = false;
void USART1_init(void)
{
//Init Callback
rxHandler = 0;
//Enable Run in Debug
USART1.DBGCTRL = USART_DBGRUN_bm;
//Enable RX Interrupts
USART1.CTRLA = USART_RXCIE_bm;
//Async Mode, No Parity, 1 Stop Bit, 8 bit TX
USART1.CTRLC = USART_CMODE_ASYNCHRONOUS_gc | USART_PMODE_DISABLED_gc | USART_SBMODE_1BIT_gc | USART_CHSIZE_8BIT_gc;
//Baud for 115,200 at 4 MHz Clock
USART1.BAUD = 139;
//Enable Normal Mode for USART
USART1.CTRLB = USART_RXMODE_NORMAL_gc;
//Note: Call enableTX/enableRX after this function
}
void USART1_initIO(void)
{
//Default Value for output should be 1
PORTA.OUTSET = PIN1_bm;
// //Clear PORTMUX for USART1
// PORTMUX.USARTROUTEA &= ~(PORTMUX_USART1_gm);
//
// //Set PORTMUX for USART1
// PORTMUX.USARTROUTEA |= (PORTMUX_USART1_ALT1_gc);
//Set PA1 as Output
PORTA.DIRSET = PIN1_bm;
//Set PA2 as Input
PORTA.DIRCLR = PIN2_bm;
}
//Enable TX
void USART1_enableTX(void)
{
USART1.CTRLB |= USART_TXEN_bm;
}
//Disable TX
void USART1_disableTX(void)
{
USART1.CTRLB &= ~(USART_TXEN_bm);
}
//Enable RX
void USART1_enableRX(void)
{
USART1.CTRLB |= USART_RXEN_bm;
}
//Disable RX
void USART1_disableRX(void)
{
USART1.CTRLB &= ~(USART_RXEN_bm);
}
//Sets the callback function for Data RX
void USART1_setRXCallback(void (*function)(char))
{
rxHandler = function;
}
//Sends a byte of data
bool USART1_sendByte(char c)
{
if (USART1_canTransmit())
{
//Clear done bit
USART1.STATUS |= USART_TXCIF_bm;
//Load Byte of Data
USART1.TXDATAL = c;
return true;
}
return false;
}
//Returns true if the peripheral can accept a new byte
bool USART1_canTransmit(void)
{
return (USART1.STATUS & USART_DREIF_bm);
}
//Returns true if the shifter is running
bool USART1_isBusy(void)
{
return (!(USART1.STATUS & USART_TXCIF_bm));
}
//Returns true if data is being shifted in
bool USART1_isRXActive(void)
{
return isRXBusy;
}
ISR(USART1_RXC_vect)
{
//Data
char rx = USART1.RXDATAL;
if (rxHandler)
{
rxHandler(rx);
}
isRXBusy = false;
}