写一段基于STM32的单片机的函数程序实现: 从串口1接收由计算机发送过来的6个字节的数据串,其中,最后一个字节是前面5个字节的异或值(称为校验值)。在程序中进行校验,若计算的校验值和收到的校验值相同,则发回1;否则,发回0。通信参数:9600,n,8,1
时间: 2023-12-14 17:37:50 浏览: 32
下面是一个基于STM32的单片机的函数程序实现,可以实现从串口1接收由计算机发送过来的6个字节的数据串,其中,最后一个字节是前面5个字节的异或值(称为校验值)。在程序中进行校验,若计算的校验值和收到的校验值相同,则发回1;否则,发回0。通信参数为9600,n,8,1。
```c
#include "stm32f1xx_hal.h"
uint8_t RxBuffer[6]; // 接收缓存
uint8_t Checksum; // 校验和
void UART1_RxCpltCallback(UART_HandleTypeDef *huart) // 串口接收完成回调函数
{
if(huart->Instance == USART1)
{
static uint8_t Index = 0;
if(Index == 0) // 收到第一个字节时,清空缓存和校验和
{
memset(RxBuffer, 0, sizeof(RxBuffer));
Checksum = 0;
}
RxBuffer[Index++] = huart->Instance->DR;
Checksum ^= RxBuffer[Index - 1]; // 计算校验和
if(Index == 6) // 收到6个字节后,进行校验
{
if(Checksum == RxBuffer[5]) // 校验通过,发送1
{
uint8_t TxBuffer[] = {1};
HAL_UART_Transmit(huart, TxBuffer, sizeof(TxBuffer), HAL_MAX_DELAY);
}
else // 校验不通过,发送0
{
uint8_t TxBuffer[] = {0};
HAL_UART_Transmit(huart, TxBuffer, sizeof(TxBuffer), HAL_MAX_DELAY);
}
Index = 0;
}
}
}
int main(void)
{
// 初始化串口1为9600,n,8,1
UART_HandleTypeDef huart1;
huart1.Instance = USART1;
huart1.Init.BaudRate = 9600;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
HAL_UART_Init(&huart1);
// 开启中断接收
HAL_UART_Receive_IT(&huart1, RxBuffer, 1);
while (1)
{
// 主循环不需要做任何事情
}
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)