首页 > 代码库 > WindowsAPI操作串口

WindowsAPI操作串口

 

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

int main()
{
    //1.打开串口
    HANDLE hCom;
    hCom = CreateFile("COM1",
        GENERIC_READ|GENERIC_WRITE,
        0,
        NULL,
        OPEN_EXISTING,
        0,
        NULL);
    if (hCom ==(HANDLE)-1 )
        printf("打开串口失败!\n");
    else 
        printf("打开串口成功!\n");

    //2.初始化串口
    DCB dcb;
    GetCommState(hCom, &dcb);
    dcb.BaudRate = 9600;//波特率
    //dcb.fParity = 0;//奇偶校验使能
    dcb.ByteSize = 8;//数据位
    dcb.Parity = NOPARITY;//奇偶校验
    dcb.StopBits = ONESTOPBIT;//停止位
    SetCommState(hCom, &dcb);

    SetupComm(hCom, 1024, 1024);
    COMMTIMEOUTS TimeOuts;

    //设定读超时
    TimeOuts.ReadIntervalTimeout = 1000;
    TimeOuts.ReadTotalTimeoutConstant = 5000;
    TimeOuts.ReadTotalTimeoutMultiplier = 500;

    //设定写超时
    TimeOuts.WriteTotalTimeoutConstant = 2000;
    TimeOuts.WriteTotalTimeoutMultiplier = 500;

    SetCommTimeouts(hCom, &TimeOuts);

    //清空缓冲区
    PurgeComm(hCom, PURGE_TXCLEAR|PURGE_RXCLEAR);
    Sleep(500);

    //3.读写串口
    unsigned char buf[10] = {0x00, 0x06, D, A, T, A}; 
    BOOL bWriteStat;
    DWORD dwBytesWrite = 6;
    bWriteStat = WriteFile(hCom, buf, dwBytesWrite, &dwBytesWrite, NULL);
    if (!bWriteStat)
    {
        printf("写串口失败!\n");
    }
    else 
        printf("写串口成功!\n");

    unsigned char rBuf[1024];
    BOOL bReadStat;
    DWORD dwBytesRead;
    bReadStat = ReadFile(hCom, rBuf, 1024, &dwBytesRead, NULL);
    if (!bReadStat)
    {
        printf("读串口失败!\n");
    }
    else
    {
        printf("读串口成功!\n");
    }
    for (DWORD j = 0; j < dwBytesRead; j++)
    {
        printf("%x ", rBuf[j]);
    }
    printf("\n");
    
    //4.关闭串口
    CloseHandle(hCom);
    return 0;
}