C语言读写串口例子程序

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

#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

 

 

 

 

 

使用方法:
    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();
           }

 

 

 

 

 

 

  • 1
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Anyanyamy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值