keil5中STM32F103rs485接受u16数据的功能函数
时间: 2023-11-27 07:50:59 浏览: 92
以下是在Keil uVision5中使用STM32F103的RS485接收u16数据的示例代码:
```c
#include "stm32f10x.h"
// 定义RS485接收缓冲区大小
#define RS485_RX_BUF_SIZE 10
// 定义RS485接收状态机的各个状态
typedef enum {
RS485_RX_IDLE = 0,
RS485_RX_START,
RS485_RX_RECEIVING,
RS485_RX_COMPLETE,
RS485_RX_ERROR
} RS485_RX_StateTypeDef;
// 定义RS485接收数据结构
typedef struct {
uint16_t data[RS485_RX_BUF_SIZE]; // 数据缓冲区
uint8_t dataLen; // 接收到的数据长度
RS485_RX_StateTypeDef state; // 接收状态
} RS485_RX_TypeDef;
// 定义RS485接收结构体变量
RS485_RX_TypeDef rs485Rx = {0};
// RS485接收中断处理函数
void USART1_IRQHandler(void)
{
// 接收中断
if (USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) {
switch (rs485Rx.state) {
case RS485_RX_IDLE:
// 等待起始符
if (USART_ReceiveData(USART1) == 0xAAAA) {
rs485Rx.state = RS485_RX_START;
rs485Rx.dataLen = 0;
}
break;
case RS485_RX_START:
// 接收数据
rs485Rx.data[rs485Rx.dataLen++] = USART_ReceiveData(USART1);
if (rs485Rx.dataLen >= RS485_RX_BUF_SIZE) {
rs485Rx.state = RS485_RX_ERROR;
} else {
rs485Rx.state = RS485_RX_RECEIVING;
}
break;
case RS485_RX_RECEIVING:
// 接收数据
rs485Rx.data[rs485Rx.dataLen++] = USART_ReceiveData(USART1);
if (rs485Rx.dataLen >= RS485_RX_BUF_SIZE) {
rs485Rx.state = RS485_RX_ERROR;
} else {
rs485Rx.state = RS485_RX_COMPLETE;
}
break;
default:
break;
}
}
}
int main(void)
{
// 初始化USART1
USART_InitTypeDef usart1_init;
usart1_init.USART_BaudRate = 115200;
usart1_init.USART_WordLength = USART_WordLength_8b;
usart1_init.USART_StopBits = USART_StopBits_1;
usart1_init.USART_Parity = USART_Parity_No;
usart1_init.USART_Mode = USART_Mode_Rx;
usart1_init.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_Init(USART1, &usart1_init);
// 使能USART1接收中断
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
// 使能USART1
USART_Cmd(USART1, ENABLE);
while (1) {
// 接收完成
if (rs485Rx.state == RS485_RX_COMPLETE) {
// 处理接收到的数据
for (uint8_t i = 0; i < rs485Rx.dataLen; i++) {
printf("%d ", rs485Rx.data[i]);
}
printf("\n");
// 清空接收缓冲区
memset(&rs485Rx, 0, sizeof(RS485_RX_TypeDef));
// 重置接收状态
rs485Rx.state = RS485_RX_IDLE;
}
// 接收出错
if (rs485Rx.state == RS485_RX_ERROR) {
// 清空接收缓冲区
memset(&rs485Rx, 0, sizeof(RS485_RX_TypeDef));
// 重置接收状态
rs485Rx.state = RS485_RX_IDLE;
}
}
}
```
在以上代码中,我们定义了一个`RS485_RX_TypeDef`结构体来存储接收到的数据和接收状态,使用了一个状态机来控制接收过程。在`USART1_IRQHandler()`中断处理函数中,我们根据接收状态来进行相应的操作,当接收完成或出错时,我们需要重置接收状态并清空缓冲区。在主函数中,我们不停地检查接收状态并处理接收到的数据。
阅读全文