匿名飞控协议程序

整体程序

#include <stdio.h>
#include <iostream>
using namespace std;
#include <string>

#define BYTE0(dwTemp)       ( *( (char *)(&dwTemp)		) )
#define BYTE1(dwTemp)       ( *( (char *)(&dwTemp) + 1) )
#define BYTE2(dwTemp)       ( *( (char *)(&dwTemp) + 2) )
#define BYTE3(dwTemp)       ( *( (char *)(&dwTemp) + 3) )

static void SendPar(uint8_t dest_addr, uint16_t p_id)
{
    
    
	int p_val = 100;
	uint8_t otherDataTmp[64];

	uint8_t _cnt = 0;

	otherDataTmp[_cnt++] = 0xAA;
	otherDataTmp[_cnt++] = dest_addr;
	otherDataTmp[_cnt++] = 0xE2;
	otherDataTmp[_cnt++] = 0;

	otherDataTmp[_cnt++] = BYTE0(p_id);
	otherDataTmp[_cnt++] = BYTE1(p_id);

	otherDataTmp[_cnt++] = BYTE0(p_val);
	otherDataTmp[_cnt++] = BYTE1(p_val);
	otherDataTmp[_cnt++] = BYTE2(p_val);
	otherDataTmp[_cnt++] = BYTE3(p_val);

	otherDataTmp[3] = _cnt - 4;
	uint8_t check_sum1 = 0, check_sum2 = 0;
	for (uint8_t i = 0; i < _cnt; i++)
	{
    
    
		check_sum1 += otherDataTmp[i];
		check_sum2 += check_sum1;
	}
	otherDataTmp[_cnt++] = check_sum1;
	otherDataTmp[_cnt] = check_sum2;


	printf("0是:%x \n", otherDataTmp[0]);
	printf("1是:%x \n", otherDataTmp[1]);
	printf("2是:%x \n", otherDataTmp[2]);
	printf("3是:%x \n", otherDataTmp[3]);
	printf("4是:%x \n", otherDataTmp[4]);
	printf("5是:%x \n", otherDataTmp[5]);
	printf("6是:%x \n", otherDataTmp[6]);
	printf("7是:%x \n", otherDataTmp[7]);
	printf("8是:%x \n", otherDataTmp[8]);
	printf("9是:%x \n", otherDataTmp[9]);
	printf("10是:%x \n", otherDataTmp[10]);
	printf("11是:%x \n", otherDataTmp[11]);
	
	printf("CNT是:%d \n", _cnt);
	printf("check_sum1是:%x \n", check_sum1);
	printf("check_sum2是:%x \n", check_sum2);

}

void main()
{
    
    
	int addr = 0xFF;
	int id = 1000;
	SendPar(addr, id);
}

注意

如果打印的不够,可以在程序中适当的增加,改个数字即可

总结

在这个程序中,我认为有一个值得学习的地方

#define BYTE0(dwTemp)       ( *( (char *)(&dwTemp)		) )
#define BYTE1(dwTemp)       ( *( (char *)(&dwTemp) + 1) )
#define BYTE2(dwTemp)       ( *( (char *)(&dwTemp) + 2) )
#define BYTE3(dwTemp)       ( *( (char *)(&dwTemp) + 3) )

用上面的这个就可以实现:数据的转换 。可以不用专门查相关的转换函数,直接用程序中用到的方法来实现转换。同时也省去了字符串变成十六进制数组。

猜你喜欢

转载自blog.csdn.net/a919964703/article/details/125965380