C#调用API读取串口,紧急求助!
调用CreateFile函数打开串口
- C# code
[DllImport("kernel32.dll")] private static extern int CreateFile( string lpFileName, uint dwDesiredAccess, int dwShareMode, int lpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, int hTemplateFile );hComm = CreateFile(PortNum, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);...
打开之后,调用PurgeComm方法清除缓冲区
- C# code
PurgeComm(hComm, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT);
然后,在一个循环中,不断的读取串口的值,奇怪的是:打开串口后,什么都没做,调用ReadFile方法读取串口值,每次都有读取到数据。这是什么问题呢?
[解决办法]
每次的值都一样?
你试一下下位机向串口发送一个byte看得到的数据是不是你想要的
或者用Serialport(这个应该不会有问题)来读
[解决办法]
读取的什么数据?串口连接了什么设备?