
要用C语言写一个简单的串口通信程序,首先需要了解串口通信的基本原理、配置串口参数、编写通信代码,并处理数据读写。 具体步骤包括:选择适合的平台和开发环境、设置串口参数如波特率、数据位、停止位和校验位、编写初始化函数、读写数据函数、以及处理串口错误的函数。下面我将详细描述如何实现这些步骤。
一、选择开发环境和平台
在开始写C语言程序之前,选择合适的开发环境和平台是非常重要的。常见的开发环境包括Windows、Linux、macOS等,不同平台上的串口操作略有差异。
在Windows上,可以使用Visual Studio进行开发,利用WinAPI进行串口操作;在Linux上,可以使用GCC编译器,利用POSIX标准的串口操作函数。
Windows平台
在Windows平台上,可以使用WinAPI中的函数如CreateFile、SetCommState、ReadFile、WriteFile等,来进行串口操作。
Linux平台
在Linux平台上,可以使用标准的POSIX接口,包括open、close、read、write、tcgetattr、tcsetattr等函数来进行串口通信。
二、初始化串口
初始化串口是串口通信的第一步。在Windows和Linux上,初始化串口的方式有所不同,但总体思路是一致的。
Windows平台初始化
在Windows平台上,使用CreateFile函数打开串口设备,使用SetCommState函数设置串口参数。以下是一个示例代码:
#include <windows.h>
#include <stdio.h>
HANDLE hSerial;
void initSerial(const char* portName) {
hSerial = CreateFile(portName, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (hSerial == INVALID_HANDLE_VALUE) {
printf("Error opening serial portn");
return;
}
DCB dcbSerialParams = {0};
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
if (!GetCommState(hSerial, &dcbSerialParams)) {
printf("Error getting serial port staten");
CloseHandle(hSerial);
return;
}
dcbSerialParams.BaudRate = CBR_9600;
dcbSerialParams.ByteSize = 8;
dcbSerialParams.StopBits = ONESTOPBIT;
dcbSerialParams.Parity = NOPARITY;
if (!SetCommState(hSerial, &dcbSerialParams)) {
printf("Error setting serial port staten");
CloseHandle(hSerial);
return;
}
}
Linux平台初始化
在Linux平台上,使用open函数打开串口设备,使用tcgetattr和tcsetattr函数设置串口参数。以下是一个示例代码:
#include <stdio.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
int serialPort;
void initSerial(const char* portName) {
serialPort = open(portName, O_RDWR);
if (serialPort < 0) {
printf("Error opening serial portn");
return;
}
struct termios tty;
if (tcgetattr(serialPort, &tty) != 0) {
printf("Error getting serial port attributesn");
close(serialPort);
return;
}
cfsetispeed(&tty, B9600);
cfsetospeed(&tty, B9600);
tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8;
tty.c_iflag &= ~IGNBRK;
tty.c_lflag = 0;
tty.c_oflag = 0;
tty.c_cc[VMIN] = 0;
tty.c_cc[VTIME] = 5;
tty.c_iflag &= ~(IXON | IXOFF | IXANY);
tty.c_cflag |= (CLOCAL | CREAD);
tty.c_cflag &= ~(PARENB | PARODD);
tty.c_cflag |= 0;
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CRTSCTS;
if (tcsetattr(serialPort, TCSANOW, &tty) != 0) {
printf("Error setting serial port attributesn");
close(serialPort);
return;
}
}
三、读写数据
读写数据是串口通信的核心。在Windows和Linux上,分别使用ReadFile/WriteFile和read/write函数进行数据读写操作。
Windows平台读写数据
以下是一个读写数据的示例代码:
#include <windows.h>
#include <stdio.h>
void writeData(const char* data) {
DWORD bytesWritten;
if (!WriteFile(hSerial, data, strlen(data), &bytesWritten, NULL)) {
printf("Error writing data to serial portn");
}
}
void readData(char* buffer, DWORD bufferSize) {
DWORD bytesRead;
if (!ReadFile(hSerial, buffer, bufferSize, &bytesRead, NULL)) {
printf("Error reading data from serial portn");
}
buffer[bytesRead] = '