Serial port Writefile方法错误串行端口
我正在尝试写入串行端口com 1:(到atmega8 MCU) 使用EscapeComm函数 创建文件方法,写入文件Serial port Writefile方法错误串行端口,serial-port,writefile,Serial Port,Writefile,我正在尝试写入串行端口com 1:(到atmega8 MCU) 使用EscapeComm函数 创建文件方法,写入文件 DCB dcb = new DCB(); [DllImport("kernel32.dll")] static extern bool SetCommState(IntPtr hFile, [In] ref DCB lpDCB); [DllImport("kernel32.dll", SetLastError = true)] publ
DCB dcb = new DCB();
[DllImport("kernel32.dll")]
static extern bool SetCommState(IntPtr hFile, [In] ref DCB lpDCB);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool CloseHandle(IntPtr handle);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool EscapeCommFunction(IntPtr hFile, int dwFunc);
IntPtr portHandle;
int SETRTS = 3;
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern IntPtr CreateFile(string lpFileName, System.UInt32 dwDesiredAccess, System.UInt32 dwShareMode, IntPtr pSecurityAttributes, System.UInt32 dwCreationDisposition, System.UInt32 dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport("kernel32.dll")]
static extern bool WriteFile(IntPtr hFile, byte[] lpBuffer, uint nNumberOfBytesToWrite, out uint lpNumberOfBytesWritten, [In] ref NativeOverlapped lpOverlapped);
[StructLayout(LayoutKind.Sequential, Pack = 8)]
public struct NativeOverlapped
{
private IntPtr InternalLow;
private IntPtr InternalHigh;
public long Offset;
public IntPtr EventHandle;
}
NativeOverlapped OverLap = new NativeOverlapped();
主窗体加载:
private void MainForm_Load(object sender, EventArgs e)
{
try
{
portHandle = CreateFile("COM1", 0x80000000 | 0x40000000, 0x00000000, IntPtr.Zero, 4, 0x40000000, IntPtr.Zero);
dcb.BaudRate = 9600;
dcb.Parity = 0;
dcb.ByteSize = 8;
dcb.StopBits = 1;
SetCommState(portHandle, ref dcb);
MessageBox.Show(EscapeCommFunction(portHandle, 3).ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
我正在尝试发送数据
private void btnSend_Click(object sender, EventArgs e)
{
lpNumberOfBytesWritten = 0;
bytesLen = 0;
byte[] message = new byte[11];
//creating message
bytesLen = (uint)message.Length;
MessageBox.Show(WriteFile(portHandle, message, bytesLen, out lpNumberOfBytesWritten, ref OverLap).ToString());
}
EscapeComm函数返回为真,
Writefile返回为false。
怎么了?重写.NET SerialPort类是非常不明智的。你注定会犯一些简单的错误,导致无法诊断的“不起作用”行为。比如没有正确初始化DCB。忘记WriteFile()声明中的SetLastError。最终的错误是,省略了所有必需的错误检查代码。你再也没有友好的.NET异常来让你远离麻烦,这种捕获永远不会捕获任何东西。取得成功的最好方法是扔掉这个,使用System.IO.Ports.SerialPort类。是的,你说得对,谢谢你的帮助!