Files
car_stm32f103vet6/Core/Bsp/checksum.c

24 lines
760 B
C
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include <stdint.h>
/**
* @brief 计算校验和
* @param buf: 数据缓冲区指针 (即你的 uart1_rx_buf)
* @param start_pos: 校验数据的起始下标 (通常跳过帧头 "LOGI:")
* @param length: 需要校验的数据长度 (不包含校验位本身和帧尾)
* @return uint8_t: 计算得出的校验和
*
* 算法说明: 将所有字节相加取低8位 (相当于 % 256)
*/
uint8_t Calculate_CheckSum(uint8_t *buf, uint16_t start_pos, uint16_t length)
{
uint32_t sum = 0; // 使用32位防止累加溢出虽然uint8累加也不会溢出单片机寄存器
uint16_t i;
for (i = 0; i < length; i++)
{
sum += buf[start_pos + i];
}
// 返回低8位相当于 sum % 256
return (uint8_t)(sum & 0xFF);
}