linux 串口读写c代码
Linux是一种广泛使用的操作系统,其强大的开放性和灵活性使其成为许多嵌入式系统和服务器的首选。在Linux系统中,串口通信是一种常见的通信方式,可以实现与外部设备的数据交换。本文将介绍如何在Linux系统中进行串口读写的C代码编写。
在Linux系统中进行串口通信需要使用串口设备文件。串口设备文件的命名规则为/dev/ttySx或/dev/ttyUSBx,其中x为串口号。在打开串口设备文件之前,需要使用open函数打开该文件。可以使用以下代码来打开串口设备文件:
```c
#include <fcntl.h>
#include <unistd.h>
int open_port(const char *port_name)
{
    int fd = open(port_name, O_RDWR | O_NOCTTY | O_NDELAY);
    if (fd == -1)
    {
        perror("open_port: Unable to open serial port");
        return -1;
    }
    else
    {
        fcntl(fd, F_SETFL, 0);
        return fd;
    }
}
```
在打开串口设备文件后,需要对串口进行一系列的配置,以确保数据的正确传输。配置串口的代码如下所示:
```c
#include <termios.h>
int set_serial_port(int fd, int baud_rate, int data_bits, int stop_bits, int parity)
{
    struct termios options;
    tcgetattr(fd, &options);
    cfsetispeed(&options, baud_rate);
    cfsetospeed(&options, baud_rate);
   
    // 设置数据位
    options.c_cflag &= ~CSIZE;
    switch (data_bits)
    {
        case 5:
            options.c_cflag |= CS5;
            break;
        case 6:
            options.c_cflag |= CS6;
            break;
        case 7:
            options.c_cflag |= CS7;
            break;
        case 8:
            options.c_cflag |= CS8;
            break;write的返回值
        default:
            fprintf(stderr, "Unsupported data size\n");
            return -1;
    }
   
    // 设置停止位
    switch (stop_bits)
    {
        case 1:
            options.c_cflag &= ~CSTOPB;
            break;
        case 2:
            options.c_cflag |= CSTOPB;
            break;
        default:
            fprintf(stderr, "Unsupported stop bits\n");
            return -1;
    }
   
    // 设置校验位
    switch (parity)
    {