Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

linux串口应用编程

作者:◆丶依然如风   发布日期:2026-05-29   浏览:20

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

解释说明:

  1. 打开串口:使用 open 函数打开指定的串口设备文件(例如 /dev/ttyUSB0),并检查是否成功打开。
  2. 配置串口参数
    • 使用 tcgetattr 获取当前的串口属性。
    • 设置波特率(例如 9600)。
    • 配置数据位、停止位和校验位。
    • 禁用硬件流控,启用接收器,并设置为原始模式。
  3. 发送数据:使用 write 函数将字符串写入串口。
  4. 接收数据:使用 read 函数从串口读取数据,并打印接收到的消息。
  5. 关闭串口:使用 close 函数关闭串口。

这个示例代码展示了如何在 Linux 下进行基本的串口通信编程。

上一篇:linux怎么看内存

下一篇:linux杀死端口

大家都在看

linux如何启动nginx

linux常用命令查询端口是否正常

linux 发送邮件

linux长ping命令

linux groupadd

linux关机命令行

linux 安装 gcc

linux重启oracle命令

linux把一个文件夹移动到另一个文件夹里

linux查看系统运行时间

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站