通过 RS485 与读卡器通信

Posted hellowzl

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了通过 RS485 与读卡器通信相关的知识,希望对你有一定的参考价值。

using NLog;
using System;
using System.IO.Ports;
using System.Text;
using System.Threading;

namespace TestCom485
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                SerialEntity serialEntity = new SerialEntity();
                serialEntity.PortName = "COM1";
                serialEntity.BaudRate = 19200;
                serialEntity.DataBits = 8;
                serialEntity.StopBits = "1";
                serialEntity.Parity = "0";
                ScanProvider scanProvider = new ScanProvider(serialEntity);
                scanProvider.DataReceived += PrintData;
                scanProvider.Open();

                while (true)
                {
                    //给485读头发送读卡指令
                    byte[] send = new byte[] { 0x01 };
                    scanProvider.Write(send, 0, 7);

                    Thread.Sleep(1000);
                }                
            }
            catch(Exception ex)
            {
                Console.Write(ex.ToString());
                Console.WriteLine();
            }

            Console.ReadKey();
        }

        static void PrintData(object sender, SerialSortEventArgs eventArgs)
        {
            Console.WriteLine(eventArgs.Code);
        }
    }

    public class ScanProvider
    {
        public SerialPort _serialPort = new SerialPort();
        public event EventHandler<SerialSortEventArgs> DataReceived;

        public ScanProvider(SerialEntity serialEntity)
        {
            // 串口名  
            _serialPort.PortName = serialEntity.PortName;
            // 波特率  
            _serialPort.BaudRate = serialEntity.BaudRate;
            // 数据位  
            _serialPort.DataBits = serialEntity.DataBits;
            // 停止位  
            _serialPort.StopBits = (StopBits)Enum.Parse((typeof(StopBits)), serialEntity.StopBits);
            // 无奇偶校验位  
            _serialPort.Parity = (Parity)Enum.Parse((typeof(Parity)), serialEntity.Parity);
            _serialPort.DataReceived += _serialPort_DataReceived;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="portName">串口名</param>
        /// <param name="baudRate">波特率</param>
        public ScanProvider(SerialPort _serialPort, string portName, int baudRate)
        {
            this._serialPort = _serialPort;
            // 串口名  
            _serialPort.PortName = portName;
            // 波特率  
            _serialPort.BaudRate = baudRate;
            // 数据位  
            _serialPort.DataBits = 8;
            // 停止位  
            _serialPort.StopBits = StopBits.One;
            // 无奇偶校验位  
            _serialPort.Parity = Parity.None;
            _serialPort.DataReceived += _serialPort_DataReceived;
        }

        /// <summary>  
        /// 是否处于打开状态  
        /// </summary>  
        public bool IsOpen
        {
            get { return _serialPort != null && _serialPort.IsOpen; }
        }

        /// <summary>  
        /// 打开串口  
        /// </summary>  
        /// <returns></returns>  
        public bool Open()
        {
            try
            {
                if (_serialPort == null)
                    return this.IsOpen;
                if (_serialPort.IsOpen)
                    this.Close();
                _serialPort.Open();
            }
            catch (Exception e)
            {
                _serialPort.Close();
                throw e;
            }
            return this.IsOpen;
        }

        /// <summary>  
        /// 关闭串口  
        /// </summary>  
        public void Close()
        {
            if (this.IsOpen)
                _serialPort.Close();
        }

        /// <summary>  
        /// 向串口内写入  
        /// </summary>  
        /// <param name="send">写入数据</param>  
        /// <param name="offSet">偏移量</param>  
        /// <param name="count">写入数量</param>  
        public void Write(byte[] send, int offSet, int count)
        {
            if (this.IsOpen)
            {
                _serialPort.Write(send, offSet, count);
            }
        }

        public void Dispose()
        {
            if (this._serialPort == null)
                return;
            if (this._serialPort.IsOpen)
                this.Close();
            this._serialPort.Dispose();
            this._serialPort = null;
        }

        void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            // 等待100ms,防止读取不全的情况  
            Thread.Sleep(100);
            ReceiveDate();
        }

        public void ReceiveDate()
        {
            byte[] m_recvBytes = new byte[_serialPort.BytesToRead]; //定义缓冲区大小  
            int result = _serialPort.Read(m_recvBytes, 0, m_recvBytes.Length); //从串口读取数据  
            if (result <= 0)
                return;
            string strResult = BitConverter.ToString(m_recvBytes, 0).Replace("-", " ").ToLower();
            _serialPort.DiscardInBuffer();
            if (this.DataReceived != null)
                this.DataReceived(this, new SerialSortEventArgs() { Code = strResult });
        }
    }

    public class SerialSortEventArgs : EventArgs
    {
        public string Code { get; set; }
    }

    public class SerialEntity
    {
        public string PortName { get; set; }
        public int BaudRate { get; set; }
        public int DataBits { get; set; }
        public string StopBits { get; set; }
        public string Parity { get; set; }
    }
}

参考资料:https://blog.csdn.net/weixin_41415541/article/details/80921956

以上是关于通过 RS485 与读卡器通信的主要内容,如果未能解决你的问题,请参考以下文章

怎样具体实现 三菱PLC 通过 485接口 与电脑的通信?越详细越好,谢谢

串口通信:RS232与RS485互连

工业机器人-- UART和RS-232RS-422RS-485通信接口

工业机器人-- UART和RS-232RS-422RS-485通信接口

stm32---RS485半双工通信

普通PC通过USB转485串口 ModBus-RTU通信协议控制伺服电机