Linux Reads Serial Data

本文介绍了如何在Linux环境下读取串口数据,特别是从传感器获取数据的情况。内容包括数据格式、串口初始化、数据读取与分析以及将数据存储到MySQL数据库的操作流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Linux Reads Serial Data

Computer serial port data reading is often used when using sensors. Next, I introduce the method of reading Linux serial port data in a project. I hope it will be helpful to you.

Data Format

A set of data transmitted by the sensor through serial port is 13 bytes. The data format is as follows:

在这里插入图片描述

Initialize Serial Port

We need to initialize the serial port before reading the serial port data. The initialization of the serial port needs three steps:opening the serial port, setting the parameters of the serial port (including baud rate, data bit, stop bit, check bit).

Opening the Port

The procedure of opening serial port is as follow, function returns a handle:

int openPort()
{
    int fd;
    fd = open(SERIAL_PORT, O_RDWR | O_NOCTTY |O_NDELAY);   
    if(fd == -1)
  	{
        perror("open serial failed!\n");
        exit(1);
    }    
    return fd;
}

SERIAL_PORT is a serial address;
O_RDWR means to open in a readable and writable manner;
O_NOCTTY indicates that if the open file is a terminal device, the terminal will not be regarded as a process control terminal;
O_NDELAY denotes opening a file in an uninterruptible manner.

Setting the Parameters

Here is the program for setting baud rate and data bits

int setSpeed(int fd, int speed, struct termios Opt)
{
  int i;

  if(tcgetattr(STDIN_FILENO, &Opt) !
### Linux C++ Serial Port Communication Tutorial In the context of developing applications that require serial communication on a Linux system using C++, several key points must be addressed to ensure successful implementation. The focus here is not only on writing efficient code but also understanding how to interact with hardware through software interfaces. #### Understanding Basic Concepts Serial communication under Linux involves interacting directly with device files typically found in `/dev`. These devices can represent physical or virtual ports such as `ttyS0` (standard UART), `ttyUSB0` (for USB-to-serial adapters), etc.[^1] To establish communication over these channels, one needs to open, configure, read from/write to, and close the respective file descriptors associated with each port. This process requires familiarity with POSIX I/O functions like `open()`, `close()`, `read()`, `write()`, along with termios structures used for setting up baud rates, parity bits, stop bits, flow control parameters among others[^2]. #### Example Code Demonstrating Serial Communication Below demonstrates basic operations required when working with serial ports: ```cpp #include <iostream> #include <fcntl.h> /* File Control Definitions */ #include <termios.h> /* POSIX Terminal Control Definitions */ #include <unistd.h> /* UNIX Standard Definitions */ int main(){ int fd; // File descriptor for the port struct termios tty; // Open the port fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY); if(fd < 0){ std::cerr << "Error opening serial port." << std::endl; return -1; } // Get current attributes of the port tcgetattr(fd, &tty); // Set Baud Rate cfsetospeed(&tty, B9600); cfsetispeed(&tty, B9600); // Setting other Port Stuff tty.c_cflag &= ~PARENB; // No Parity tty.c_cflag &= ~CSTOPB; // One Stop Bit tty.c_cflag &= ~CSIZE; // Clear all size bits tty.c_cflag |= CS8; // Select 8 data bits // Enable receiver and set local mode tty.c_cflag |= (CLOCAL | CREAD); // Disable hardware flow control tty.c_iflag &= ~(IXON | IXOFF | IXANY); // Timeouts tty.c_cc[VTIME] = 10; // Wait for up to 1s (10 deciseconds) tty.c_cc[VMIN] = 0; // Apply settings immediately without waiting for pending input/output tcsetattr(fd, TCSANOW, &tty); char buffer[32]; memset(buffer, '\0', sizeof(buffer)); // Read data from the port ssize_t n = read(fd, buffer, sizeof(buffer)-1); if(n > 0){ printf("Read %ld bytes: '%s'\n", n, buffer); }else{ perror("Failed to read"); } close(fd); } ``` This program opens a connection to a specified serial port (`/dev/ttyUSB0`) at 9600 bps, configures it according to standard requirements, reads any available incoming message into a buffer, prints out its content, then closes the connection properly afterwards.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值