0

我有一个问题,我想每隔 1 秒用 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 );

}

任何人都可以帮助我,我的代码有什么问题

丹尼尔

4

1 回答 1

0

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

我在上一个答案中包含了一个工作示例。

于 2013-03-20T04:12:20.920 回答