129 lines
2.4 KiB
C++
129 lines
2.4 KiB
C++
#include <msp430g2553.h>
|
|
#include <stdio.h>
|
|
#include <isr_compat.h>
|
|
|
|
#include "uart.h"
|
|
|
|
|
|
|
|
volatile uint8_t txBuffer[UART_TX_BUFFER_SIZE+5];
|
|
|
|
volatile uint8_t txBufferReadIdx = 0;
|
|
volatile uint8_t txBufferWriteIdx = 0;
|
|
|
|
volatile uint8_t rxBuffer[UART_RX_BUFFER_SIZE+5];
|
|
volatile uint8_t rxBufferReadIdx = 0;
|
|
volatile uint8_t rxBufferWriteIdx = 0;
|
|
|
|
|
|
static inline void enableDataRegisterEmptyInterrupt() {
|
|
IE2 |= UCA0TXIE;
|
|
}
|
|
|
|
static inline void disableDataRegisterEmptyInterrupt() {
|
|
IE2 &= ~UCA0TXIE;
|
|
}
|
|
|
|
void uartInit() {
|
|
UCA0CTL1 |= UCSWRST;
|
|
|
|
P1SEL = BIT1 + BIT2;
|
|
P1SEL2 = BIT1 + BIT2;
|
|
|
|
UCA0CTL0 |= UCPEN | UCPAR; // even parity
|
|
UCA0CTL1 |= UCSSEL0; // ACLK
|
|
|
|
UCA0BR0 = 13;
|
|
UCA0BR1 = 0;
|
|
|
|
UCA0MCTL = UCBRS1 | UCBRS2;
|
|
|
|
UCA0CTL1 &= ~UCSWRST;
|
|
|
|
IE2 |= UCA0RXIE;
|
|
}
|
|
|
|
|
|
void uartWrite(uint8_t o) {
|
|
if (txBufferWriteIdx == (UART_TX_BUFFER_SIZE - 1)) {
|
|
while (txBufferReadIdx == UART_TX_BUFFER_SIZE);
|
|
} else {
|
|
while (txBufferReadIdx == (txBufferWriteIdx + 1));
|
|
}
|
|
|
|
txBuffer[txBufferWriteIdx] = o;
|
|
txBufferWriteIdx++;
|
|
|
|
if (txBufferWriteIdx > UART_TX_BUFFER_SIZE) {
|
|
txBufferWriteIdx = 0;
|
|
}
|
|
|
|
enableDataRegisterEmptyInterrupt();
|
|
}
|
|
|
|
|
|
//int uartPutchar(char c, FILE *stream) {
|
|
// if (c == '\n')
|
|
// uartPutchar('\r', stream);
|
|
// uartWrite((uint8_t) c);
|
|
// return 0;
|
|
//}
|
|
|
|
|
|
|
|
ISR(USCIAB0TX, UART_TX_ISR) {
|
|
if ((IFG2 & UCA0TXIE) != 0) {
|
|
if (txBufferReadIdx != txBufferWriteIdx) {
|
|
UCA0TXBUF = txBuffer[txBufferReadIdx];
|
|
txBufferReadIdx++;
|
|
if (txBufferReadIdx > UART_TX_BUFFER_SIZE) {
|
|
txBufferReadIdx = 0;
|
|
}
|
|
} else {
|
|
disableDataRegisterEmptyInterrupt();
|
|
}
|
|
}
|
|
}
|
|
|
|
ISR(USCIAB0RX, UART_RX_ISR) {
|
|
while ((IFG2 & UCA0RXIE) != 0) {
|
|
if (rxBufferWriteIdx == UART_RX_BUFFER_SIZE - 1) {
|
|
if (rxBufferReadIdx == UART_RX_BUFFER_SIZE) {
|
|
// rx buffer overflow
|
|
}
|
|
} else {
|
|
if (rxBufferReadIdx == rxBufferWriteIdx + 1) {
|
|
// rx buffer overflow
|
|
}
|
|
}
|
|
|
|
rxBuffer[rxBufferWriteIdx] = UCA0RXBUF;
|
|
rxBufferWriteIdx++;
|
|
|
|
if (rxBufferWriteIdx > UART_RX_BUFFER_SIZE) {
|
|
rxBufferWriteIdx = 0;
|
|
}
|
|
}
|
|
}
|
|
|
|
uint8_t uartHasChar() {
|
|
return rxBufferWriteIdx != rxBufferReadIdx;
|
|
}
|
|
|
|
uint8_t uartGetChar() {
|
|
uint8_t c = rxBuffer[rxBufferReadIdx];
|
|
rxBufferReadIdx++;
|
|
if (rxBufferReadIdx > UART_RX_BUFFER_SIZE) {
|
|
rxBufferReadIdx = 0;
|
|
}
|
|
return c;
|
|
}
|
|
|
|
int uartRead() {
|
|
int res = -1;
|
|
if (uartHasChar()) {
|
|
res = uartGetChar();
|
|
}
|
|
return res;
|
|
}
|