设计目的
- 支持类似于单片机串口通信的协议设计
- 输入必要信息
- 一键自动添加帧头帧尾,校验位等组成完整的帧的内容
- 方便检查传输内容是否正确
帧定义
见
【RT-Thread】基于串口的小型板级通信模块
https://www.yuque.com/wangxi_chn/qaxke0/xpkyvm
Module library based on RT-Thread operate system
https://gitee.com/WangXi_Chn/RttOs_ModuleLib
所需功能
- 字符串以十六进制转整形
- 整形数据按位拆分
- 整型数据转十六进制字符串,并用0在左填充高位
- 错误报警防崩溃
源代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BspComProtocolMaker
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
byte[] data = new byte[11];
string frame = "";
data[0] = (byte)0xA5;
frame += Convert.ToString(data[0], 16).PadLeft(2, '0') + " ";
data[1] = (byte)0x5A;
frame += Convert.ToString(data[1], 16).PadLeft(2, '0') + " ";
data[2] = (byte)(Convert.ToInt32(TextBox_AimID.Text, 16));
frame += Convert.ToString(data[2], 16).PadLeft(2, '0') + " ";
data[3] = (byte)(Convert.ToInt32(TextBox_MyID.Text, 16));
frame += Convert.ToString(data[3], 16).PadLeft(2, '0') + " ";
data[4] = (byte)(Convert.ToInt32(TextBox_FrameID.Text, 16));
frame += Convert.ToString(data[4], 16).PadLeft(2, '0') + " ";
data[5] = (byte)((Convert.ToInt32(TextBox_Data.Text) & 0xFF000000) >> 24);
frame += Convert.ToString(data[5], 16).PadLeft(2, '0') + " ";
data[6] = (byte)((Convert.ToInt32(TextBox_Data.Text) & 0x00FF0000) >> 16);
frame += Convert.ToString(data[6], 16).PadLeft(2, '0') + " ";
data[7] = (byte)((Convert.ToInt32(TextBox_Data.Text) & 0x0000FF00) >> 8);
frame += Convert.ToString(data[7], 16).PadLeft(2, '0') + " ";
data[8] = (byte)(Convert.ToInt32(TextBox_Data.Text) & 0x000000FF);
frame += Convert.ToString(data[8], 16).PadLeft(2, '0') + " ";
data[9] = (byte)(data[2] + data[3] + data[4] + data[5] + data[6] + data[7] + data[8]);
frame += Convert.ToString(data[9], 16).PadLeft(2, '0') + " ";
data[10] = (byte)0xAA;
frame += Convert.ToString(data[10], 16);
TextBox_Frame.Text = frame;
}
catch (Exception)
{
MessageBox.Show("生成发生错误,可能是输入帧信息格式错误导致的");
}
}
}
}