#include <stdio.h>
#include <string.h>
typedef unsigned char uint8_t;
typedef unsigned int uint32_t;
typedef struct {
uint32_t header;
uint32_t length;
uint32_t data[7];
uint32_t checksum;
} Packet;
uint32_t gData[10];
// 计算校验和的函数
uint32_t calculate_checksum(Packet* packet, uint32_t length)
{
uint32_t checksum = 0;
uint32_t data[10];
memcpy(&data, packet, sizeof(Packet));
for (uint8_t i = 0; i < (length / sizeof(uint32_t)); i++)
{
checksum += data[i];
}
return checksum;
}
uint32_t port_send(Packet packet, uint32_t length)
{
memcpy(&gData, &packet, sizeof(Packet));
}
uint32_t port_recv(Packet* packet, uint32_t length)
{
memcpy(packet, &gData, sizeof(Packet));
memset(&gData, 0, sizeof(Packet));
}
uint32_t sendA()
{
Packet packet;
packet.header = 0xA0;
packet.length = 7;
for(uint8_t i = 0; i < 7; i++)
{
packet.data[i] = 0x01;
}
packet.checksum = calculate_checksum(&packet, sizeof(packet) - sizeof(packet.checksum));
printf("\nsendchecksum: 0x%x\n\n", packet.checksum);
port_send(packet, sizeof(Packet));
}
uint32_t recvA()
{
uint32_t checksum_cal;
Packet received_packet;
port_recv(&received_packet, sizeof(Packet));
printf("recv header: 0x%x\n", received_packet.header);
printf("recv length: 0x%x\n", received_packet.length);
for(uint8_t i = 0; i < 7; i++)
{
printf("recv data[%d]: 0x%x\n", i, received_packet.data[i]);
}
printf("recv checksum: 0x%x\n", received_packet.checksum);
checksum_cal = calculate_checksum(&received_packet,
sizeof(Packet) - sizeof(received_packet.checksum));
printf("\nchecksum_cal: 0x%x\n", checksum_cal);
if (received_packet.checksum == checksum_cal)
{
// 校验和验证通过
printf("校验和验证通过\n\n");
}
else
{
// 校验和验证失败
printf("校验和验证失败\n\n");
return 1;
}
}
int main()
{
sendA();
recvA();
return 0;
}
简单的C语言收发接口,包含校验和
最新推荐文章于 2024-08-23 18:38:13 发布