Writefile方法错误串口

时间:2015-07-14 12:23:44

标签: serial-port writefile

我试图编写串口com 1 :(对于atmega8 MCU) 使用EscapeCommFunction 创建文件方法,写文件

    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();

Mainform load:

    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());
    }

EscapeCommFunction回归真实, Writefile返回false。 有什么问题?

0 个答案:

没有答案