標籤: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;}