Visual c++ 在VC+中读取串行端口时挂起+;

Visual c++ 在VC+中读取串行端口时挂起+;,visual-c++,serial-port,Visual C++,Serial Port,我有一个问题,我想用vc++窗体应用程序每隔1秒读取一次串口。 但当我调试时,读取串行端口后,它将停止(可以再调试)。 当我运行它时,程序被挂起 void CENVSConfigDlg::OnTimer(UINT_PTR ID){ if(ID==cTimer1){ char Buff[3]="0"; char Buf[6]="0"; int b; int Count = 20; DWORD nbytes; //Read Sensors

我有一个问题,我想用vc++窗体应用程序每隔1秒读取一次串口。 但当我调试时,读取串行端口后,它将停止(可以再调试)。 当我运行它时,程序被挂起

void CENVSConfigDlg::OnTimer(UINT_PTR ID){
if(ID==cTimer1){

    char Buff[3]="0";
    char Buf[6]="0";
    int b;
    int Count = 20;
    DWORD nbytes;


    //Read Sensors

    b=0; //sensor 0
    sprintf(Buff,"%iz",b);
    if(!WriteFile( hnd_serial, Buff, Count, &nbytes, NULL )){KillTimer(cTimer1);MessageBox(L"Write Com Port fail!");return;}

    Sleep(20);

    if(!ReadFile( hnd_serial, Buf, Count, &nbytes, NULL )){KillTimer(cTimer1);MessageBox(L"Read Com Port fail!");return;}

    /* Store buf value*/
    sensor1 =atoi(Buf);

    /* Update text box. */
    CString string;
    string.Format( L"%i", sensor1 );
    Sensor_1_edit.SetWindowText( (LPCTSTR)string );
 }}
下面是一些相关代码:

 BOOL CENVSConfigDlg::OnInitDialog()
 {
    CDialog::OnInitDialog();

// Set the icon for this dialog.  The framework does this automatically
//  when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE);         // Set big icon
SetIcon(m_hIcon, FALSE);        // Set small icon



if(!OpenComPort())MessageBox(L"Could not open Adrino port!");

return TRUE;  // return TRUE  unless you set the focus to a control
}


   BOOL CENVSConfigDlg::OpenComPort(){
//Opens com port to adrino
DCB conf = { 0 };
conf.DCBlength = sizeof( conf );

if ( hnd_serial != INVALID_HANDLE_VALUE )
    CloseHandle( hnd_serial );

MessageBox(L"Opening serial connection.\n" );

hnd_serial = CreateFileA( AdrinoComPort, GENERIC_READ | GENERIC_WRITE, 0, 0,
                         OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0 );

if ( hnd_serial == INVALID_HANDLE_VALUE ) {
    MessageBox(L"Failed to open serial port.\n" );
    return FALSE;
}

if ( !GetCommState( hnd_serial, &conf ) ) {
    MessageBox(L"Failed to configure serial port.\n" );
    CloseHandle( hnd_serial );
    hnd_serial = INVALID_HANDLE_VALUE;
    return FALSE;
}

conf.BaudRate = CBR_9600;
conf.ByteSize = 8;
conf.Parity = NOPARITY;
conf.StopBits = ONESTOPBIT;

if ( !SetCommState( hnd_serial, &conf ) ) {
    MessageBox(L"Failed to configure serial port.\n" );
    CloseHandle( hnd_serial );
    hnd_serial = INVALID_HANDLE_VALUE;
    return FALSE;   
}
}

void CENVSConfigDlg::CloseComPort(){
//Opens com port to adrino
if ( hnd_serial != INVALID_HANDLE_VALUE )
    CloseHandle( hnd_serial );

}
有人能帮我吗,我的代码怎么了


daniel

使用com端口时,通常需要使用comm DCB设置端口参数。您通常还需要使用
SetCommTimeouts
来说明如何写入和(尤其是)读取通信端口

我在一个示例中包含了一个工作示例