简体   繁体   English

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

[英]How to read data from COM port with C language

I have been coding on C/C++ for a while but now I have faced a major problem which I can not resolve. 我已经在C / C ++上编码了一段时间了,但是现在我遇到了一个我无法解决的重大问题。 I am trying to communicate with COM port. 我正在尝试与COM端口通信。 First I am sending data with WriteFile(), this part works.But when it comes to receiving an answer from the port with ReadFile(), I do not get anything. 首先我使用WriteFile()发送数据,这部分工作正常,但是当使用ReadFile()从端口接收答案时,我什么也没得到。

Here is the code: 这是代码:

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

}

There is a file pointer, both for read and write. 有一个文件指针,用于读取和写入。 After the WriteFile it is at the end of the file. 在WriteFile之后,它位于文件的末尾。 If you try to read from it, you will read at the end of the file. 如果尝试从中读取文件,则将在文件末尾读取。 To read what you just wrote you have to reposition the file pointer at the start of the file, using the SetFilePointer function: 要读取您刚刚写的内容,您必须使用SetFilePointer函数将文件指针重新定位在文件的开头:

SetFilePointer(hCom, 0, NULL, FILE_BEGIN);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM