C言語でシリアル通信を行う方法
シリアル通信を実現するには、C言語では対応するライブラリ関数を使用できます。以下はシリアル通信の簡単なC言語コードの例です。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
int main() {
int serial_port;
struct termios tty;
// 打开串口
serial_port = open("/dev/ttyUSB0", O_RDWR);
if (serial_port < 0) {
perror("打开串口失败");
return -1;
}
// 配置串口
memset(&tty, 0, sizeof(tty));
if (tcgetattr(serial_port, &tty) != 0) {
perror("获取串口配置失败");
return -1;
}
// 设置波特率
cfsetospeed(&tty, B9600);
cfsetispeed(&tty, B9600);
// 设置数据位、停止位和校验位
tty.c_cflag &= ~PARENB; // 不使用奇偶校验
tty.c_cflag &= ~CSTOPB; // 1个停止位
tty.c_cflag &= ~CSIZE; // 清除字符大小的位
tty.c_cflag |= CS8; // 设置字符大小为8位
// 设置为原始模式
tty.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
// 禁用软件流控制
tty.c_iflag &= ~(IXON | IXOFF | IXANY);
// 禁用硬件流控制
tty.c_cflag &= ~CRTSCTS;
// 保存设置
if (tcsetattr(serial_port, TCSANOW, &tty) != 0) {
perror("保存串口配置失败");
return -1;
}
// 从串口读取数据
char buffer[255];
memset(buffer, '\0', sizeof(buffer));
int bytes_read = read(serial_port, buffer, sizeof(buffer) - 1);
if (bytes_read > 0) {
printf("接收到的数据:%s\n", buffer);
} else {
perror("读取串口数据失败");
return -1;
}
// 向串口写入数据
char *message = "Hello, Serial Port!";
int bytes_written = write(serial_port, message, strlen(message));
if (bytes_written > 0) {
printf("成功写入 %d 字节的数据\n", bytes_written);
} else {
perror("向串口写入数据失败");
return -1;
}
// 关闭串口
close(serial_port);
return 0;
}
まず、open() 関数を使用してシリアルポートデバイスファイル(例: /dev/ttyUSB0)を開き、tcgetattr() と tcsetattr() 関数を使用してシリアルポートの設定パラメータを取得・設定します。設定パラメータには、ボーレート、データビット、ストップビット、パリティなどの値が含まれます。次に、read() 関数を使用してシリアルポートからデータを読み込み、write() 関数を使用してシリアルポートにデータを書き込みます。最後に、close() 関数を使用してシリアルポートを閉じます。
上記のコードは簡易なサンプルであり、エラー処理や完全なデータの読み書きは行っていません。実際の利用においては、具体的なニーズに合わせて修正や改良を行う必要があります。