在VC ++中读取串口时挂起

时间:2013-03-20 03:59:04

标签: visual-c++ serial-port

我有一个问题,我想每1 S用vc ++表单应用程序读取串口。 但是当我调试时,它会在读取串口后停止(可以再调试)。 当我运行它时,程序挂起。

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

}

任何人都可以帮助我,我的代码是错误的

丹尼尔

1 个答案:

答案 0 :(得分:0)

使用com端口时,通常需要使用comm DCB设置端口的参数。您通常还希望使用SetCommTimeouts来告诉您要如何写入和(尤其)从通信端口读取。

我在previous answer中添加了一个工作示例。