C# 串口通信代码

//引用命名空间
using System.IO.Ports;

private SerialPort comm = new SerialPort();
private void initComm()
{
    try
    {
        //初始化SerialPort对象     
        comm.NewLine = "/r/n";
        comm.RtsEnable = true;//根据实际情况吧。     
        //添加事件注册     
        comm.DataReceived += comm_DataReceived;

        if (comm.IsOpen)
        {
            comm.Close();
        }
        else
        {
            //关闭时点击,则设置好端口,波特率后打开     
            comm.PortName = SysCommmon.COM;
            comm.BaudRate = SysCommmon.Baudrate;
            try
            {
                comm.Open();
            }
            catch (Exception ex)
            {
                comm = new SerialPort();
                setMsg("打开COM口[" + SysCommmon.COM + "]异常:" + ex.Message);
            }
        }
    }
    catch (Exception err)
    {
        setMsg("初始化COM口过程异常:" + err.Message);
    }
}


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();//清除字符串构造器的内容     
    //builder.Length = 0;
    //因为要访问ui资源,所以需要使用invoke方式同步ui。     
    this.Invoke((EventHandler)(delegate
    {
        //直接按ASCII规则转换成字符串     
        enter_TaiPei(Encoding.ASCII.GetString(buf));
        //this.WindowState = FormWindowState.Normal;
        //this.Show();
    }));
}

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO.Ports; using System.Windows.Forms; namespace SComm { public class Com { private SerialPort sport; /// <summary> /// 设置发送缓冲区大小 /// </summary> public int outBufferSize { set { sport.WriteBufferSize = value; } } /// <summary> /// 设置接收缓冲区大小 /// </summary> public int inBufferSize { set { sport.ReadBufferSize = value; } } public Com() { sport = new SerialPort(); } /// <summary> /// 初始化 /// </summary> /// <param name="portName">端口名称</param> /// <param name="rate">波特率</param> /// <param name="parity">校验方式</param> public Com(string portName,int rate,Parity parity) { sport = new SerialPort(portName,rate,parity); } public bool InitCom() { if (sport.IsOpen) return true; else { try { sport.Open(); return true; } catch (Exception e) { return false; } } } public void Close() { if (sport.IsOpen) sport.Close(); } /// <summary> /// 串口设置并打开 /// </summary> /// <param name="portName"></param> /// <param name="rate"></param> /// <param name="parity"></param> /// <returns></returns> public bool InitCom(string portName, int rate, Parity parity) { if (sport.IsOpen) sport.Close(); sport.BaudRate = rate; sport.PortName = portName; sport.Parity = parity; try { sport.Open(); return true; } catch (Exception e) { return false; } } /// <summary> /// 发送字节 /// </summary> /// <param name="writeBytes">要发送的字节</param> /// <param name="count">发送字节的数量</param> /// <returns></returns> public bool write(byte[] writeBytes,int count) { if (InitCom()) { try { sport.Write(writeBytes, 0, count); return true; } catch (Exception e) { return false; } } return false; } /// <summary> /// 发送字符串 /// </summary> /// <param name="writestrs"></param> /// <returns></returns> public bool write(string writeStrs) { if (InitCom()) { try { sport.Write(writeStrs); System.Threading.Thread.Sleep(100); return true; } catch { return false; } } return false; } /// <summary> /// 读取数据 /// </summary> /// <param name="NumBytes">读取的字节数</param> /// <returns></returns> public byte[] Read(int NumBytes) { byte[] inbuffer=null; if (sport.IsOpen && sport.BytesToRead > 0) { if (NumBytes > sport.BytesToRead) NumBytes = sport.BytesToRead; try { int b = sport.ReadByte(); string s = sport.ReadExisting(); string s1 = sport.NewLine; // string ss = sport.ReadLine(); inbuffer = new byte[NumBytes]; int count = sport.Read(inbuffer, 0, NumBytes); } catch (TimeoutException) { throw; } } // sport.Close(); return inbuffer; } public byte[] Read() { return Read(sport.BytesToRead); } public string ReadLine() { try { if (sport.IsOpen && sport.BytesToRead > 0) { string s = sport.ReadExisting(); return sport.ReadLine(); } return null; } catch (TimeoutException e) { return e.Message; } } public string ReadExisting() { return sport.ReadExisting(); } public void SendSignal(byte cmd) { byte[] hexdata = new byte[5]; hexdata[0] = 0x01; hexdata[1] = 0x03; hexdata[2] = cmd; ushort crc = CommWithARM. CRC_16(hexdata, 3); hexdata[3] = (byte)(crc / 256); hexdata[4] = (byte)(crc % 256); write(hexdata, 5); } public void OnOnCommMscomm1() { byte[] rxdata= Read(); ////string srxdata = ReadLine(); int i = 0; try ////{ //// foreach (char s in srxdata) //// { //// rxdata[i++] = (byte)s; //// } ////} ////catch { } if (rxdata != null) { int len = rxdata.Length; if (len == 23) { CommWithARM.CheckHandSignal(rxdata); } else if (len >= 53) { CommWithARM.HandData(rxdata, len); } } } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值