[技术问答] C#制作串口助手源码

[复制链接]
5930|63
 楼主| mmbs 发表于 2023-7-27 08:00 | 显示全部楼层 |阅读模式
搜狗高速浏览器截图20230726231533.png
WinFormSeriport.zip (88.05 KB, 下载次数: 24)
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.IO.Ports;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.Windows.Forms;

  11. namespace WinFormSeriport
  12. {
  13.     public partial class FORM1 : Form
  14.     {
  15.         SerialPort sp = new SerialPort();
  16.         
  17.         public FORM1()
  18.         {
  19.             Control.CheckForIllegalCrossThreadCalls = false;
  20.             InitializeComponent();
  21.             sp.Close();
  22.             lbl_TxRx.Text = "Tx:" +0+" " + "Rx:" + 0;
  23.         }
  24.         private void Form1_Load_1(object sender, EventArgs e)
  25.         {
  26.             Timer_SendDate.Interval = 1000;
  27.             Timer_SendDate.Stop();
  28.         }

  29.         
  30.         private void Form1_MouseMove(object sender, MouseEventArgs e)
  31.         {
  32.             lbl_Move.Text = e.X.ToString() + " " + e.Y.ToString();
  33.         }

  34.       

  35.         private void serialPort1_ErrorReceived(object sender, System.IO.Ports.SerialErrorReceivedEventArgs e)
  36.         {
  37.             MessageBox.Show("接收数据时发生未知错误!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Information);
  38.         }

  39.         private void btn_OpenSerial_Click(object sender, EventArgs e)
  40.         {
  41.             if (sp.IsOpen == false)
  42.             {
  43.                 btn_OpenSerial.Text = "开启串口";
  44.                 try
  45.                 {
  46.                     sp.PortName = comboBox_Com.Text;
  47.                     sp.BaudRate = Convert.ToInt32(comboBox_Bot.Text);
  48.                     sp.Parity = (System.IO.Ports.Parity)Enum.Parse(typeof(System.IO.Ports.Parity), comboBox_Parity.Text);
  49.                     sp.DataBits = Convert.ToInt16(comboBox_DateBit.Text);
  50.                     sp.StopBits = (System.IO.Ports.StopBits)Enum.Parse(typeof(System.IO.Ports.StopBits), comboBox_StopBit.Text);
  51.                     sp.Encoding = Encoding.Default;    //设置串口编码为default:获取操作系统的当前 ANSI 代码页的编码。
  52.                     sp.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived);

  53.                     sp.Open();    //开启串口
  54.                     if (checkBox_ClearShow.Checked)   //如果开启了自动清空功能
  55.                         Timer_SendDate.Start();

  56.                     btn_OpenSerial.Text = "关闭串口";
  57.                 }
  58.                 catch
  59.                 {
  60.                     MessageBox.Show("配置串口出错,检查各项参数是否设置!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
  61.                 }
  62.             }
  63.             else
  64.             {
  65.                 btn_OpenSerial.Text = "关闭串口";
  66.                 try
  67.                 {
  68.                     sp.Close();

  69.                     btn_OpenSerial.Text = "开启串口";
  70.                     MessageBox.Show("串口已关闭!","提示",MessageBoxButtons.OK, MessageBoxIcon.Information);
  71.                 }
  72.                 catch
  73.                 {
  74.                     MessageBox.Show("出现未知错误,串口关闭失败!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);      
  75.                 }
  76.             }

  77.         }
  78.         string receiveData;
  79.         UInt32 receiveBytesCount;
  80.         string sendData;
  81.         UInt32 sendBytesCount;
  82.         private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
  83.         {

  84.             receiveData = sp.ReadExisting();
  85.             receiveBytesCount += (UInt32)receiveData.Length;


  86.             //字符串显示
  87.             if (checkBox_ClearShow.Checked == false)
  88.             {
  89.                 if (checkBox_16Show.Checked == false)   //hex 方式显示
  90.                 {
  91.                     richtxtbox_ShowGetNumber.AppendText(receiveData);
  92.                     richtxtbox_ShowGetNumber.Focus();   //让光标到这来
  93.                     richtxtbox_ShowGetNumber.Select(richtxtbox_ShowGetNumber.TextLength, 0);
  94.                     this.richtxtbox_ShowGetNumber.ScrollToCaret(); //设置光标到最后
  95.                 }
  96.                 //16进制显示
  97.                 else
  98.                 {
  99.                     byte[] recData = System.Text.Encoding.Default.GetBytes(receiveData);// 将接受到的字符串据转化成数组;  

  100.                     foreach (byte str in recData)
  101.                     {
  102.                         richtxtbox_ShowGetNumber.AppendText(string.Format("{0:X2} ", str));
  103.                     }
  104.                 }
  105.             }
  106.             lbl_TxRx.Text = "Tx:" + sendBytesCount.ToString()+" " + "Rx:" + receiveBytesCount.ToString();
  107.         }


  108.         private void btn_GetCom_Click(object sender, EventArgs e)  //自动获取串口号
  109.         {
  110.             string[] serialPortName = System.IO.Ports.SerialPort.GetPortNames();

  111.             foreach (string name in serialPortName)
  112.             {
  113.                 comboBox_Com.Text = name;
  114.             }
  115.         }

  116.         private void btn_Send_Click(object sender, EventArgs e)
  117.         {
  118.             if (sp.IsOpen == false)
  119.             {
  120.                 btn_OpenSerial.Text = "开启串口";
  121.                 MessageBox.Show("请打开串口!", "错误",MessageBoxButtons.OK, MessageBoxIcon.Information);
  122.             }
  123.             else
  124.             {
  125.                 btn_OpenSerial.Text = "关闭串口";
  126.                 if (checkBox_SendByItself.Checked)
  127.                 {
  128.                     Timer_SendDate.Interval = Convert.ToInt32(textBox_SendTime.Text);
  129.                     Timer_SendDate.Start();
  130.                 }
  131.                 sendData = richTextBox_Send.Text;
  132.                 if (checkBox_SendIn16.Checked == false)
  133.                 {
  134.                     sp.Write(sendData);
  135.                 }
  136.                 else
  137.                 {
  138.                     try
  139.                     {
  140.                         sendData.Replace("0x", "");   //去掉0x
  141.                         sendData.Replace("0X", "");   //去掉0X
  142.                         //  sendData.

  143.                         string[] strArray = sendData.Split(new char[] { ',', ',', '\r', '\n', ' ', '\t' });
  144.                         int decNum = 0;
  145.                         int i = 0;
  146.                         byte[] sendBuffer = new byte[strArray.Length];  //发送数据缓冲区

  147.                         foreach (string str in strArray)
  148.                         {
  149.                             try
  150.                             {
  151.                                 decNum = Convert.ToInt16(str, 16);
  152.                                 sendBuffer[i] = Convert.ToByte(decNum);
  153.                                 i++;
  154.                             }
  155.                             catch
  156.                             {

  157.                             }
  158.                         }
  159.                         sp.Write(sendBuffer, 0, sendBuffer.Length);

  160.                         //更新发送数据计数
  161.                         sendBytesCount += (UInt32)sendBuffer.Length;

  162.                         lbl_TxRx.Text = "Tx:" + sendBytesCount.ToString()+" " + "Rx:" + receiveBytesCount.ToString();

  163.                     }
  164.                     catch
  165.                     {

  166.                     }
  167.                 }
  168.             }
  169.         }

  170.         private void Timer_SendDate_Tick(object sender, EventArgs e)
  171.         {

  172.             if (checkBox_ClearShow.Checked)
  173.                 richtxtbox_ShowGetNumber.Text = null;

  174.             sendData = richTextBox_Send.Text;
  175.    
  176.             if (sp.IsOpen)
  177.             {
  178.                 btn_OpenSerial.Text = "关闭串口";
  179.                 if (checkBox_SendByItself.Checked)
  180.                 {
  181.                     if (checkBox_SendIn16.Checked == false)
  182.                     {
  183.                         sp.Write(sendData);
  184.                     }
  185.                     else
  186.                     {
  187.                         try
  188.                         {
  189.                             sendData.Replace("0x", "");   //去掉0x
  190.                             sendData.Replace("0X", "");   //去掉0X
  191.                             //  sendData.

  192.                             string[] strArray = sendData.Split(new char[] { ',', ',', '\r', '\n', ' ', '\t' });
  193.                             int decNum = 0;
  194.                             int i = 0;
  195.                             byte[] sendBuffer = new byte[strArray.Length];  //发送数据缓冲区

  196.       

  197.                             foreach (string str in strArray)
  198.                             {
  199.                                 try
  200.                                 {
  201.                                     decNum = Convert.ToInt16(str, 16);
  202.                                     sendBuffer[i] = Convert.ToByte(decNum);
  203.                                     i++;
  204.                                 }
  205.                                 catch
  206.                                 {

  207.                                 }
  208.                             }
  209.                             sp.Write(sendBuffer, 0, sendBuffer.Length);

  210.                         }
  211.                         catch
  212.                         {

  213.                         }
  214.                     }
  215.                     //更新发送数据计数
  216.                     sendBytesCount += (UInt32)sendData.Length;

  217.                     lbl_TxRx.Text = "Tx:" + sendBytesCount.ToString()+" " + "Rx:" + receiveBytesCount.ToString();
  218.                 }
  219.                 else
  220.                 {
  221.                  if (checkBox_ClearShow.Checked)
  222.                     checkBox_SendByItself.CheckState=CheckState .Unchecked ;
  223.                 else
  224.                     Timer_SendDate.Stop();
  225.                 }
  226.             }

  227.             else
  228.             {
  229.                     btn_OpenSerial.Text = "开启串口";
  230.                     Timer_SendDate.Stop();
  231.                     MessageBox.Show("串口已经关闭!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Information);      
  232.             }
  233.         
  234.         }

  235.         private void btn_ClearAll_Click(object sender, EventArgs e)
  236.         {
  237.             richtxtbox_ShowGetNumber.Text = null;
  238.             richTextBox_Send.Text = null;
  239.         }
  240.     }
  241. }


zerorobert 发表于 2023-8-7 16:15 | 显示全部楼层
用C#写的串口通信程序的源代码,就像串口调试助手那种软件
vivilyly 发表于 2023-8-7 16:25 | 显示全部楼层
在使用串口通信时,可能会遇到各种异常情况,例如读写超时、数据错误等。需要注意的是,需要在代码中处理这些异常情况,以保证程序的健壮性和稳定性。
pmp 发表于 2023-8-7 16:49 | 显示全部楼层
怎么实现串口发送文件的               
cashrwood 发表于 2023-8-7 17:14 | 显示全部楼层
如何使用C#编写串口程序?               
jkl21 发表于 2023-8-7 17:36 | 显示全部楼层
串口通信通常需要使用多线程来实现数据的发送和接收。在源码中要注意线程安全,避免多个线程同时访问串口资源导致的竞态条件和数据混乱问题。
tifmill 发表于 2023-8-7 17:57 | 显示全部楼层
在源码中要考虑到这些异常情况,并进行适当的异常处理,以确保程序的稳定性和可靠性。
xiaoyaodz 发表于 2023-8-7 18:20 | 显示全部楼层
在源码中要实现相应的数据解析算法,将字节流转换为可读的数据格式。
updownq 发表于 2023-8-7 18:42 | 显示全部楼层
串口助手通常需要一个用户界面,用于显示接收到的数据、发送数据等操作。
pmp 发表于 2023-8-7 19:03 | 显示全部楼层
C#中有很多不同的串口库可供选择,例如SerialPort、ComPort、SerialPortEx等。选择合适的串口库可以帮助你更快地实现串口通信。
tabmone 发表于 2023-8-7 19:25 | 显示全部楼层
在使用完串口后,要及时释放相关的资源,如关闭串口、释放线程等,以避免资源泄露和系统性能下降。
timfordlare 发表于 2023-8-7 19:46 | 显示全部楼层
需要考虑线程同步的问题。               
yorkbarney 发表于 2023-8-7 20:09 | 显示全部楼层
用C#中的SerialPort写一个通信串口调试程序
rosemoore 发表于 2023-8-7 20:31 | 显示全部楼层
怎么实现利用C#编上位机程序,然后通过串口
usysm 发表于 2023-8-7 20:52 | 显示全部楼层
你可能需要解析接收到的数据,并根据约定的协议进行相应的处理。确保对接收到的数据进行正确解析和处理,以满足应用需求。
1988020566 发表于 2023-8-7 21:15 | 显示全部楼层
在使用串口通信时,需要注意保护自己的代码和数据
pl202 发表于 2023-8-7 21:37 | 显示全部楼层
需要在代码中添加串口助手的功能,例如读写串口数据、设置串口参数、显示串口通信日志等
minzisc 发表于 2023-8-7 21:59 | 显示全部楼层
建议使用异步方式进行数据传输。这样可以避免主线程阻塞,同时提高程序的响应性能。
wilhelmina2 发表于 2023-8-7 22:21 | 显示全部楼层
在实际使用串口时,要考虑到可能的异常情况,如设备拔出、通信异常等
backlugin 发表于 2023-8-7 22:42 | 显示全部楼层
求一套C#串口助手的源码               
您需要登录后才可以回帖 登录 | 注册

本版积分规则

197

主题

6917

帖子

3

粉丝
快速回复 在线客服 返回列表 返回顶部