128 lines
2.4 KiB
C
128 lines
2.4 KiB
C
/*
|
|
* UART.c
|
|
*
|
|
* Created: 25/11/2021 16:26:10
|
|
* Author: n0x
|
|
*/
|
|
|
|
#include "UART.h"
|
|
CircularBuffer TxBuffer;
|
|
CircularBuffer* pTxBuffer = &TxBuffer;
|
|
CircularBuffer RxBuffer;
|
|
CircularBuffer* pRxBuffer = &RxBuffer;
|
|
|
|
volatile uint8_t TxActive;
|
|
|
|
void
|
|
uart_init(void)
|
|
{
|
|
UBRR0 = 103; /* set BAUD rate to 9600 */
|
|
|
|
UCSR0C |=
|
|
(0<<UMSEL00)|(0<<UMSEL01)| /* Async UART */
|
|
(0<<UPM00)|(0<<UPM01)| /* Disable Parity */
|
|
(1<<UCSZ00)|(1<<UCSZ01)| /* 8 Bit */
|
|
(0<<USBS0); /* 1 Stopbit */
|
|
|
|
|
|
UCSR0B |=
|
|
(1<<TXEN0)|(1<<RXEN0)| /* enable send and receive */
|
|
(1<<RXCIE0); /* enable Receive interrupts */
|
|
|
|
pTxBuffer->Readpointer = 0;
|
|
pTxBuffer->Writepointer = 0;
|
|
pRxBuffer->Readpointer = 0;
|
|
pRxBuffer->Writepointer = 0;
|
|
}
|
|
|
|
/* ------------------------ */
|
|
/* Sending Data */
|
|
/* ------------------------ */
|
|
|
|
void
|
|
uart_send_string(char* string)
|
|
{
|
|
int i = 0;
|
|
while(string[i] != '\0'){
|
|
uart_send_byte(string[i]);
|
|
i++;
|
|
}
|
|
}
|
|
|
|
void
|
|
uart_send_byte(char c)
|
|
{
|
|
/* Disable the TX Interrupt */
|
|
UCSR0B &= ~(1<<TXCIE0);
|
|
|
|
if(TxActive){
|
|
pTxBuffer->data[pTxBuffer->Writepointer++] = c;
|
|
if (pTxBuffer->Writepointer>=SIZE_BUFFER){
|
|
pTxBuffer->Writepointer = 0;
|
|
}
|
|
} else {
|
|
TxActive = 1;
|
|
UDR0 = c;
|
|
}
|
|
/* Enable the TX Interrupt again*/
|
|
UCSR0B |= (1<<TXCIE0);
|
|
}
|
|
|
|
ISR(USART0_TX_vect)
|
|
{
|
|
if(pTxBuffer->Readpointer != pTxBuffer->Writepointer)
|
|
{
|
|
UDR0 = pTxBuffer->data[pTxBuffer->Readpointer++];
|
|
|
|
if(pTxBuffer->Readpointer >= SIZE_BUFFER){
|
|
pTxBuffer->Readpointer = 0;
|
|
}
|
|
} else {
|
|
TxActive = 0;
|
|
}
|
|
}
|
|
|
|
/* ------------------------ */
|
|
/* Receiving Data */
|
|
/* ------------------------ */
|
|
|
|
uint8_t
|
|
uart_data_available(void)
|
|
{
|
|
uint8_t dataAvailabel = 0;
|
|
UCSR0B &= ~(1<<RXCIE0);
|
|
if(pRxBuffer->Readpointer != pRxBuffer->Writepointer){
|
|
dataAvailabel = 1;
|
|
}
|
|
UCSR0B |= (1<<RXCIE0);
|
|
return dataAvailabel;
|
|
}
|
|
|
|
char
|
|
uart_get_data(void)
|
|
{
|
|
char data = 0;
|
|
UCSR0B &= ~(1<<RXCIE0);
|
|
if(pRxBuffer->Readpointer != pRxBuffer->Writepointer)
|
|
{
|
|
data = pRxBuffer->data[pRxBuffer->Readpointer++];
|
|
if(pRxBuffer->Readpointer >= SIZE_BUFFER){
|
|
pRxBuffer->Readpointer = 0;
|
|
}
|
|
}
|
|
UCSR0B |= (1<<RXCIE0);
|
|
return data;
|
|
}
|
|
|
|
ISR(USART0_RX_vect)
|
|
{
|
|
uint8_t status = UCSR0A;
|
|
uint8_t data = UDR0;
|
|
|
|
if((status & ((1<<DOR0) | (1>>FE0))) == 0){
|
|
pRxBuffer->data[pRxBuffer->Writepointer++] = data;
|
|
if(pRxBuffer->Writepointer >= SIZE_BUFFER) {
|
|
pRxBuffer->Writepointer = 0;
|
|
}
|
|
}
|
|
} |