C#串口通信三步走

第一步:实例化串口通讯类

 SerialPort sp = new SerialPort();

第二步:设置串口信息并打开串口

  //串口设置
    public void SetSP(string PortName,string BaudRate,string DataBits,string StopBits,string Command)
    {
        sp.Close();
        sp.PortName = PortName;//串口号
        sp.BaudRate = int.Parse(BaudRate);//波特率
        sp.DataBits = int.Parse(DataBits);//数据位
        sp.StopBits = (StopBits)int.Parse(StopBits);//停止位
        sp.ReadTimeout = 500;//读取数据的超时时间,引发ReadExisting异常
        bntSwitchSP_Click(Command);//开串口
    }
    //打开串口
        private void bntSwitchSP_Click(string command)
        {
            if (sp.PortName!= "" && sp.BaudRate!= "" && sp.DataBits!= "" && sp.StopBits!= "")
            {
                try
                {
                    if (sp.IsOpen)
                    {   
                    	sp.Close();
                        sp.Open();//打开串口
                    }
                    else
                    {
                        sp.Open();//打开串口
                    }
                    ToSendMessage(command);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("错误:" + ex.Message, "C#串口通信");
                }
            }
            else
            {
                MessageBox.Show("请先设置串口!", "RS232串口通信");
            }           
        }

第三步:发送指令

   //发送数据
    public void ToSendMessage()
    {
        if (sp.IsOpen)
        {
            try
            {
                sp.Encoding = System.Text.Encoding.GetEncoding("GB2312");
                string Command = "100110010001111101";
                
                //发送数据(类型:十六进制)
                sp.Write(strToHexByte(Command ), 0, strToHexByte(Command ).Length);
                
                发送数据(类型:字符串)
                //sp.Write(SerialCommand);
                
                //发送成功!
            }
            catch (Exception ex)
            {
                MessageBox.Show("错误:" + ex.Message);
            }
        }
        else
        {
            MessageBox.Show("串口未打开!");
        }
    }
    // 字符串转换成16进制编码
    private byte[] strToHexByte(string hexString)
    {
        hexString = hexString.Replace(" ", "");
        if ((hexString.Length % 2) != 0) hexString += " ";
        byte[] returnBytes = new byte[hexString.Length / 2];
        for (int i = 0; i < returnBytes.Length; i++)
            returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Replace(" ", ""), 16);
        return returnBytes;
    }

大功告成,学会了没有啊在这里插入图片描述
2021年12月29日遇到的问题:
打包时报错The type or namespace name ‘SerialPort’ could not be found (are you missing
解决方式:
更换api版本为.NET 4.x
在这里插入图片描述

监听串口信息可以参考下方脚本
监听:

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
 
namespace HtTcp
{
    public delegate void ITCPAcsEvents_OnEventEventHandler(string _Type, string _ReturnValue);
 
    public class HtTcpAcs
    {
        public event ITCPAcsEvents_OnEventEventHandler OnEvent;
       
 
       
        public HtTcpAcs()
        {
 
        }
 
        public void HtTcpAcsx(string IpAddress,int IpPorts)
        {
            Socket serverSocket;
 
            IPEndPoint ephost = new IPEndPoint(IPAddress.Parse(IpAddress), IpPorts);
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 
            #region 发送接收
            try
            {
                int counter = 0;
                string retrunValue = "";
                string retrunType = "";
                serverSocket.Connect(ephost);
                while (true)
                {
                    //接收的消息 暂定获取1M数据
                    Byte[] recvBytes = new Byte[2048];
                    Int32 bytes = serverSocket.Receive(recvBytes, recvBytes.Length, SocketFlags.None);
 
                    string msg = TcpDataHelp.ToHexString(recvBytes, recvBytes.Length).ToUpper();
 
                    //截取有效帧数据
                    int i = msg.IndexOf("3A") + 2;
                    int j = msg.IndexOf("0D0A");
                    string strred = msg.Substring(i, j - i);
                    string strxy = strred.Substring(0, strred.Length - 2);
                    string strbd = strred.Substring(strred.Length - 2, 2);
 
                    if (TcpValidate.CheckSumgz(strxy) == strbd)
                    {
                        //获取编码
                        string funCode = strxy.Substring(2, 2);
                        //判断编码 区分数据解析函数
                        switch (funCode)
                        {
                             retrunValue = Convert.ToInt64(strxy.Substring(4, strxy.Length - 4), 16).ToString();
                        }
                        if (OnEvent!=null)
                        {
                            OnEvent(funCode, retrunValue);
                        }
                    }
                    //Thread.Sleep(100);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(<span style="font-family: Arial, Helvetica, sans-serif;">"连接/发送/接收过程中,发生了错误!\r\n"</span><span style="font-family: Arial, Helvetica, sans-serif;">)</span>
            }
            finally
            {
                serverSocket.Close();
            }
            #endregion
        }
        //监听控制器
    }
}

原文链接:https://blog.csdn.net/li_ser/article/details/52681353

posted @ 2022-06-22 18:05  哒哒哒~~~  阅读(797)  评论(0编辑  收藏  举报