mirror of
https://github.com/sergeyyarkov/atmega8a_rgb-night-light.git
synced 2026-10-11 10:29:27 +03:00
64 lines
1.3 KiB
C
64 lines
1.3 KiB
C
#include "usart.h"
|
|
|
|
void (*EOT_Handler)(volatile char *rx_buffer) = NULL;
|
|
|
|
volatile char rx_buffer[RX_BUFFER_SIZE];
|
|
volatile uint8_t rx_buffer_idx = 0;
|
|
volatile bool rx_received_packet = false;
|
|
|
|
ISR(USART_RXC_vect) {
|
|
char c = UDR;
|
|
|
|
if (rx_buffer_idx >= RX_BUFFER_SIZE - 1) rx_buffer_idx = 0;
|
|
|
|
rx_buffer[rx_buffer_idx++] = c;
|
|
|
|
if (c == EOT || c == '\r' || c == '\n') {
|
|
rx_buffer[rx_buffer_idx] = '\0';
|
|
rx_buffer_idx = 0;
|
|
if (EOT_Handler != NULL) (*EOT_Handler)(rx_buffer);
|
|
}
|
|
}
|
|
|
|
void USART_SetReceiveHandler(void (*handler)(volatile char *rx_buffer)) {
|
|
EOT_Handler = handler;
|
|
}
|
|
|
|
void USART_OnReceivePacketHandler(void) {
|
|
if (EOT_Handler != NULL && rx_received_packet) {
|
|
(*EOT_Handler)(rx_buffer);
|
|
rx_received_packet = false;
|
|
}
|
|
}
|
|
|
|
void USART_Init(void) {
|
|
/**
|
|
* USART
|
|
* 8-bit char size, 1 stop bit, even parity, baud 9600
|
|
*/
|
|
DDRD &= ~_BV(PD0);
|
|
DDRD |= _BV(PD1);
|
|
UCSRB |= _BV(RXEN) | _BV(TXEN) | _BV(RXCIE);
|
|
UCSRC = _BV(URSEL) | _BV(UCSZ0) | _BV(UCSZ1) | _BV(UPM1);
|
|
UBRRH = UBRRH_VALUE;
|
|
UBRRL = UBRRL_VALUE;
|
|
}
|
|
|
|
void USART_SendChar(char c) {
|
|
loop_until_bit_is_set(UCSRA, UDRE);
|
|
UDR = c;
|
|
}
|
|
|
|
void USART_SendStr(char *str) {
|
|
char c;
|
|
|
|
while ((c = *str++) != '\0') {
|
|
USART_SendChar(c);
|
|
}
|
|
}
|
|
|
|
void USART_SendInt16(int16_t num) {
|
|
char str[7];
|
|
itoa(num, str, 10);
|
|
USART_SendStr(str);
|
|
} |