其他分享
首页 > 其他分享> > 读串口

读串口

作者:互联网

private SerialPort _serialPort = null;

string _qrCode = string.Empty;

private void InitQrIOPort()
{
    try
    {
        _serialPort = new SerialPort();
        //设置参数
        _serialPort.PortName = "COM2";
        _serialPort.BaudRate = 9600;
        _serialPort.DataBits = 8;
        _serialPort.StopBits = StopBits.One;
        _serialPort.Parity = Parity.None;
        _serialPort.ReadTimeout = 3000;
        _serialPort.WriteTimeout = 3000;
        _serialPort.DataReceived += new             
        SerialDataReceivedEventHandler(CommDataReceived);
        _serialPort.ReceivedBytesThreshold = 1;
        _serialPort.Open();
    }
    catch (Exception ex)
    {
        _syncContext.Post(ShowErrTip, "初始化串口失败");
        LogHelper.logger.Error(ex);
    }
}

public void CommDataReceived(Object sender, SerialDataReceivedEventArgs e)
{
    try
    {
        if (!IsOrderedSign && !IsSearchInfo) return;
        lock (_qrCode)
        {
            _qrCode += _serialPort.ReadExisting();
        }
    }
    catch (Exception ex)
    {
        LogHelper.logger.Error(ex);
    }
}

private void timer_QrCode_Tick(object sender, EventArgs e)
{
    try
    {
        lock (_qrCode)
        {
            if ( !_qrCode.EndsWith("\r")) return;
            _qrCode = _qrCode.TrimEnd('\r');
            //使用_qrCode
            _qrCode = string.Empty;
        }
    }
    catch (Exception ex)
    {
        LogHelper.logger.Error(ex);
    }
}                                        

 

标签:Exception,private,serialPort,ex,串口,qrCode,LogHelper
来源: https://www.cnblogs.com/chixiner/p/15020665.html