Linux 串口通信

串口通信

参考 Serial Programming Guide for POSIX Operating System 和树莓派的 WiringPi 代码。关于串口的介绍可以看 STM32

Linux 与 STM32 不同。32 本质上是操作寄存器,但是 Linux 本着一切设备皆文件的理念,串口操作也是通过文件的‘读’与‘写’完成。串口在 Linux 下 /dev/tty*

打开串口

使用 Linux open(2) 函数。参数一般选择:

  • O_RDWR: 串口读写
  • O_NOCTTY: 放弃对 /dev/tty* 端口控制。如果没有设置的话,端口的输入会影响当前进程。
  • O_NDELAY: Noblocking Mode。如果没有设置的话,在 RS232 DCD 为低时,当前进程会休眠(无数据时阻塞了当前进程)。

Example

#include <stdio.h>   /* Standard input/output definitions */
#include <string.h>  /* String function definitions */
#include <unistd.h>  /* UNIX standard function definitions */
#include <fcntl.h>   /* File control definitions */
#include <errno.h>   /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */

/*
 * 'open_port()' - Open serial port 1.
 *
 * Returns the file descriptor on success or -1 on error.
 */

int
open_port(void)
{
  int fd; /* File descriptor for the port */


  fd = open("/dev/ttyf1", O_RDWR | O_NOCTTY | O_NDELAY);
  if (fd == -1)
  {
   /*
    * Could not open the port.
    */

    perror("open_port: Unable to open /dev/ttyf1 - ");
  }
  else
    fcntl(fd, F_SETFL, 0);

  return (fd);
}

数据读取

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值