设计目的

  • 支持类似于单片机串口通信的协议设计
  • 输入必要信息
  • 一键自动添加帧头帧尾,校验位等组成完整的帧的内容
  • 方便检查传输内容是否正确

帧定义


【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在左填充高位
  • 错误报警防崩溃

源代码

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. namespace BspComProtocolMaker
  11. {
  12. public partial class Form1 : Form
  13. {
  14. public Form1()
  15. {
  16. InitializeComponent();
  17. }
  18. private void button1_Click(object sender, EventArgs e)
  19. {
  20. try
  21. {
  22. byte[] data = new byte[11];
  23. string frame = "";
  24. data[0] = (byte)0xA5;
  25. frame += Convert.ToString(data[0], 16).PadLeft(2, '0') + " ";
  26. data[1] = (byte)0x5A;
  27. frame += Convert.ToString(data[1], 16).PadLeft(2, '0') + " ";
  28. data[2] = (byte)(Convert.ToInt32(TextBox_AimID.Text, 16));
  29. frame += Convert.ToString(data[2], 16).PadLeft(2, '0') + " ";
  30. data[3] = (byte)(Convert.ToInt32(TextBox_MyID.Text, 16));
  31. frame += Convert.ToString(data[3], 16).PadLeft(2, '0') + " ";
  32. data[4] = (byte)(Convert.ToInt32(TextBox_FrameID.Text, 16));
  33. frame += Convert.ToString(data[4], 16).PadLeft(2, '0') + " ";
  34. data[5] = (byte)((Convert.ToInt32(TextBox_Data.Text) & 0xFF000000) >> 24);
  35. frame += Convert.ToString(data[5], 16).PadLeft(2, '0') + " ";
  36. data[6] = (byte)((Convert.ToInt32(TextBox_Data.Text) & 0x00FF0000) >> 16);
  37. frame += Convert.ToString(data[6], 16).PadLeft(2, '0') + " ";
  38. data[7] = (byte)((Convert.ToInt32(TextBox_Data.Text) & 0x0000FF00) >> 8);
  39. frame += Convert.ToString(data[7], 16).PadLeft(2, '0') + " ";
  40. data[8] = (byte)(Convert.ToInt32(TextBox_Data.Text) & 0x000000FF);
  41. frame += Convert.ToString(data[8], 16).PadLeft(2, '0') + " ";
  42. data[9] = (byte)(data[2] + data[3] + data[4] + data[5] + data[6] + data[7] + data[8]);
  43. frame += Convert.ToString(data[9], 16).PadLeft(2, '0') + " ";
  44. data[10] = (byte)0xAA;
  45. frame += Convert.ToString(data[10], 16);
  46. TextBox_Frame.Text = frame;
  47. }
  48. catch (Exception)
  49. {
  50. MessageBox.Show("生成发生错误,可能是输入帧信息格式错误导致的");
  51. }
  52. }
  53. }
  54. }

界面设计

【C#】简易协议帧生成器设计 - 图1

源文件

BspComProtocolMaker.rar