`

C#串口操作

    博客分类:
  • C#
阅读更多
#region Using

using System;
using System.IO;
using System.Threading;
using System.Runtime.InteropServices;
using System.ComponentModel;

#endregion Using

namespace LoMaN.IO {

    public class SerialStream : Stream {
        
        #region Attributes

        private IOCompletionCallback m_IOCompletionCallback;
        private IntPtr m_hFile = IntPtr.Zero;
        private string m_sPort;
        private bool m_bRead;
        private bool m_bWrite;

        #endregion Attributes

        #region Properties

        public string Port {
            get {
                return m_sPort;
            }
            set {
                if (m_sPort != value) {
                    Close();
                    Open(value);
                }
            }
        }

        public override bool CanRead {
            get {
                return m_bRead;
            }
        }

        public override bool CanWrite {
            get {
                return m_bWrite;
            }
        }

        public override bool CanSeek {
            get {
                return false;
            }
        }

        public bool Closed  {
            get {
                return m_hFile.ToInt32()  0;
            }
        }

        public bool Dsr {
            get {
                uint status;
                if (!GetCommModemStatus(m_hFile, out status)) {
                    throw new Win32Exception();
                }
                return (status & MS_DSR_ON) > 0;
            }
        }

        public bool Ring {
            get {
                uint status;
                if (!GetCommModemStatus(m_hFile, out status)) {
                    throw new Win32Exception();
                }
                return (status & MS_RING_ON) > 0;
            }
        }

        public bool Rlsd {
            get {
                uint status;
                if (!GetCommModemStatus(m_hFile, out status)) {
                    throw new Win32Exception();
                }
                return (status & MS_RLSD_ON) > 0;
            }
        }

        #endregion Properties

        #region Constructors

        public SerialStream() : this(FileAccess.ReadWrite) {
        }

        public SerialStream(FileAccess access) {
            m_bRead  = ((int)access & (int)FileAccess.Read) != 0;
            m_bWrite = ((int)access & (int)FileAccess.Write) != 0;
            unsafe {
                m_IOCompletionCallback = new IOCompletionCallback(AsyncFSCallback);
            }
        }

        public SerialStream(string port) : this(FileAccess.ReadWrite) {
            Open(port);
        }

        public SerialStream(string port, FileAccess access) : this(access) {
            Open(port);
        }

        #endregion Constructors

        #region Methods

        public void Open(string port) {
            if (m_hFile != IntPtr.Zero) {
                throw new IOException("Stream already opened.");
            }
            m_sPort = port;
            m_hFile = CreateFile(port, (uint)((m_bRead?GENERIC_READ:0)|(m_bWrite?GENERIC_WRITE:0)), 0, 0, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
            if (m_hFile.ToInt32() == INVALID_HANDLE_VALUE) {
                m_hFile = IntPtr.Zero;
                throw new FileNotFoundException("Unable to open " + port);
            }

            ThreadPool.BindHandle(m_hFile);

            SetTimeouts(0, 0, 0, 0, 0);
        }

        public override void Close() {
            CloseHandle(m_hFile);
            m_hFile = IntPtr.Zero;
            m_sPort = null;
        }

        public IAsyncResult BeginRead(byte[] buffer) {
            return BeginRead(buffer, 0, buffer.Length, null, null);
        }

        public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) {
            GCHandle gchBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned);
            SerialAsyncResult sar = new SerialAsyncResult(this, state, callback, true, gchBuffer);
            Overlapped ov = new Overlapped(0, 0, sar.AsyncWaitHandle.Handle.ToInt32(), sar);
            unsafe {
                NativeOverlapped* nov = ov.Pack(m_IOCompletionCallback);
                byte* data = (byte*)((int)gchBuffer.AddrOfPinnedObject() + offset);

                uint read = 0;
                if (ReadFile(m_hFile, data, (uint)count, out read, nov)) {
                    sar.m_bCompletedSynchronously = true;
                    return sar;
                }
                else if (GetLastError() == ERROR_IO_PENDING) {
                    return sar;
                }
                else
                    throw new Exception("Unable to initialize read. Errorcode: " + GetLastError().ToString());
            }
        }

        public IAsyncResult BeginWrite(byte[] buffer) {
            return BeginWrite(buffer, 0, buffer.Length, null, null);
        }

        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) {
            GCHandle gchBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned);
            SerialAsyncResult sar = new SerialAsyncResult(this, state, callback, false, gchBuffer);
            Overlapped ov = new Overlapped(0, 0, sar.AsyncWaitHandle.Handle.ToInt32(), sar);
            unsafe {
                NativeOverlapped* nov = ov.Pack(m_IOCompletionCallback);
                byte* data = (byte*)((int)gchBuffer.AddrOfPinnedObject() + offset);

                uint written = 0;
                if (WriteFile(m_hFile, data, (uint)count, out written, nov)) {
                    sar.m_bCompletedSynchronously = true;
                    return sar;
                }
                else if (GetLastError() == ERROR_IO_PENDING) {
                    return sar;
                }
                else
                    throw new Exception("Unable to initialize write. Errorcode: " + GetLastError().ToString());
            }
        }

        private int EndOperation(IAsyncResult asyncResult, bool isRead) {
            SerialAsyncResult sar = (SerialAsyncResult)asyncResult;
            if (sar.m_bIsRead != isRead)
                throw new IOException("Invalid parameter: IAsyncResult is not from a " + (isRead ? "read" : "write"));
            if (sar.EndOperationCalled) {
                throw new IOException("End" + (isRead ? "Read" : "Write") + " called twice for the same operation.");
            }
            else {
                sar.m_bEndOperationCalled = true;
            }

            while (!sar.m_bCompleted) {
                sar.AsyncWaitHandle.WaitOne();
            }

            sar.Dispose();

            if (sar.m_nErrorCode != ERROR_SUCCESS && sar.m_nErrorCode != ERROR_OPERATION_ABORTED) {
                throw new IOException("Operation finished with errorcode: " + sar.m_nErrorCode);
            }

            return sar.m_nReadWritten;
        }
        
        public override int EndRead(IAsyncResult asyncResult) {
            return EndOperation(asyncResult, true);
        }
        
        public override void EndWrite(IAsyncResult asyncResult) {
            EndOperation(asyncResult, false);
        }

        public int EndWriteEx(IAsyncResult asyncResult) {
            return EndOperation(asyncResult, false);
        }

        public override int Read(byte[] buffer, int offset, int count) {
            return EndRead(BeginRead(buffer, offset, count, null, null));
        }

        public override void Write(byte[] buffer, int offset, int count) {
            EndWrite(BeginWrite(buffer, offset, count, null, null));
        }

        public int WriteEx(byte[] buffer, int offset, int count) {
            return EndWriteEx(BeginWrite(buffer, offset, count, null, null));
        }

        public int Read(byte[] buffer) {
            return EndRead(BeginRead(buffer, 0, buffer.Length, null, null));
        }

        public int Write(byte[] buffer) {
            return EndOperation(BeginWrite(buffer, 0, buffer.Length, null, null), false);
        }

        public override void Flush() {
            FlushFileBuffers(m_hFile);
        }

        public bool PurgeRead() {
            return PurgeComm(m_hFile, PURGE_RXCLEAR);
        }

        public bool PurgeWrite() {
            return PurgeComm(m_hFile, PURGE_TXCLEAR);
        }

        public bool Purge() {
            return PurgeRead() && PurgeWrite();
        }

        public bool CancelRead() {
            return PurgeComm(m_hFile, PURGE_RXABORT);
        }

        public bool CancelWrite() {
            return PurgeComm(m_hFile, PURGE_TXABORT);
        }

        public bool CancelAll() {
            return CancelRead() && CancelWrite();
        }

        public override void SetLength(long nLength) {
            throw new NotSupportedException("SetLength isn't supported on serial ports.");
        }

        public override long Seek(long offset, SeekOrigin origin) {
            throw new NotSupportedException("Seek isn't supported on serial ports.");
        }

        public void SetTimeouts(int ReadIntervalTimeout,
                                int ReadTotalTimeoutMultiplier,
                                int ReadTotalTimeoutConstant, 
                                int WriteTotalTimeoutMultiplier,
                                int WriteTotalTimeoutConstant) {
            SerialTimeouts Timeouts = new SerialTimeouts(ReadIntervalTimeout,
                                                         ReadTotalTimeoutMultiplier,
                                                         ReadTotalTimeoutConstant, 
                                                         WriteTotalTimeoutMultiplier,
                                                         WriteTotalTimeoutConstant);
            unsafe { SetCommTimeouts(m_hFile, ref Timeouts); }
        }

        public bool SetPortSettings(uint baudrate) {
            return SetPortSettings(baudrate, FlowControl.Hardware);
        }

        public bool SetPortSettings(uint baudrate, FlowControl flowControl) {
            return SetPortSettings(baudrate, flowControl, Parity.None);
        }

        public bool SetPortSettings(uint baudrate, FlowControl flowControl, Parity parity) {
            return SetPortSettings(baudrate, flowControl, parity, 8, StopBits.One);
        }

        public bool SetPortSettings(uint baudrate, FlowControl flowControl, Parity parity, byte databits, StopBits stopbits) {
            unsafe {
                DCB dcb = new DCB();
                dcb.DCBlength = sizeof(DCB);
                dcb.BaudRate = baudrate;
                dcb.ByteSize = databits;
                dcb.StopBits = (byte)stopbits;
                dcb.Parity = (byte)parity;
                dcb.fParity = (parity > 0)? 1U : 0U;
                dcb.fBinary = dcb.fDtrControl = dcb.fTXContinueOnXoff = 1;
                dcb.fOutxCtsFlow = dcb.fAbortOnError = (flowControl == FlowControl.Hardware)? 1U : 0U;
                dcb.fOutX = dcb.fInX = (flowControl == FlowControl.XOnXOff)? 1U : 0U;
                dcb.fRtsControl = (flowControl == FlowControl.Hardware)? 2U : 1U;
                dcb.XonLim = 2048;
                dcb.XoffLim = 512;
                dcb.XonChar = 0x11; // Ctrl-Q
                dcb.XoffChar = 0x13; // Ctrl-S
                return SetCommState(m_hFile, ref dcb);
            }
        }

        public bool SetPortSettings(DCB dcb) {
            return SetCommState(m_hFile, ref dcb);
        }

        public bool GetPortSettings(out DCB dcb) {
            unsafe {
                DCB dcb2 = new DCB();
                dcb2.DCBlength = sizeof(DCB);
                bool ret = GetCommState(m_hFile, ref dcb2);
                dcb = dcb2;
                return ret;
            }
        }

        public bool SetXOn() {
            return EscapeCommFunction(m_hFile, SETXON);
        }

        public bool SetXOff() {
            return EscapeCommFunction(m_hFile, SETXOFF);
        }

        private unsafe void AsyncFSCallback(uint errorCode, uint numBytes, NativeOverlapped* pOverlapped) {
            SerialAsyncResult sar = (SerialAsyncResult)Overlapped.Unpack(pOverlapped).AsyncResult;

            sar.m_nErrorCode = errorCode;
            sar.m_nReadWritten = (int)numBytes;
            sar.m_bCompleted = true;

            if (sar.Callback != null)
                sar.Callback.Invoke(sar);

            Overlapped.Free(pOverlapped);
        }

        #endregion Methods

        #region Constants

        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.

        private const uint SETXOFF  = 1;    // Simulate XOFF received
        private const uint SETXON   = 2;    // Simulate XON received
        private const uint SETRTS    = 3;    // Set RTS high
        private const uint CLRRTS    = 4;    // Set RTS low
        private const uint SETDTR    = 5;    // Set DTR high
        private const uint CLRDTR    = 6;    // Set DTR low
        private const uint SETBREAK    = 8;    // Set the device break line.
        private const uint CLRBREAK    = 9;    // Clear the device break line.

        private const uint MS_CTS_ON  = 0x0010;
        private const uint MS_DSR_ON  = 0x0020;
        private const uint MS_RING_ON = 0x0040;
        private const uint MS_RLSD_ON = 0x0080;

        private const uint FILE_FLAG_OVERLAPPED = 0x40000000;

        private const uint OPEN_EXISTING = 3;

        private const int  INVALID_HANDLE_VALUE = -1;

        private const uint GENERIC_READ = 0x80000000;
        private const uint GENERIC_WRITE = 0x40000000;

        private const uint ERROR_SUCCESS = 0;
        private const uint ERROR_OPERATION_ABORTED = 995;
        private const uint ERROR_IO_PENDING = 997;

        #endregion Constants

        #region Enums

        public enum Parity {None, Odd, Even, Mark, Space};
        public enum StopBits {One, OneAndHalf, Two};
        public enum FlowControl {None, XOnXOff, Hardware};

        #endregion Enums

        #region Classes

        [StructLayout(LayoutKind.Sequential)]
        public struct DCB {

            #region Attributes

            public int DCBlength;
            public uint BaudRate;
            public uint Flags;
            public ushort wReserved;
            public ushort XonLim;
            public ushort XoffLim;
            public byte ByteSize;
            public byte Parity;
            public byte StopBits;
            public sbyte XonChar;
            public sbyte XoffChar;
            public sbyte ErrorChar;
            public sbyte EofChar;
            public sbyte EvtChar;
            public ushort wReserved1;

            #endregion Attributes

            #region Properties

            public uint fBinary { get { return Flags&0x0001; } 
                                  set { Flags = Flags & ~1U | value; } }
            public uint fParity { get { return (Flags>>1)&1; }
                                  set { Flags = Flags & ~(1U >2)&1; }
                                  set { Flags = Flags & ~(1U >3)&1; }
                                  set { Flags = Flags & ~(1U >4)&3; }
                                  set { Flags = Flags & ~(3U >6)&1; }
                                  set { Flags = Flags & ~(1U >7)&1; }
                                  set { Flags = Flags & ~(1U >8)&1; }
                                  set { Flags = Flags & ~(1U >9)&1; }
                                  set { Flags = Flags & ~(1U >10)&1; }
                                  set { Flags = Flags & ~(1U >11)&1; }
                                  set { Flags = Flags & ~(1U >12)&3; }
                                  set { Flags = Flags & ~(3U >14)&1; }
                                  set { Flags = Flags & ~(1U << 14) | (value << 14); } }

            #endregion Properties

            #region Methods

            public override string ToString() {
                return "DCBlength: " + DCBlength + "\r\n" +
                    "BaudRate: " + BaudRate + "\r\n" +
                    "fBinary: " + fBinary + "\r\n" +
                    "fParity: " + fParity + "\r\n" +
                    "fOutxCtsFlow: " + fOutxCtsFlow + "\r\n" +
                    "fOutxDsrFlow: " + fOutxDsrFlow + "\r\n" +
                    "fDtrControl: " + fDtrControl + "\r\n" +
                    "fDsrSensitivity: " + fDsrSensitivity + "\r\n" +
                    "fTXContinueOnXoff: " + fTXContinueOnXoff + "\r\n" +
                    "fOutX: " + fOutX + "\r\n" +
                    "fInX: " + fInX + "\r\n" +
                    "fErrorChar: " + fErrorChar + "\r\n" +
                    "fNull: " + fNull + "\r\n" +
                    "fRtsControl: " + fRtsControl + "\r\n" +
                    "fAbortOnError: " + fAbortOnError + "\r\n" +
                    "XonLim: " + XonLim + "\r\n" +
                    "XoffLim: " + XoffLim + "\r\n" +
                    "ByteSize: " + ByteSize + "\r\n" +
                    "Parity: " + Parity + "\r\n" +
                    "StopBits: " + StopBits + "\r\n" +
                    "XonChar: " + XonChar + "\r\n" +
                    "XoffChar: " + XoffChar + "\r\n" +
                    "EofChar: " + EofChar + "\r\n" +
                    "EvtChar: " + EvtChar + "\r\n";
            }

            #endregion Methods
        }

        private class SerialAsyncResult : IAsyncResult, IDisposable {

            #region Attributes

            internal bool m_bEndOperationCalled = false;
            internal bool m_bIsRead;
            internal int m_nReadWritten = 0;
            internal bool m_bCompleted = false;
            internal bool m_bCompletedSynchronously = false;
            internal uint m_nErrorCode = ERROR_SUCCESS;

            private object m_AsyncObject;
            private object m_StateObject;
            private ManualResetEvent m_WaitHandle = new ManualResetEvent(false);
            private AsyncCallback m_Callback;
            private GCHandle m_gchBuffer;

            #endregion Attributes

            #region Properties

            internal bool EndOperationCalled { get { return m_bEndOperationCalled; } }

            public bool IsCompleted { get { return m_bCompleted; } }

            public bool CompletedSynchronously { get { return m_bCompletedSynchronously; } }

            public object AsyncObject { get { return m_AsyncObject; } }

            public object AsyncState { get { return m_StateObject; } }

            public WaitHandle AsyncWaitHandle { get { return m_WaitHandle; } }
            internal ManualResetEvent WaitHandle { get { return m_WaitHandle; } }

            public AsyncCallback Callback { get { return m_Callback; } }

            #endregion Properties

            #region Constructors

            public SerialAsyncResult(object asyncObject,
                object stateObject, 
                AsyncCallback callback, 
                bool bIsRead, 
                GCHandle gchBuffer) {

                m_AsyncObject = asyncObject;
                m_StateObject = stateObject;
                m_Callback = callback;
                m_bIsRead = bIsRead;
                m_gchBuffer = gchBuffer;
            }

            #endregion Constructors

            #region Methods

            public void Dispose() {
                m_WaitHandle.Close();
                m_gchBuffer.Free();
            }

            #endregion Methods
        }

        #endregion Classes

        #region Imports

        [DllImport("kernel32.dll", EntryPoint="CreateFileW",  SetLastError=true,
            CharSet=CharSet.Unicode, ExactSpelling=true)]
        static extern IntPtr CreateFile(string filename, uint access, uint sharemode, uint security_attributes, uint creation, uint flags, uint template);

        [DllImport("kernel32.dll", SetLastError=true)]
        static extern bool CloseHandle(IntPtr handle);

        [DllImport("kernel32.dll", SetLastError=true)]
        static extern unsafe bool ReadFile(IntPtr hFile, byte* lpBuffer, uint nNumberOfBytesToRead, out uint lpNumberOfBytesRead, NativeOverlapped* lpOverlapped);

        [DllImport("kernel32.dll", SetLastError=true)]
        static extern unsafe bool WriteFile(IntPtr hFile, byte* lpBuffer, uint nNumberOfBytesToWrite, out uint lpNumberOfBytesWritten, NativeOverlapped* lpOverlapped);

        [DllImport("kernel32.dll", SetLastError=true)]
        static extern bool SetCommTimeouts(IntPtr hFile, ref SerialTimeouts lpCommTimeouts);

        [DllImport("kernel32.dll", SetLastError=true)]
        static extern bool SetCommState(IntPtr hFile, ref DCB lpDCB);

        [DllImport("kernel32.dll", SetLastError=true)]
        static extern bool GetCommState(IntPtr hFile, ref DCB lpDCB);

        [DllImport("kernel32.dll", SetLastError=true)]
        static extern bool BuildCommDCB(string def, ref DCB lpDCB);

        [DllImport("kernel32.dll", SetLastError=true)]
        static extern int GetLastError();

        [DllImport("kernel32.dll", SetLastError=true)]
        static extern bool FlushFileBuffers(IntPtr hFile);

        [DllImport("kernel32.dll", SetLastError=true)]
        static extern bool PurgeComm(IntPtr hFile, uint dwFlags);

        [DllImport("kernel32.dll", SetLastError=true)]
        static extern bool EscapeCommFunction(IntPtr hFile, uint dwFunc);

        [DllImport("kernel32.dll", SetLastError=true)]
        static extern bool GetCommModemStatus(IntPtr hFile, out uint modemStat);

        #endregion Imports
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct SerialTimeouts {

        #region Attributes

        public int ReadIntervalTimeout;
        public int ReadTotalTimeoutMultiplier;
        public int ReadTotalTimeoutConstant;
        public int WriteTotalTimeoutMultiplier;
        public int WriteTotalTimeoutConstant;

        #endregion Attributes

        #region Constructors

        public SerialTimeouts(int r1, int r2, int r3, int w1, int w2) {
            ReadIntervalTimeout = r1;
            ReadTotalTimeoutMultiplier = r2;
            ReadTotalTimeoutConstant = r3;
            WriteTotalTimeoutMultiplier = w1;
            WriteTotalTimeoutConstant = w2;
        }

        #endregion Constructors

        #region Methods

        public override string ToString() {
            return "ReadIntervalTimeout: " + ReadIntervalTimeout + "\r\n" +
                   "ReadTotalTimeoutMultiplier: " + ReadTotalTimeoutMultiplier + "\r\n" +
                   "ReadTotalTimeoutConstant: " + ReadTotalTimeoutConstant + "\r\n" +
                   "WriteTotalTimeoutMultiplier: " + WriteTotalTimeoutMultiplier + "\r\n" +
                   "WriteTotalTimeoutConstant: " + WriteTotalTimeoutConstant + "\r\n";
        }

        #endregion Methods
    }
}



using System;
using System.IO;
using System.Threading;

using LoMaN.IO;

namespace SerialStreamReader {

    class App {

        // The main serial stream
        static SerialStream ss;

        [STAThread]
        static void Main(string[] args) {

            // Create a serial port
            ss = new SerialStream();
            try {
                ss.Open("COM3");
            }
            catch (Exception e) {
                Console.WriteLine("Error: " + e.Message);
                return;
            }

            // Set port settings
            ss.SetPortSettings(9600);

            // Set timeout so read ends after 20ms of silence after a response
            ss.SetTimeouts(20, 0, 0, 0, 0);

            // Create the StreamWriter used to send commands
            StreamWriter sw = new StreamWriter(ss, System.Text.Encoding.ASCII);

            // Create the Thread used to read responses
            Thread responseReaderThread = new Thread(new ThreadStart(ReadResponseThread));
            responseReaderThread.Start();

            // Read all returned lines
            for (;;) {
                // Read command from console
                string command = Console.ReadLine();

                // Check for exit command
                if (command.Trim().ToLower() == "exit") {
                    responseReaderThread.Abort();
                    break;
                }

                // Write command to modem
                sw.WriteLine(command);
                sw.Flush();
            }
        }

        // Main loop for reading responses
        static void ReadResponseThread() {
            StreamReader sr = new StreamReader(ss, System.Text.Encoding.ASCII);
            try {
                for (;;) {
                    // Read response from modem
                    string response = sr.ReadLine();
                    Console.WriteLine("Response: " + response);
                }
            }
            catch (ThreadAbortException) {
            }
        }
    }
}
分享到:
评论

相关推荐

    C# 串口操作类

    C# 串口操作类 常用串口操作

    c# 串口 操作。很实用。呵呵 大家可以试试。c#串口操作

    c# 串口 操作。很实用。呵呵 大家可以试试。 c# 串口 操作。很实用。呵呵 大家可以试试。c# 串口 操作。很实用。呵呵 大家可以试试。c# 串口 操作。很实用。呵呵 大家可以试试。c# 串口 操作。很实用。呵呵 大家可以...

    C#.NET串口通信C# 串口操作C#与51单片机串口通信技术文档资料(15个).zip

    001.C#串口通信编程类(修改版).doc 002.C#结合串口通信类实现串口通信源代码.doc 003.C_并口及串口通信.docx 004.C#_SerialPort通信详细介绍.pdf 005.SerialPort控件的使用.doc 006.C#与51单片机串口通信.doc 007.C_...

    C# 串口操作协议

    ### C# 串口操作协议详解 #### 一、引言 在计算机与外部设备通信的过程中,串口通信因其简单易用的特点而被广泛应用。在众多编程语言中,C# 提供了强大的串口通信支持,使得开发人员能够轻松地进行串口数据收发和...

    C#串口操作串口操作串口操作

    根据提供的信息,我们可以总结出以下关于C#串口操作的相关知识点: ### C#串口操作概述 在C#中,串口通信是一种常见的数据传输方式,尤其适用于与硬件设备进行交互的应用程序。串口通信主要涉及到对串口的打开、...

    C#串口操作小例子,P/Invoke

    通过学习这个"C#串口操作小例子",开发者将能深入理解如何在.NET环境中使用P/Invoke技术进行串口通信,这对于开发涉及硬件交互的应用程序至关重要。在实际项目中,这种能力可以帮助开发者创建定制化的解决方案,以...

    C#串口操作一个很好的例子C#源代码

    在C#编程中,串口通信(Serial Port Communication)是一种常用的技术,用于设备间的双向...现在,你可以下载提供的“C#串口操作”压缩包文件,查看源代码并进行实践,这将有助于进一步巩固和深化这些知识点的理解。

    实际工作中总结C#串口操作

    ### 实际工作中总结C#串口操作 #### 概述 在现代软件开发过程中,特别是在工业自动化、设备控制等领域,串行通信仍然是一个非常重要的技术环节。本文将基于一篇关于`C#`串口操作的实际工作经验总结进行深入解析,...

    C#串口操作实际应用开发详解.pdf

    ### C#串口操作实际应用开发详解 #### 一、C#串口操作概述 C#作为一种现代化的编程语言,在工业自动化控制、设备通信等领域有着广泛的应用。串口通信作为传统且常用的数据交换方式之一,仍然是许多场景下不可或缺...

    C#串口操作合集(我把CSDN上的几个可行的串口程序下了哈哈哈)

    标题提到的"C#串口操作合集"可能包含一系列C#代码示例,这些示例展示了如何在C#环境中实现串口通信。CSDN是一个知名的中文开发者社区,提供了大量的技术资源和代码分享,这里的合集可能是其他开发者贡献的串口通信...

    c#串口操作类

    总之,"c#串口操作类"提供了一个方便的工具,使开发者能够轻松地在C#应用中实现串口通信。通过理解SerialPort类的使用方法和串口通信的基本概念,你可以根据需求创建自定义的串口类,实现更复杂的通信功能。在实际...

    c# 串口操作实例:C#操作串口,发送数据,接收数据.Demo中代码已经调试通过;

    本教程将深入讲解如何使用C#进行串口操作,并基于标题和描述中的“C# 串口操作实例:C#操作串口,发送数据,接收数据.Demo中代码已经调试通过”进行详细阐述。 首先,我们需要引入`System.IO.Ports`命名空间: ```...

    c#串口操作-工业-商业-串口对接

    "c#串口操作-工业-商业-串口对接"这个主题深入探讨了如何使用C#编程语言进行串口通信,以便实现与各种硬件设备的接口对接。 首先,我们需要了解串口通信的基本原理。串口通信采用串行传输方式,即数据一位一位地...

    C# 串口操作系列(5)--通讯库雏形

    在本篇中,我们将深入探讨"C# 串口操作系列(5)--通讯库雏形"这一主题。在软件开发中,特别是在嵌入式系统、工业自动化或者物联网(IoT)应用中,串口通信扮演着至关重要的角色。C#语言由于其易用性和丰富的类库,成为...

    C#串口操作类CommBase

    根据提供的文件信息,我们可以从标题、描述以及部分代码中提炼出关于C#串口操作类`CommBase`的相关知识点。 ### C#串口操作类CommBase #### 1. 类的功能与用途 - `CommBase`类是为实现C#语言下的串口通信功能而...

    C#串口操作(两种方案)

    本篇文章将深入探讨两种不同的C#串口操作方案,帮助开发者更好地理解和应用这一关键技术。 ### 方案一:使用`System.IO.Ports`命名空间 `System.IO.Ports`是.NET框架内建的命名空间,它提供了`SerialPort`类,可以...

    C# 串口操作 modbus类

    该协议为C#串口modbus通信协议,方便操作modbus协议的数字传感器。

    C#串口的读与写操作

    C#串口操作是指使用C#语言对串口进行读写操作的过程。串口是一种常用的通信接口,广泛应用于工业自动化、机器人控制、医疗设备等领域。通过C#语言,可以轻松地对串口进行读写操作,实现设备之间的数据交换。 串口读...

Global site tag (gtag.js) - Google Analytics