Linux Reads Serial Data

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) !
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值