c#串口通信讲解(一)(winform、wpf)

发布时间 2023-08-06 18:09:41作者: 竹林听雨行

转载:https://blog.csdn.net/weixin_30466421/article/details/99278174

串口操作需要注意的几点如下:

1、如果是USB转串口;则需要安装USB转串口驱动,附件有此驱动。

2、串口打开状态最好不要直接插拔串口,可能会导致中控板或者串口线烧坏。

3、使用串口调试工具CEIWEI,下一章节会贴上使用教程

简单的串口收发通信,有以下步骤:

1、打开制定的串口、绑定串口接收事件

2、初始化串口指令

3、发送串口指令

 

-------打开串口代码--------

  1.  
    /// <summary>
  2.  
    /// 打开串口
  3.  
    /// </summary>
  4.  
    /// <param name="strPortName">串口号</param>
  5.  
    /// <param name="nRate">波特率</param>
  6.  
    /// <param name="nDataBit">数据位</param>
  7.  
    /// <param name="stopBits">停止位</param>
  8.  
    /// /// <param name="nParity">校验位</param>
  9.  
    /// <returns></returns>
  10.  
    public bool OpenSerial(string strPortName, int nRate, int nDataBit, float nStopBits, int nParity)
  11.  
    {
  12.  
    //这里就是绑定串口接收回调事件,即发送一条串口命令,发送成功,则会触发此事件进入ReciceSerialData方法,我们就进行判断发送成功还是失败。
  13.  
    serial.DataReceived += new SerialDataReceivedEventHandler(ReciveSerialData);
  14.  
    serial.PortName = strPortName;//串口号
  15.  
    serial.BaudRate = nRate;//波特率
  16.  
    float f = nStopBits;//停止位
  17.  
    if (f == 0)
  18.  
    {
  19.  
    serial.StopBits = StopBits.None;
  20.  
    }
  21.  
    else if (f == 1.5)
  22.  
    {
  23.  
    serial.StopBits = StopBits.OnePointFive;
  24.  
    }
  25.  
    else if (f == 1)
  26.  
    {
  27.  
    serial.StopBits = StopBits.One;
  28.  
    }
  29.  
    else
  30.  
    {
  31.  
    serial.StopBits = StopBits.Two;
  32.  
    }
  33.  
     
  34.  
    serial.DataBits = nDataBit;//数据位
  35.  
    if (nParity == 0) //校验位
  36.  
    {
  37.  
    serial.Parity = Parity.None;
  38.  
    }
  39.  
    else if (nParity == 1)
  40.  
    {
  41.  
    serial.Parity = Parity.Odd;
  42.  
    }
  43.  
    else if (nParity == 2)
  44.  
    {
  45.  
    serial.Parity = Parity.Even;
  46.  
    }
  47.  
    else
  48.  
    {
  49.  
    serial.Parity = Parity.None;
  50.  
    }
  51.  
     
  52.  
    serial.ReadTimeout = 3000;//设置超时读取时间
  53.  
    serial.WriteTimeout = 500;//超时写入时间
  54.  
    try
  55.  
    {
  56.  
    if (!serial.IsOpen)
  57.  
    {
  58.  
    serial.Open();
  59.  
    }
  60.  
    }
  61.  
    catch (Exception ex)
  62.  
    {
  63.  
    MessageBox.Show(ex.ToString());
  64.  
    return false;
  65.  
    }
  66.  
     
  67.  
    return true;
  68.  
     
  69.  
    }

 -------使用实例--------

  1.  
    //定义串口对象
  2.  
    private SerialPort serial = new SerialPort();
  3.  
     
  4.  
    //在按钮Click事件里调用打开串口的方法,串口COM号参数以本机具体串口号为准,COM1除外,如果只有COM1则需要安装串口驱动,见附件
  5.  
    private void btnOpenSerial_Click(object sender, EventArgs e)
  6.  
    {
  7.  
    if (!OpenSerial("COM3", 115200, 8, 1, 0))
  8.  
    {
  9.  
    //串口打开失败
  10.  
    MessageBox.Show("串口打开失败!");
  11.  
    }
  12.  
    }

-------初始化串口命令、发送指令-------

注:我这个命令并不是通用的,是根据我这边的中控板协议;发对应的命令,但是其他中控板的命令格式也是差不多的

  1.  
    /// <summary>
  2.  
    /// 初始化串口命令
  3.  
    /// </summary>
  4.  
    /// <param name="nStaus">操作类型</param>
  5.  
    public void InitialSerialCommand(int nStaus)
  6.  
    {
  7.  
    byte[] btyData = new byte[100];
  8.  
    btyData[0] = 0x5A;
  9.  
    btyData[1] = 0x55;
  10.  
    btyData[2] = 0x00;
  11.  
    btyData[3] = 0x00;
  12.  
    btyData[4] = 0x02;
  13.  
    btyData[5] = 0xD1;
  14.  
    btyData[6] = 0x00;
  15.  
    btyData[7] = 0x18;
  16.  
    btyData[8] = 0x6A;
  17.  
    btyData[9] = 0x69;
  18.  
     
  19.  
    //开灯
  20.  
    if (nStaus == 0)
  21.  
    {
  22.  
    btyData[6] = 0x01;
  23.  
    }
  24.  
    //全关
  25.  
    else
  26.  
    {
  27.  
    btyData[6] = 0x00;
  28.  
    }
  29.  
     
  30.  
    //发送指令
  31.  
    if (serial != null)
  32.  
    {
  33.  
    try
  34.  
    {
  35.  
    SerialWrite(0, btyData);
  36.  
    }
  37.  
    catch (Exception ex)
  38.  
    {
  39.  
    MessageBox.Show(ex.ToString());
  40.  
    }
  41.  
    }
  42.  
    }

---------串口回调方法-----------

  1.  
    /// <summary>
  2.  
    /// 接收数据事件
  3.  
    /// </summary>
  4.  
    /// <param name="sender"></param>
  5.  
    /// <param name="e"></param>
  6.  
    private void ReciveSerialData(object sender, SerialDataReceivedEventArgs e)
  7.  
    {
  8.  
    try
  9.  
    {
  10.  
    if (serial.BytesToRead == 0)
  11.  
    {
  12.  
    return;
  13.  
    }
  14.  
    byte[] btyReciveData = new byte[serial.BytesToRead];
  15.  
    byte[] btyResoureData = new byte[btyReciveData.Length];
  16.  
    string strData = string.Empty;
  17.  
    int intSp = serial.Read(btyReciveData, 0, btyReciveData.Length);//在此就可以读取到当前缓冲区内的数据
  18.  
    int i = 0;
  19.  
    string[] hex = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
  20.  
    for (i = 0; i < btyReciveData.Length; i++)
  21.  
    {
  22.  
    btyResoureData[i] = Convert.ToByte(("0x" + (hex[btyReciveData[i] / 16]).ToString() + (hex[btyReciveData[i] % 16]).ToString()), 16);
  23.  
    }
  24.  
    for (int a = 0; a < btyReciveData.Length; a++)
  25.  
    {
  26.  
    strData += btyResoureData[a].ToString("X2");
  27.  
    }
  28.  
     
  29.  
    //若串口命令发送成功,则会返回和发送指令一样的指令,我发送的指令是(5A55000002D101186A69 );返回的也是(5A55000002D101186A69 );则可以判定串口数据交互成功。
  30.  
    if (strData.IndexOf("5A55000002D101186A69") >= 0)
  31.  
    {
  32.  
    //发送成功
  33.  
    }
  34.  
     
  35.  
     
  36.  
     
  37.  
    }
  38.  
    catch (Exception ex)
  39.  
    {
  40.  
    MessageBox.Show(ex.ToString());
  41.  
    }
  42.  
    }

DEMO实例:https://files.cnblogs.com/files/henryzong/%E4%B8%B2%E5%8F%A3%E9%80%9A%E4%BF%A1DEMO.zip

串口驱动:https://files.cnblogs.com/files/henryzong/%E4%B8%B2%E5%8F%A3%E9%A9%B1%E5%8A%A8.zip

串口调试工具:https://files.cnblogs.com/files/henryzong/%E4%B8%B2%E5%8F%A3%E8%B0%83%E8%AF%95%E5%B7%A5%E5%85%B7.zip

转载于:https://www.cnblogs.com/henryzong/p/7429681.html