linux串口编程入门

linux串口设备文件:

/dev/ttyS0 , /dev/ttyS1 ,/dev/ttyS3 以此类推,还有其他为终端等设备文件。


打开串口设备

#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/ttyS3", O_RDWR | O_NOCTTY); //打开串口
  if (fd == -1)
  {
    perror("open_port: Unable to open /dev/ttyf1 - ");
  }
  else
    fcntl(fd, F_SETFL, 0);  //设置描述符标志位

  return (fd);
}

设置串口

最基本的设置串口包括波特率设置,效验位和停止位设置。

串口设置也就是填充结构体struct termios。

struct termios
{	unsigned short  c_iflag;	/* 输入模式标志 */	
	unsigned short  c_oflag;		/* 输出模式标志 */	
	unsigned short  c_cflag;		/* 控制模式标志*/	
	unsigned short  c_lflag;		/* local mode flags */	
	unsigned char  c_line;		    /* line discipline */	
	unsigned char  c_cc[NCC];    /* control characters */
};

    tcflush(fd, TCIOFLUSH);
    tcgetattr(fd, &ti);
    cfmakeraw(&ti);
    ti.c_cflag |= (CLOCAL | CREAD);
    ti.c_cflag &= ~(PARENB | CSIZE | CSTOPB | CRTSCTS);
    ti.c_cflag |= CS8;
    ti.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
    
    cfsetospeed(&ti, B115200);
    cfsetispeed(&ti, B115200);
    tcsetattr(fd, TCSANOW, &ti);
    tcflush(fd, TCIOFLUSH);


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值