pipi_123456
皮柯晓
2019-04-30 13:55

我小白拼凑一程序,VC++控制台程序用API函数与三菱PLC串口通信,但写不进读不出求大神指点

10
  • c++
  • c语言
  • 开发语言

#include
#include
#include
#define BYTE unsigned char
#define ONESTOPBITS 1
int main()
{
HANDLE hCom; //全局变量,串口句柄

hCom = CreateFile("COM1",
GENERIC_READ | GENERIC_WRITE, //允许读和写

0, //独占方式

NULL,
OPEN_EXISTING, //打开而不是创建

FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, //异步方式

         NULL);
    if (hCom == (HANDLE)-1)
    {
        printf("打开COM失败!");
        return FALSE;
    }
    else
        printf("打开串口成功\n");

    SetupComm(hCom, 1024, 1024); //输入缓冲区和输出缓冲区的大小都1024 
    COMMTIMEOUTS TimeOuts;
    //设定读超时
    TimeOuts.ReadIntervalTimeout=1000;
    TimeOuts.ReadTotalTimeoutMultiplier=500;
    TimeOuts.ReadTotalTimeoutConstant=5000;
    //设定写超时
    TimeOuts.WriteTotalTimeoutMultiplier=500;
    TimeOuts.WriteTotalTimeoutConstant=2000; 
    SetCommTimeouts(hCom,&TimeOuts); //设置超时

    DCB dcb;
    GetCommState(hCom, &dcb);
    dcb.BaudRate = 9600; //波特率为9600 
    dcb.ByteSize = 7; //每个字节有7位 
    dcb.Parity = EVENPARITY; //偶校验位 
    dcb.StopBits = 1; //1个停止位
    SetCommState(hCom,&dcb);
    PurgeComm(hCom, PURGE_TXCLEAR | PURGE_RXCLEAR);     
    printf("____________\n");

    //写串口
     char buffer[1024]="02 45 37 30 30 30 43 03 35 32";

    DWORD dwBytesWritten = 1024;
    DWORD dwErrorFlags;
    COMSTAT ComStat;
    OVERLAPPED m_osWrite;
    BOOL bWriteStat;
    bWriteStat = WriteFile(hCom, buffer, dwBytesWritten, &dwBytesWritten, &m_osWrite);
    if (!bWriteStat)
    {

        printf("写入失败!\n");
        if (GetLastError() == ERROR_IO_PENDING)
        {
            WaitForSingleObject(m_osWrite.hEvent, 1000);
            printf("%d\n", dwBytesWritten);
        }
        //return 0;
    }
    printf("%d\n", dwBytesWritten);

    //异步读串口的示例代码:

    char lpInBuffer[1024] = {};
    DWORD dwBytesRead = 1024;
//  COMSTAT ComStat;
//  DWORD dwErrorFlags;
    OVERLAPPED m_osRead;
    memset(&m_osRead, 0, sizeof(OVERLAPPED)); 
    m_osRead.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    ClearCommError(hCom, &dwErrorFlags, &ComStat); 
    dwBytesRead = min(dwBytesRead, (DWORD)ComStat.cbInQue); 
    if (!dwBytesRead) 
        printf("读取失败!\n");
    BOOL bReadStatus;
    bReadStatus = ReadFile(hCom, lpInBuffer, dwBytesRead, &dwBytesRead, &m_osRead);
    if (!bReadStatus) //如果ReadFile函数返回FALSE 
    {

        if (GetLastError() == ERROR_IO_PENDING) //GetLastError()函数返回ERROR_IO_PENDING,表明串口正在进行读操作 
        {
            WaitForSingleObject(m_osRead.hEvent, 2000); //使用WaitForSingleObject函数等待,直到读操作完成或延时已达到2秒钟 //当串口读操作进行完毕后,m_osRead的hEvent事件会变为有信号
            //return dwBytesRead;
        }
        //return 0;
    }
    printf("%d\n",dwBytesRead);
     CloseHandle( hCom);
     return 0;

}


  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答