#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
int main() {
int serial_port = open("/dev/ttyUSB0", O_RDWR);
// 检查串口是否成功打开
if (serial_port < 0) {
printf("Error %i from open: %s\n", errno, strerror(errno));
return -1;
}
struct termios tty;
memset(&tty, 0, sizeof tty);
// 读取当前的属性设置
if (tcgetattr(serial_port, &tty) != 0) {
printf("Error %i from tcgetattr: %s\n", errno, strerror(errno));
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_cflag &= ~CRTSCTS;
// 启用接收器,设置为原始模式
tty.c_cflag |= CREAD | CLOCAL;
// 设置最小字符数和等待时间
tty.c_cc[VMIN] = 1;
tty.c_cc[VTIME] = 5;
// 写入新的配置
if (tcsetattr(serial_port, TCSANOW, &tty) != 0) {
printf("Error %i from tcsetattr: %s\n", errno, strerror(errno));
return -1;
}
// 发送数据
const char *write_buffer = "Hello, World!";
int num_written = write(serial_port, write_buffer, strlen(write_buffer));
if (num_written < 0) {
printf("Error %i from write: %s\n", errno, strerror(errno));
return -1;
} else if (num_written != strlen(write_buffer)) {
printf("Warning: only %d of %lu characters were written!\n",
num_written, strlen(write_buffer));
}
// 接收数据
char read_buffer[256];
int num_read = read(serial_port, &read_buffer, sizeof(read_buffer) - 1);
if (num_read < 0) {
printf("Error %i from read: %s\n", errno, strerror(errno));
return -1;
} else if (num_read == 0) {
printf("No data read.\n");
} else {
read_buffer[num_read] = '\0';
printf("Read %i bytes. Received message: %s\n", num_read, read_buffer);
}
// 关闭串口
close(serial_port);
return 0;
}
open 函数打开指定的串口设备文件(例如 /dev/ttyUSB0),并检查是否成功打开。tcgetattr 获取当前的串口属性。write 函数将字符串写入串口。read 函数从串口读取数据,并打印接收到的消息。close 函数关闭串口。这个示例代码展示了如何在 Linux 下进行基本的串口通信编程。
上一篇:linux怎么看内存
下一篇:linux杀死端口
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站