chore: rewrite to modbus rtu

This commit is contained in:
2024-11-09 00:36:06 +06:00
parent 0a0084f98f
commit 68f47c9d53
14 changed files with 506 additions and 167 deletions

43
rs485.c Normal file
View File

@@ -0,0 +1,43 @@
#include "rs485.h"
#include "ch32v003fun.h"
#define RS485_DIR (1 << 0)
void rs485_init(int uartBRR) {
RCC->APB2PCENR |= RCC_APB2Periph_GPIOD | RCC_APB2Periph_GPIOC |
RCC_APB2Periph_USART1 | RCC_APB2Periph_AFIO;
// RS485_DIR as output, initial recv mode
GPIOC->CFGLR &= ~(0xf << (4 * 0));
GPIOC->CFGLR |= (GPIO_Speed_10MHz | GPIO_CNF_OUT_PP) << (4 * 0);
GPIOC->BCR = RS485_DIR;
// UART pins (PD5=TX, PD6=RX)
GPIOD->CFGLR &= ~(0xf << (4 * 5) | 0xf << (4 * 6));
GPIOD->CFGLR |= (GPIO_Speed_10MHz | GPIO_CNF_OUT_PP_AF) << (4 * 5);
GPIOD->CFGLR |= GPIO_CNF_IN_FLOATING << (4 * 6);
USART1->CTLR1 =
USART_WordLength_8b | USART_Parity_No | USART_Mode_Tx | USART_Mode_Rx;
USART1->CTLR2 = USART_StopBits_1;
USART1->CTLR3 = USART_HardwareFlowControl_None;
USART1->BRR = uartBRR;
USART1->CTLR1 |= CTLR1_UE_Set;
}
void rs485_send(uint8_t *buf, uint16_t len) {
GPIOC->BSHR = RS485_DIR; // TX mode
for (uint16_t i = 0; i < len; i++) {
while (!(USART1->STATR & USART_FLAG_TXE));
USART1->DATAR = buf[i];
}
while (!(USART1->STATR & USART_FLAG_TC));
GPIOC->BCR = RS485_DIR; // RX mode
}
uint8_t rs485_available(void) { return (USART1->STATR & USART_FLAG_RXNE) != 0; }
uint8_t rs485_read(void) { return USART1->DATAR & 0xFF; }