-
Notifications
You must be signed in to change notification settings - Fork 0
/
uart.c
113 lines (94 loc) · 2.56 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
112
113
//
// uart.c
//
// Somewhat generic code for buffered UART output. No checks for buffer overflow.
// Packet length is always 8 bytes and baud rate guarantees adequate throughput
#ifndef STM32F0 // helps Xcode resolve headers
#define STM32F0
#endif
#include <libopencm3/stm32/usart.h>
#include <libopencm3/cm3/nvic.h>
#include <libopencm3/stm32/gpio.h>
#include "uart.h"
#include <stdio.h>
#include <string.h>
// output buffer
int uartbuf[64];
long qnext, qlast;
// **** ISR
// Used for transmit only
void usart1_isr(void)
{
if (USART_ISR(USART1) & USART_ISR_TXE) // (should be the only bit enabled)
{
if (qnext != qlast)
{
gpio_set(GPIOC, GPIO9);
USART_TDR(USART1) = uartbuf[qnext++];
}
else
{
usart_disable_tx_interrupt(USART1);
gpio_clear(GPIOC, GPIO9);
}
qnext &= 0x3f;
}
}
// ****
// Buffered single char output. Put in mem buf and return. ISR sends it
void putch(int ch)
{
usart_disable_tx_interrupt(USART1); // prevent collision ISR access to qlast
uartbuf[qlast++] = ch;
qlast &= 0x3f;
usart_enable_tx_interrupt(USART1);
}
void putwd(long wd) // Write 16-bit value to UART
{
putch((wd & 0xFF00) >> 8); // msb
putch(wd & 0xFF); // lsb
}
void putswab(long wd) // Write 16-bit byte swappped to UART
{
putch(wd & 0xFF); // lsb
putch((wd & 0xFF00) >> 8); // msb
}
void SetupUART(void)
{
nvic_enable_irq(NVIC_USART1_IRQ);
// UART at 57600baud
usart_set_baudrate(USART1, 115200);
usart_set_databits(USART1, 8);
usart_set_stopbits(USART1, USART_STOPBITS_1);
usart_set_parity(USART1, USART_PARITY_NONE);
usart_set_flow_control(USART1, USART_FLOWCONTROL_NONE);
usart_set_mode(USART1, USART_MODE_TX_RX);
qnext = 0;
qlast = 0;
usart_enable(USART1);
putch('!'); // send a char to show it was reset
}
// void printWord(long toPrint)
// {
// for (unsigned int i = 0; i <= sizeof(toPrint); i++)
// {
// putch(toPrint);
// }
// putch('\r');
// putch('\n');
// char buffer[12];
// snprintf(buffer, sizeof(buffer), "%li", raw);
// char msg[] = "raw: ";
// int sizeMSG = strlen(msg);
// for (int i = 0; i < sizeMSG; i++)
// {
// usart_send_blocking(USART1, msg[i]);
// }
// int sizeBUF = strlen(buffer);
// for (int i = 0; i < sizeBUF; i++)
// {
// usart_send_blocking(USART1, buffer[i]);
// }
// usart_send_blocking(USART1, '\r');
// usart_send_blocking(USART1, '\n');
// }