如何使用C语言从COM端口读取数据

时间:2019-01-07 14:46:51

标签: c windows winapi serial-port readfile

我已经在C / C ++上编码了一段时间了,但是现在我遇到了一个我无法解决的重大问题。我正在尝试与COM端口通信。首先,我使用WriteFile()发送数据,这部分工作正常。但是,使用ReadFile()从端口接收答案时,我什么也没得到。

代码如下:

#include <stdlib.h>
#include <windows.h>
#include <stdio.h>
#include <conio.h>

int main(int argc, char *argv[])
{
   int n=0;
   DCB dcb={0};
   HANDLE hCom;
   BOOL fSuccess;
   char *pcCommPort = "COM3";
   DWORD dwBytesRead=0;
   DWORD dwRead;
   DWORD dwBytesWrite=0;
   DWORD dwWrite=0;
/***************************************CommTimeouts******************************************/
COMMTIMEOUTS timeouts={0};
timeouts.ReadIntervalTimeout=200;
//timeouts.ReadTotalTimeoutConstant=1;
//timeouts.ReadTotalTimeoutMultiplier=1;
timeouts.WriteTotalTimeoutConstant=2;
//timeouts.WriteTotalTimeoutMultiplier=1;
/*******************************************Handle*******************************************/
   hCom = CreateFile( pcCommPort,
                    GENERIC_READ | GENERIC_WRITE,
                    FILE_SHARE_READ,    // must be opened with exclusive-access
                    NULL, // no security attributes
                    OPEN_EXISTING, // must use OPEN_EXISTING
                    FILE_ATTRIBUTE_NORMAL,    // not overlapped I/O
                    NULL  // hTemplate must be NULL for comm devices
                    );
/***************************************SET*UP*COM*PORT**************************************/
   if (hCom == INVALID_HANDLE_VALUE)
   {
       printf ("CreateFile failed with error %d.\n", GetLastError());
       CloseHandle(hCom);
       return (1);
   }

   if(!SetCommTimeouts(hCom, &timeouts))
    {
        /*Well, then an error occurred*/
   }

   fSuccess = GetCommState(hCom, &dcb);

   if (!fSuccess)
   {

     /*More Error Handling*/
      printf ("GetCommState failed with error %d.\n", GetLastError());
      CloseHandle(hCom);

      return (2);
   }
   dcb.BaudRate = 9600;     // set the baud rate
   dcb.ByteSize = 8;             // data size, xmit, and rcv
   dcb.Parity = EVENPARITY;        // no parity bit
   dcb.StopBits = ONESTOPBIT;    // one stop bit
   fSuccess = SetCommState(hCom, &dcb);

   if (!fSuccess)
   {
      printf ("SetCommState failed. Error: %d.\n", GetLastError());
      CloseHandle(hCom);
      return (3);
   }

   printf ("Serial port %s successfully configured.\n", pcCommPort);
 //  return (0);
/*************************************Writing************************************************/
char bytes_to_send[] = {'36'};
if(!WriteFile(hCom, bytes_to_send, 2, &dwBytesWrite, NULL))
    {
        fprintf(stderr, "Error\n");
        CloseHandle(hCom);
        return 1;
    }
    printf("dwBytesWrite = %d | %x\n", dwBytesWrite, (dwBytesWrite));
/*************************************Reading************************************************/

char bytes_to_receive[7];

if(!ReadFile(hCom, bytes_to_receive, 7, &dwBytesRead, NULL)){
      printf ("SetCommState failed. Error: %d.\n", GetLastError());
      CloseHandle(hCom);
      return (4);
} else {
printf("Bytes read %d -> %d\n",dwBytesRead, bytes_to_receive);}


/********************************************************************************************/

CloseHandle(hCom);

return(0);

}

1 个答案:

答案 0 :(得分:0)

有一个文件指针,用于读取和写入。在WriteFile之后,它位于文件的末尾。如果尝试从中读取文件,则将在文件末尾读取。要阅读您刚刚写的内容,您必须使用SetFilePointer函数在文件的开头重新定位文件指针:

SetFilePointer(hCom, 0, NULL, FILE_BEGIN);