2010-11-08 3 views
1

Эта проблема задана много раз, я читал все ответы, но все еще не смог понять проблему.Последовательный порт: проблема чтения данных с петлей, ничего не читает

Я установил соединение с портом COM1 Написал данные в порт COM1 с помощью WriteFile Теперь я пытаюсь читать данные из порта с помощью ReadFile, но он ничего не читает. У меня есть жесткий посуда LoopBack 2-го и 3-го по RS232, так что вход может быть прочитана как выход

#include <windows.h> 
#include <stdio.h> 
# include <tchar.h> 


int main(int argc, char *argv[]) 

{ 

    DCB dcb; 
    HANDLE hCom; 
    BOOL fSuccess; 
    char *pcCommPort = "COM3"; 

    hCom = CreateFile(_T("COM3"), //pcCommPort, 
        GENERIC_READ | GENERIC_WRITE, 
        0, // must be opened with exclusive-access 
        0, // no security attributes 
        OPEN_EXISTING, // must use OPEN_EXISTING 
        FILE_ATTRIBUTE_NORMAL, // not overlapped I/O 
        NULL // hTemplate must be NULL for comm devices 
        ); 


    if (hCom == INVALID_HANDLE_VALUE) 
    { 
     // Handle the error. 
     printf ("CreateFile failed with error %d.\n", GetLastError()); 
     } 

    // Build on the current configuration, and skip setting the size 
    // of the input and output buffers with SetupComm. 
    fSuccess = GetCommState(hCom, &dcb); 

    if (!fSuccess) 
    { 
    // Handle the error. 
     printf ("GetCommState failed with error %d.\n", GetLastError()); 
    } 

    dcb.BaudRate = 9600;  // set the baud rate 
    dcb.ByteSize = 8;    // data size, xmit, and rcv 
    dcb.Parity = NOPARITY;  // no parity bit 
    dcb.StopBits = ONESTOPBIT; // one stop bit 

    fSuccess = SetCommState(hCom, &dcb); 

    if (!fSuccess) 
    { 
     // Handle the error. 
     printf ("SetCommState failed with error %d.\n", GetLastError()); 
    } 


    printf ("Serial port %s successfully reconfigured.\n", pcCommPort); 

    char Buff[] = "Hello"; 
    char Buff2[50] = {}; 

    DWORD dwNumBytesWritten; 
    DWORD dwBytesTransferred; 

    printf("\n\n\n\n\n\n Start writting ! \n"); 

    WriteFile (hCom,    // Port handle 
       Buff,    // Pointer to the data to write 
       sizeof(Buff),     // Number of bytes to write 
       &dwNumBytesWritten, // Pointer to the number of bytes written 
       NULL     // Must be NULL for Windows Embedded CE 
      ); 


      printf("\n Bytes Written to the terminal "); 
      for(int j=0; j<dwNumBytesWritten; j++) 
       printf("%c",Buff[j]); 


    printf("\n Byte length %d \n", dwNumBytesWritten); 
    printf("\n\n\n\n\n\n Start reading !\n"); 

    ReadFile (hCom,    // Port handle 
      Buff2,    // Pointer to data to read 
      dwNumBytesWritten,  // Number of bytes to read 
      &dwBytesTransferred, // Pointer to number of bytes read 
      NULL     // Must be NULL for Windows Embeddded CE 
      ); 


      for(int j=0; j<dwNumBytesWritten; j++) 
       printf("%c",Buff2[j]); 

       printf("\n BytesRead from the terminal:%d \n",dwBytesTransferred); 

    CloseHandle(hCom); 

    int num; 
    scanf("%d", &num); 
} 

Программа не возвращает код ошибки, но он непрерывно ожидает чтения данных из порта COM1 и никогда не получает ничего , Я застрял, поскольку я не могу решить, где проблема. Любые указатели будут полезны.

Спасибо,

Yogesh

ответ

1

Вы не делаете ничего очевидного для установки аппаратного квитирования сигналов. Устройство последовательного порта почти всегда проверяет сигналы RTS и DTR и ничего не посылает, пока они не будут активны. Если вы отключите EscapeCommFunction, чтобы включить их, установите элементы DCB.fDtrControl и fRtsControl, чтобы включить аппаратное квитирование.

Не устанавливать основные свойства связи, такие как скорость передачи, четность, данные и остановки, вы также можете отказаться от сбоя, если значения по умолчанию не подходят или были изменены другой программой.

И убедитесь, что проводка в порядке с отдельной программой, такой как Putty или Hyperterminal.

+0

+1 за предложение «проверки здравомыслия» с помощью шпатлевки или гипертерминала. – semaj

Смежные вопросы