您的位置:首页 > 编程语言 > C语言/C++

C语言读写串口例子程序

2015-10-17 22:21 363 查看
#include "SerialPort.h"

HANDLE hComm;
//SYSTEMTIME etime;

bool openPort(TCHAR *gszPort) {
printf("try to open the port %s \n", gszPort);

hComm = CreateFile(gszPort,                                     // pointer to name of the file
GENERIC_READ | GENERIC_WRITE,								// access (read-write) mode
0,                                                          // share mode
0,                                                          // pointer to security attributes
OPEN_EXISTING,												// how to create
0,                                                          // file attributes
0);															// handle to file with attributes to copy

if (hComm == INVALID_HANDLE_VALUE) {
printf("failed to open serial port %s \n", gszPort);
return 0;
} else {
printf("serial port %s opened \n", gszPort);
return 1;
}
}

bool setupPort() {
printf("try to set up the port \n");

DCB dcb;

//printf("setting up DCB\n");
//FillMemory(&dcb, sizeof(dcb), 0);   //initalize dcb
//dcb.DCBlength = sizeof(dcb);

//	printf("getting DCB\n");

if (!GetCommState(hComm, &dcb)) {
printf("getDCB failed\n");
return 0;
}

dcb.BaudRate = 115200;
dcb.fParity = FALSE;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
dcb.ByteSize = 8;
dcb.fOutxCtsFlow = FALSE;
dcb.fOutxDsrFlow = FALSE;
dcb.fDtrControl = DTR_CONTROL_DISABLE;
dcb.fRtsControl = RTS_CONTROL_DISABLE;

//      if (!BuildCommDCB("9600,n,8,1", &dcb)) {
//              printf("Port configuration failed\n");
//              return FALSE;
//  }
//	printf("DCB ready for use\n");
if (!SetCommState(hComm, &dcb)) {
printf("failed to set port state (%d)\n", GetLastError());
return 0;
} else {
printf("Port setup complete\n");
return 1;
}
}

/*
Discards all characters from the output or input buffer of a specified communications resource.
It can also terminate pending read or write operations on the resource.
*/
bool purgePort() {
if (PurgeComm(hComm, PURGE_RXCLEAR)) {
//printf("Port purged\n");
return 1;
}
else {
printf("Port purge failed\n");
return 0;
}
}

bool closePort() {
printf("try to close the port \n");

if (CloseHandle(hComm)) {
printf("Port closed\n");
return 1;
} else {
printf("Port close failed\n");
return 0;
}
}

bool sendSByte(unsigned char byteToWrite) {
DWORD dwWritten;
if (WriteFile(hComm, &byteToWrite, sizeof(byteToWrite), &dwWritten, 0)) {
printf("wrote byte %Xh (%c) to serial port\n", byteToWrite, byteToWrite);
return 1;
} else {
printf("serial port write failed\n");
return 0;
}
}

unsigned char readSByte() {
DWORD dwRead;
unsigned char lpBuf;

ReadFile(hComm,                     // handle of file to read
&lpBuf,                         // address of buffer that receives data
sizeof(lpBuf),                  // number of bytes to read
&dwRead,                        // address of number of bytes read
0);                             // address of structure for data
//printf("Read byte %Xh from serial port\n",lpBuf);
return lpBuf;
}
<pre name="code" class="cpp">#ifndef SERIALPORT_H
#define SERIALPORT_H

#include <stdio.h>
#include <stdbool.h>
#include <Windows.h>	//Contain definations for handle, DWORD and DCB
#include <tchar.h>		//Contain definations for _T

//int portId;				//e.g Com#3 's portId is 3.
//TCHAR commPort[11];		//e.g "\\\\.\\com3"

/*
Definitions for the methods about serial port operations.
*/
bool openPort(TCHAR *gszPort);

bool setupPort();

bool purgePort();

bool closePort();

bool sendSByte(unsigned char byteToWrite);

unsigned char readSByte();

#endif  //SERIALPORT_H



使用方法:
<pre name="code" class="cpp">	char portId[5];

char gszPort[20];   //The port number for serial communication, please change it to the right one.

printf("input the port COM number: \n");
scanf("%s", &portId);

strcpy(gszPort, "\\\\.\\com");
strcat(gszPort, portId);

printf("port Id: %s\n", gszPort);

if (openPort(gszPort)) {

if (setupPort()) {

//程序逻辑
}

closePort();
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: