zoukankan      html  css  js  c++  java
  • C#串口通信

    目录

    1、SerialPort类

    2、代码讲解

    3、实例


    1、SerialPort类

      命名空间:System.IO.Ports

      程序集:System(在 System.dll 中)

      构造函数:SerialPort()

      属性:BaudRate

         BytesToRead  接受缓冲区数据的字节数

         BytesToWrite  发送缓冲区数据的字节数

         DataBits     数据长度

         HandShake   握手协议

           IsOpen     该值指示 SerialPort 对象的打开或关闭状态

         Parity      设置奇偶校验检查协议

           PortName    设置通信端口

         StopBits     停止位

         ReadBufferSize    SerialPort 输入缓冲区的大小

         WriteBufferSize   SerialPort输出缓冲区的大小

         ReadTimeout  读操作是阻塞的,当读操作为未完成时的超时时间

         WriteTimeout     写操作是阻塞的,当写操作为未完成时的超时时间

      方法:Close

         Open

         GetPortNames       获取串口名称数组

         ReadLine     从读缓冲区读取字符串和NewLine

           WriteLine    将指定的字符串和 NewLine 值写入输出缓冲区

         Read

         public int Read(byte[] buffer ,int offset,int count)

                  buffer//将输入写入到其中的字节数

                  offset//缓冲区数组中开始写入的偏移量

                  count//要读取的字节数

                  返回值//读取的字节数

         Write 

     示例:

      1 using System;
      2 using System.IO.Ports;
      3 using System.Threading;
      4 
      5 public class PortChat
      6 {
      7     static bool _continue;
      8     static SerialPort _serialPort;
      9 
     10     public static void Main()
     11     {
     12         string name;
     13         string message;
     14         StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
     15         Thread readThread = new Thread(Read);
     16 
     17         // Create a new SerialPort object with default settings.
     18         _serialPort = new SerialPort();
     19 
     20         // Allow the user to set the appropriate properties.
     21         _serialPort.PortName = SetPortName(_serialPort.PortName);
     22         _serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
     23         _serialPort.Parity = SetPortParity(_serialPort.Parity);
     24         _serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
     25         _serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
     26         _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);
     27 
     28         // Set the read/write timeouts
     29         _serialPort.ReadTimeout = 500;
     30         _serialPort.WriteTimeout = 500;
     31 
     32         _serialPort.Open();
     33         _continue = true;
     34         readThread.Start();
     35 
     36         Console.Write("Name: ");
     37         name = Console.ReadLine();
     38 
     39         Console.WriteLine("Type QUIT to exit");
     40 
     41         while (_continue)
     42         {
     43             message = Console.ReadLine();
     44 
     45             if (stringComparer.Equals("quit", message))
     46             {
     47                 _continue = false;
     48             }
     49             else
     50             {
     51                 _serialPort.WriteLine(
     52                     String.Format("<{0}>: {1}", name, message) );
     53             }
     54         }
     55 
     56         readThread.Join();
     57         _serialPort.Close();
     58     }
     59 
     60     public static void Read()
     61     {
     62         while (_continue)
     63         {
     64             try
     65             {
     66                 string message = _serialPort.ReadLine();
     67                 Console.WriteLine(message);
     68             }
     69             catch (TimeoutException) { }
     70         }
     71     }
     72 
     73     public static string SetPortName(string defaultPortName)
     74     {
     75         string portName;
     76 
     77         Console.WriteLine("Available Ports:");
     78         foreach (string s in SerialPort.GetPortNames())
     79         {
     80             Console.WriteLine("   {0}", s);
     81         }
     82 
     83         Console.Write("COM port({0}): ", defaultPortName);
     84         portName = Console.ReadLine();
     85 
     86         if (portName == "")
     87         {
     88             portName = defaultPortName;
     89         }
     90         return portName;
     91     }
     92 
     93     public static int SetPortBaudRate(int defaultPortBaudRate)
     94     {
     95         string baudRate;
     96 
     97         Console.Write("Baud Rate({0}): ", defaultPortBaudRate);
     98         baudRate = Console.ReadLine();
     99 
    100         if (baudRate == "")
    101         {
    102             baudRate = defaultPortBaudRate.ToString();
    103         }
    104 
    105         return int.Parse(baudRate);
    106     }
    107 
    108     public static Parity SetPortParity(Parity defaultPortParity)
    109     {
    110         string parity;
    111 
    112         Console.WriteLine("Available Parity options:");
    113         foreach (string s in Enum.GetNames(typeof(Parity)))
    114         {
    115             Console.WriteLine("   {0}", s);
    116         }
    117 
    118         Console.Write("Parity({0}):", defaultPortParity.ToString());
    119         parity = Console.ReadLine();
    120 
    121         if (parity == "")
    122         {
    123             parity = defaultPortParity.ToString();
    124         }
    125 
    126         return (Parity)Enum.Parse(typeof(Parity), parity);
    127     }
    128 
    129     public static int SetPortDataBits(int defaultPortDataBits)
    130     {
    131         string dataBits;
    132 
    133         Console.Write("Data Bits({0}): ", defaultPortDataBits);
    134         dataBits = Console.ReadLine();
    135 
    136         if (dataBits == "")
    137         {
    138             dataBits = defaultPortDataBits.ToString();
    139         }
    140 
    141         return int.Parse(dataBits);
    142     }
    143 
    144     public static StopBits SetPortStopBits(StopBits defaultPortStopBits)
    145     {
    146         string stopBits;
    147 
    148         Console.WriteLine("Available Stop Bits options:");
    149         foreach (string s in Enum.GetNames(typeof(StopBits)))
    150         {
    151             Console.WriteLine("   {0}", s);
    152         }
    153 
    154         Console.Write("Stop Bits({0}):", defaultPortStopBits.ToString());
    155         stopBits = Console.ReadLine();
    156 
    157         if (stopBits == "")
    158         {
    159             stopBits = defaultPortStopBits.ToString();
    160         }
    161 
    162         return (StopBits)Enum.Parse(typeof(StopBits), stopBits);
    163     }
    164 
    165     public static Handshake SetPortHandshake(Handshake defaultPortHandshake)
    166     {
    167         string handshake;
    168 
    169         Console.WriteLine("Available Handshake options:");
    170         foreach (string s in Enum.GetNames(typeof(Handshake)))
    171         {
    172             Console.WriteLine("   {0}", s);
    173         }
    174 
    175         Console.Write("Handshake({0}):", defaultPortHandshake.ToString());
    176         handshake = Console.ReadLine();
    177 
    178         if (handshake == "")
    179         {
    180             handshake = defaultPortHandshake.ToString();
    181         }
    182 
    183         return (Handshake)Enum.Parse(typeof(Handshake), handshake);
    184     }
    185 }
    View Code

      示例结果

    2、代码讲解

      2.1、串口设置

        端口号、波特率、数据位、停止位、校验

      

    //检查是否含有串口 
                string[] str = SerialPort.GetPortNames();
                if (str == null)
                {
                    MessageBox.Show("本机没有串口!", "Error");
                    return;
                }
    
                //添加串口项目
                foreach (string s in System.IO.Ports.SerialPort.GetPortNames())
                {//获取有多少个COM口
                 
                    comboBoxSerial.Items.Add(s);
                }
                comboBoxSerial.SelectedIndex = 1;//默认选择第一个COM1
                //添加事件注册
                Comm.DataReceived += Comm_DataReceived;
    
    //设置串口号
                        string serialName = comboBoxSerial.SelectedItem.ToString();
                        Comm.PortName = serialName;
    
                        //设置各“串口设置”
                        string strBaudRate = comboBoxBaudRate.Text;
                        string strDateBits = comboBoxDataBits.Text;
                        string strStopBits = comboBoxStop.Text;
                        Int32 iBaudRate = Convert.ToInt32(strBaudRate);
                        Int32 iDateBits = Convert.ToInt32(strDateBits);
    
    
                        Comm.BaudRate = iBaudRate;       //波特率
                        Comm.DataBits = iDateBits;       //数据位
    
                        switch (comboBoxStop.Text)       //停止位
                        {
                            case "1":
                                Comm.StopBits = StopBits.One;
                                break;
                            case "2":
                                Comm.StopBits = StopBits.Two;
                                break;
                            default:
                                MessageBox.Show("Error:参数不正确!", "Error");
                                break;
                        }
                        switch (comboBoxParity.Text)             //校验位
                        {
                            case "NONE":
                                Comm.Parity = Parity.None;
                                break;
                            case "ODD":
                                Comm.Parity = Parity.Odd;
                                break;
                            case "EVEN":
                                Comm.Parity = Parity.Even;
                                break;
                            default:
                                MessageBox.Show("Error:参数不正确!", "Error");
                                break;
                        }
    View Code

      2.2、接受函数

      如果接受的是以字符串格式发送的数据,则调用Encoding.ASCII.GetString(buf)将BYTE转换成String

      如果接受的是以HEX格式(16进制)发送的数据,则调用b.toString("X2")转化为16进制的字符串

    void Comm_DataReceived(object sender, SerialDataReceivedEventArgs e)
            {
                
                int n = Comm.BytesToRead;//先记录下来,避免某种原因,人为的原因,操作几次之间时间长,缓存不一致
                byte[] buf = new byte[n];//声明一个临时数组存储当前来的串口数据
                received_count += n;//增加接收计数
                Comm.Read(buf, 0, n);//读取缓冲数据
                builder.Clear();//清除字符串构造器的内容
            
             
                    //判断是否是显示为16禁止
                    if (checkBoxHexShow.Checked)
                    {
                        //依次的拼接出16进制字符串
                        foreach (byte b in buf)
                        {
                            builder.Append(b.ToString("X2") + " ");
                        }
                    }
                    else
                    {
                        //直接按ASCII规则转换成字符串
                        builder.Append(Encoding.ASCII.GetString(buf));
                    }
                    //追加的形式添加到文本框末端,并滚动到最后。
                    this.richTextBoxReceived.AppendText(builder.ToString());
                    labelGetCount.Text = "接受:" + received_count.ToString() + "字节";
            
    
            }
    View Code

      2.3、发送函数

      如果按字符串发送,这直接调用write(string)

      如果按16进制发送,则把字符串数组转换为按16进制转换为0-255的整数

    Convert.ToByte(value, numBase);
    numBase=16
    Converted '1' to 1.
    //       Converted '08' to 8.
    //       Converted '0F' to 15.
    //       Converted '11' to 17.
    //       Converted '12' to 18.
    //       Converted '30' to 48.
     private void buttonSend_Click(object sender, EventArgs e)
            {
                if (checkBoxTimeSend.Checked)
                {
                    timerSend.Enabled = true;
                }
                else
                {
                    timerSend.Enabled = false;
                }
                if(!Comm.IsOpen)
                {
                    MessageBox.Show("请先打开串口!","error");
                    return;
                }
                string strSend = richTextBoxSend.Text;
                int n = 0;
                if (checkBoxHexSend.Checked == true)//hex发送
                {
                    //处理数字转换·
    
                    string sendnoNull = strSend.Trim();
                    string sendNOComma = sendnoNull.Replace(',', ' ');    //去掉英文逗号
                    string sendNOComma1 = sendNOComma.Replace('', ' '); //去掉中文逗号
                    string strSendNoComma2 = sendNOComma1.Replace("0x", "");   //去掉0x
                    strSendNoComma2.Replace("0X", "");   //去掉0X
                    string[] strArray = strSendNoComma2.Split(' ');
    
                    int byteBufferLength = strArray.Length;
                    for (int i = 0; i < strArray.Length; i++)
                    {
                        if (strArray[i] == "")
                        {
                            byteBufferLength--;
                        }
                    }
                    byte[] byteBuffer = new byte[byteBufferLength];
                    for (int i = 0; i < strArray.Length; i++)
                    {
                        byteBuffer[i] = Convert.ToByte(strArray[i]);
                    }
                    Comm.Write(byteBuffer, 0, byteBufferLength);
                    n = byteBufferLength;
                }
                else//字符串发送
                {
                    Comm.Write(richTextBoxSend.Text);
                    n = richTextBoxSend.Text.Length;
                }
                send_count += n;
                labelSendCount.Text = "Send:" + send_count.ToString() + "字节";
             }
    View Code

        

    3实例

  • 相关阅读:
    Postgresql HStore 插件试用小结
    postgres-xl 安装与部署 【异常处理】ERROR: could not open file (null)/STDIN_***_0 for write, No such file or directory
    GPDB 5.x PSQL Quick Reference
    postgresql 数据库schema 复制
    hive 打印日志
    gp与 pg 查询进程
    jquery table 发送两次请求 解惑
    python 字符串拼接效率打脸帖
    postgresql 日期类型处理实践
    IBM Rational Rose软件下载以及全破解方法
  • 原文地址:https://www.cnblogs.com/void0/p/4256196.html
Copyright © 2011-2022 走看看