使用termios 标准接口实现串口通信

termios是posix规范中定义的标准接口,表示终端设备(包括虚拟终端、串口等)。 


#define NCCS		18
struct termios
{
    unsigned short c_iflag;  // 输入模式标志
    unsigned short c_oflag;  // 输出模式标志
    unsigned short c_cflag;  // 控制模式标志
    unsigned short c_lflag;  // 本地模式标志
    unsigned char c_line;    // 线路规程
    unsigned char c_cc[NCC]; // 控制特性
    speed_t c_ispeed;        // 输入速度
    speed_t c_ospeed;        // 输出速度
}
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>

int main() {
    int serialFd = open("/dev/ttyS1", O_RDWR);
    if (serialFd < 0) {
        perror("opening serial port error");
        return -1;
    }

    struct termios tty;
    memset(&tty, 0, sizeof(tty));
    if (tcgetattr(serial_port, &tty) != 0) {
        perror("Error configuring serial port");
        return -1;
    }

    // 配置串口参数
    cfsetospeed(&tty, B115200);
    cfsetispeed(&tty, B115200);
    tty.c_cflag |= CS8;
    tty.c_cflag &= ~PARENB;
    tty.c_cflag &= ~CSTOPB;

    if (tcsetattr(serial_port, TCSANOW, &tty) != 0) {
        perror("Error configuring serial port");
        return -1;
    }

    // 发送数据
    while(1) {
         char data[] = "Hello, world";
         write(serialFd , data, strlen(data));

    // 接收数据
        char buffer[255];
        int recvBytes= read(serialFd , buffer, sizeof(buffer));
        printf("Received: %.*s\n", recvBytes, buffer);
        sleep(1);

    }
   
    close(serialFd);

    return 0;
}

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值