码迷,mamicode.com
首页 > Windows程序 > 详细

WindowsAPI操作串口

时间:2014-05-15 14:08:24      阅读:518      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   c   

 

bubuko.com,布布扣
#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;
}
bubuko.com,布布扣

 

WindowsAPI操作串口,布布扣,bubuko.com

WindowsAPI操作串口

标签:style   blog   class   code   java   c   

原文地址:http://www.cnblogs.com/fwst/p/3729318.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!