所谓的潇洒

导航

读串口

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);
    }
}                                        

 

posted on 2021-07-16 16:25  所谓的潇洒  阅读(50)  评论(0编辑  收藏  举报