#include "MDR32Fx.h"
#include "MDR32F9Qx_port.h"
#include "MDR32F9Qx_rst_clk.h"
#include "MDR32F9Qx_uart.h"
#define LED_PORT MDR_PORTA
#define RX_BUF_SIZE 64
volatile uint8_t rx_buf[RX_BUF_SIZE];
volatile uint8_t rx_head = 0;
volatile uint8_t rx_tail = 0;
volatile uint8_t rx_count = 0;
void init_leds(void) {
RST_CLK_PCLKcmd(RST_CLK_PCLK_PORTA, ENABLE);
PORT_InitTypeDef PortInit;
PortInit.PORT_Pin = 0xFF;
PortInit.PORT_OE = PORT_OE_OUT;
PortInit.PORT_FUNC = PORT_FUNC_PORT;
PortInit.PORT_MODE = PORT_MODE_DIGITAL;
PortInit.PORT_SPEED = PORT_SPEED_SLOW;
PORT_Init(LED_PORT, &PortInit);
PORT_Write(LED_PORT, 0x00);
}
void init_uart(void) {
RST_CLK_PCLKcmd(RST_CLK_PCLK_PORTB, ENABLE);
RST_CLK_PCLKcmd(RST_CLK_PCLK_UART1, ENABLE);
PORT_InitTypeDef PortInit;
PortInit.PORT_Pin = PORT_Pin_5 | PORT_Pin_6;
PortInit.PORT_OE = PORT_OE_IN;
PortInit.PORT_FUNC = PORT_FUNC_ALTER;
PortInit.PORT_MODE = PORT_MODE_DIGITAL;
PortInit.PORT_SPEED = PORT_SPEED_FAST;
PORT_Init(MDR_PORTB, &PortInit);
UART_InitTypeDef uart;
uart.UART_BaudRate = 57600;
uart.UART_WordLength = UART_WordLength8b;
uart.UART_StopBits = UART_StopBits1;
uart.UART_Parity = UART_Parity_No;
uart.UART_FIFOMode = UART_FIFOMode_ON;
uart.UART_HardwareFlowControl = UART_HardwareFlowControl_None;
UART_Init(MDR_UART1, &uart);
UART_ITConfig(MDR_UART1, UART_IT_RX, ENABLE);
NVIC_EnableIRQ(UART1_IRQn);
UART_Cmd(MDR_UART1, ENABLE);
}
void UART1_IRQHandler(void) {
if (UART_GetITStatus(MDR_UART1, UART_IT_RX)) {
UART_ClearITPendingBit(MDR_UART1, UART_IT_RX);
uint8_t data = UART_ReceiveData(MDR_UART1);
rx_buf[rx_head] = data;
rx_head = (rx_head + 1) % RX_BUF_SIZE;
if (rx_count < RX_BUF_SIZE) rx_count++;
}
}
uint8_t get_byte_from_buf(uint8_t index) {
return rx_buf[(rx_tail + index) % RX_BUF_SIZE];
}
int main(void) {
init_leds();
init_uart();
while (1) {
while (rx_count >= 7) {
if (get_byte_from_buf(0) == 0xFF &&
get_byte_from_buf(1) == 0xFE &&
get_byte_from_buf(2) == 0xFF &&
get_byte_from_buf(3) == 0x88 &&
get_byte_from_buf(4) == 0x15) {
uint8_t data = get_byte_from_buf(5);
uint8_t crc = get_byte_from_buf(6);
uint8_t sum = 0;
for (int i = 0; i < 7; i++) sum += get_byte_from_buf(i);
if (sum == 0) {
PORT_Write(LED_PORT, data);
}
rx_tail = (rx_tail + 7) % RX_BUF_SIZE;
rx_count -= 7;
} else {
rx_tail = (rx_tail + 1) % RX_BUF_SIZE;
rx_count--;
}
}
// Можно добавить небольшую задержку, чтобы не нагружать процессор
for (volatile int i = 0; i < 10000; i++);
}
}