WindowsAPI操作串口

來源:互聯網
上載者:User

標籤:style   blog   class   code   java   c   

 

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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.