C#读写串口类,频繁读写串口不会报错.

这是一个使用C#编写的串口通信类,支持配置波特率、数据位、校验位和停止位,并提供安全的读写操作,避免串口错误。类库中包含Win32 API调用,用于设置通信参数、清理缓冲区和处理超时。

 namespace SerialAPI
{
    /// <summary>
    ///
    /// </summary>
    public class SerialPort
    {
        public SerialPort()
        {
        }
        public int PortNum =AFC.WorkStation.UI.Maintenance.DevPartsInPage.ComPort; //1,2,3,4
        public int BaudRate = 9600; //1200,2400,4800,9600
        public byte ByteSize = 8; //8 bits
        public byte Parity = 0; // 0-4=no,odd,even,mark,space
        public byte StopBits = 1; // 0,1,2 = 1, 1.5, 2
        public int ReadTimeout = 200; //10

        //comm port win32 file handle
        private int hComm = -1;

        public bool Opened = false;

        //win32 api constants
        private const uint GENERIC_READ = 0x80000000;
        private const uint GENERIC_WRITE = 0x40000000;
        private const int OPEN_EXISTING = 3;
        private const int INVALID_HANDLE_VALUE = -1;

        private const uint PURGE_TXABORT = 0x0001; // Kill the pending/current writes to the comm port.
        private const uint PURGE_RXABORT = 0x0002; // Kill the pending/current reads to the comm port.
        private const uint PURGE_TXCLEAR = 0x0004; // Kill the transmit queue if there.
        private const uint PURGE_RXCLEAR = 0x0008; // Kill the typeahead buffer if there.

        [StructLayout(LayoutKind.Sequential)]
        private struct DCB
        {
            //taken from c struct in platform sdk
            public int DCBlength;           // sizeof(DCB)
            public int BaudRate;            // current baud rate
            public int fBinary;          // binary mode, no EOF check
            public int fParity;          // enable parity checking
            public int fOutxCtsFlow;      // CTS output flow control
            public int fOutxDsrFlow;      // DSR output flow control
            public int fDtrControl;       // DTR flow control type
            public int fDsrSensitivity;   // DSR sensitivity
            public int fTXContinueOnXoff; // XOFF continues Tx
            public int fOutX;          // XON/XOFF out flow control
            public int fInX;           // XON/XOFF in flow control
            public int fErrorChar;     // enable error replacement
            public int fNull;          // enable null stripping
            public int fRtsControl;     // RTS flow control
            public int fAbortOnError;   //

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值