none
c# Api串口通信不定每次都能接收到数据??? RRS feed

  • 问题

  • 连接没有问题,发送数据也是成功的,接收数据返回值也是为true,可就是接收不到数据,当用其他的串口工具发送时,就可以接收得到,再测试下本程序发送,可以接收到数据了,不知道是怎么回事???
    2011年4月11日 6:05

答案

全部回复

  • 串口的数据还没有准备好你就又读取了一次而已.

    等待一会在读就可以了

    • 已标记为答案 X-H 2011年4月13日 2:28
    2011年4月11日 9:29
  • 等待一会,不行咦
    2011年4月12日 4:57
  • Hi,

    能贴一些相关的code吗?以便大家分析原因.


    Paul Zhou [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • 已标记为答案 X-H 2011年4月13日 2:28
    2011年4月12日 13:50
  • 代码:

    /// <summary>
        /// 串口通讯类
        /// </summary>
        public class Com
        {
          
            #region Field
            private string PortNum; //COM1,COM2,COM3,COM4
            private int BaudRate; //1200,2400,4800,9600
            private byte ByteSize; //8 bits
            private byte Parity; // 0-4=no,odd,even,mark,space
            private byte StopBits; // 0,1,2 = 1, 1.5, 2
            private int ReadTimeout=10; //10
            //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;
            //comm port win32 file handle
            private int hComm = -1;
            public bool Opened = false;
            [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;   // abort on error
                public int fDummy2;        // reserved
                public ushort wReserved;          // not currently used
                public ushort XonLim;             // transmit XON threshold
                public ushort XoffLim;            // transmit XOFF threshold
                public byte ByteSize;           // number of bits/byte, 4-8
                public byte Parity;             // 0-4=no,odd,even,mark,space
                public byte StopBits;           // 0,1,2 = 1, 1.5, 2
                public char XonChar;            // Tx and Rx XON character
                public char XoffChar;           // Tx and Rx XOFF character
                public char ErrorChar;          // error replacement character
                public char EofChar;            // end of input character
                public char EvtChar;            // received event character
                public ushort wReserved1;         // reserved; do not use
            }

            [StructLayout(LayoutKind.Sequential)]
            private struct COMMTIMEOUTS
            {
                public int ReadIntervalTimeout;
                public int ReadTotalTimeoutMultiplier;
                public int ReadTotalTimeoutConstant;
                public int WriteTotalTimeoutMultiplier;
                public int WriteTotalTimeoutConstant;
            }

            [StructLayout(LayoutKind.Sequential)]
            private struct OVERLAPPED
            {
                public int Internal;
                public int InternalHigh;
                public int Offset;
                public int OffsetHigh;
                public int hEvent;
            }
            #endregion

            #region Properties
            #endregion

            #region Constructor

            /// <summary>
            ///
            /// </summary>
            /// <param name="portNum">COM1,COM2,COM3,COM4</param>
            /// <param name="baudRate">1200,2400,4800,9600</param>
            /// <param name="byteSize">8</param>
            /// <param name="parity">0-4=no,odd,even,mark,space </param>
            /// <param name="stopBits">0,1,2 = 1, 1.5, 2 </param>
            /// <param name="readTimeout">10</param>
            public Com(string portNum,int baudRate,int byteSize ,int parity,int stopBits,int readTimeout)
            {
                PortNum = portNum;
                BaudRate = baudRate;
                ByteSize = (byte)byteSize;
                Parity = (byte)parity;
                StopBits = (byte)stopBits;
                ReadTimeout = readTimeout;
            }
            [DllImport("kernel32.dll")]
            private static extern int CreateFile(
                string lpFileName,                         // file name
                uint dwDesiredAccess,                      // access mode
                int dwShareMode,                          // share mode
                int lpSecurityAttributes, // SD
                int dwCreationDisposition,                // how to create
                int dwFlagsAndAttributes,                 // file attributes
                int hTemplateFile                        // handle to template file
                );
            [DllImport("kernel32.dll")]
            private static extern bool GetCommState(
                int hFile,  // handle to communications device
                ref DCB lpDCB    // device-control block
                );
            [DllImport("kernel32.dll")]
            private static extern bool BuildCommDCB(
                string lpDef,  // device-control string
                ref DCB lpDCB     // device-control block
                );
            [DllImport("kernel32.dll")]
            private static extern bool SetCommState(
                int hFile,  // handle to communications device
                ref DCB lpDCB    // device-control block
                );
            [DllImport("kernel32.dll")]
            private static extern bool GetCommTimeouts(
                int hFile,                  // handle to comm device
                ref COMMTIMEOUTS lpCommTimeouts  // time-out values
                );
            [DllImport("kernel32.dll")]
            private static extern bool SetCommTimeouts(
                int hFile,                  // handle to comm device
                ref COMMTIMEOUTS lpCommTimeouts  // time-out values
                );
            [DllImport("kernel32.dll")]
            private static extern bool ReadFile(
                int hFile,                // handle to file
                byte[] lpBuffer,             // data buffer
                int nNumberOfBytesToRead,  // number of bytes to read
                ref int lpNumberOfBytesRead, // number of bytes read
                ref OVERLAPPED lpOverlapped    // overlapped buffer
                );
            [DllImport("kernel32.dll")]
            private static extern bool WriteFile(
                int hFile,                    // handle to file
                byte[] lpBuffer,                // data buffer
                int nNumberOfBytesToWrite,     // number of bytes to write
                ref int lpNumberOfBytesWritten,  // number of bytes written
                ref OVERLAPPED lpOverlapped        // overlapped buffer
                );
            [DllImport("kernel32.dll")]
            private static extern bool CloseHandle(
                int hObject   // handle to object
                );
            [DllImport("Comm.dll")]
            private static extern void Init_Comm();
            #endregion

            #region Methods
           
            #endregion
          
            public void Open()
            {
                Opened = false;

                Init_Comm();
                DCB dcbCommPort = new DCB();
                COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS();

                // OPEN THE COMM PORT.

                hComm = CreateFile(PortNum, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);

                // IF THE PORT CANNOT BE OPENED, BAIL OUT.
                if (hComm == INVALID_HANDLE_VALUE)
                {
                    //Close();
                    throw (new ApplicationException("Comm Port Can Not Be Opened"));
                }

                // SET THE COMM TIMEOUTS.

                GetCommTimeouts(hComm, ref ctoCommPort);
                ctoCommPort.ReadTotalTimeoutConstant = ReadTimeout;
                ctoCommPort.ReadTotalTimeoutMultiplier = 0;
                ctoCommPort.WriteTotalTimeoutMultiplier = 0;
                ctoCommPort.WriteTotalTimeoutConstant = 0;

                SetCommTimeouts(hComm, ref ctoCommPort);

                // SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS.
                // THERE ARE OTHER WAYS OF DOING SETTING THESE BUT THIS IS THE EASIEST.
                // IF YOU WANT TO LATER ADD CODE FOR OTHER BAUD RATES, REMEMBER
                // THAT THE ARGUMENT FOR BuildCommDCB MUST BE A POINTER TO A STRING.
                // ALSO NOTE THAT BuildCommDCB() DEFAULTS TO NO HANDSHAKING.

                dcbCommPort.DCBlength = Marshal.SizeOf(dcbCommPort);
                GetCommState(hComm, ref dcbCommPort);
                dcbCommPort.BaudRate = BaudRate;
                dcbCommPort.Parity = Parity;
                dcbCommPort.ByteSize = ByteSize;
                dcbCommPort.StopBits = StopBits;
                //dcbCommPort.
                SetCommState(hComm, ref dcbCommPort);
                Opened = true;
            }

            public void Close()
            {
                if (hComm != INVALID_HANDLE_VALUE)
                {
                    CloseHandle(hComm);
                    Opened = false;
                }
            }

            public byte[] Read(int NumBytes)
            {
                byte[] BufBytes;
                byte[] OutBytes;
                BufBytes = new byte[NumBytes];
                if (hComm != INVALID_HANDLE_VALUE)
                {
                    OVERLAPPED ovlCommPort = new OVERLAPPED();
                    int BytesRead = 0;
                    bool b = false;
                    b= ReadFile(hComm, BufBytes, NumBytes, ref BytesRead, ref ovlCommPort);
                    OutBytes = new byte[BytesRead];
                    Array.Copy(BufBytes, OutBytes, BytesRead);
                }
                else
                {
                    throw (new ApplicationException("Comm Port Not Open"));
                }
                return OutBytes;
            }

            public int Write(byte[] WriteBytes)
            {
                int BytesWritten = 0;
                if (hComm != INVALID_HANDLE_VALUE)
                {
                    OVERLAPPED ovlCommPort = new OVERLAPPED();
                    bool b=WriteFile(hComm, WriteBytes, WriteBytes.Length, ref BytesWritten, ref ovlCommPort);
                }
                else
                {
                    throw (new ApplicationException("Comm Port Not Open"));
                }
                return BytesWritten;
            }
        }

    2011年4月13日 1:33
  • 加上这段就好了:dcbCommPort.fOutxCtsFlow = 524800; //用于发送控制

    谢谢各位的帮忙!


    我要飞得更长
    • 已标记为答案 X-H 2011年4月13日 2:28
    2011年4月13日 2:27