Linux串口通信

#include "stdio.h"
#include "stdlib.h"
#include "unistd.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "fcntl.h"
#include "termios.h"
#include "errno.h"
#include "string.h"

int main()
{
    int tty_fd;
    struct termios opt;
    int n;
    char buf[512];


    tty_fd = open("/dev/ttyS0", O_RDWR);
    if(tty_fd == -1){
        perror("open tty faild\n");
        return 0;
    }
    printf("open tty OK\n");
    
    //
    tcgetattr(tty_fd, &opt);
    tcflush(tty_fd, TCIOFLUSH);

    //设置波特率
    cfsetispeed(&opt, B9600);
    cfsetospeed(&opt, B9600);
    
	//设置通信参数
    opt.c_cflag &= ~CSIZE;//在设置数据位时 必须先使用CSIZE做位屏蔽
    opt.c_cflag |= CS8;//设置8位数据位
	opt.c_cflag &= ~CSTOPB;//设置1位停止位
	opt.c_cflag &= ~PARENB;//关闭输出奇偶校验
	opt.c_iflag &= ~INPCK;//关闭输入奇偶校验
	opt.c_iflag &= ~ICANON;//关闭标准模式(标准模式下读需要接收\r\n才会从缓存区读出)
	
	//设置read函数超时时间
	opt.c_cc[VTIME] = 150;//VTIME以十分之一秒为单位:1500s=
    opt.c_cc[VMIN] = 0;

    //关回显
    opt.c_lflag &= ~ECHO;
	
    //
    if(0!=tcsetattr(tty_fd, TCSANOW, &opt))
    {
        perror("set faild\n");
        return 0;
    }
    tcflush(tty_fd, TCIOFLUSH);

    write(tty_fd, "123",3);
    printf("go while\n");
    while(1)
    {
        n = read(tty_fd,buf,512);

        if(n <= 0)
        {
            perror("read faild\n");
            break;
        }
        buf[n] = '\0';

        printf("recev :%s\n",buf);
        if(strcmp(buf, "serial_exit") == 0)
        {
            printf("cmd exit\n");
            break;
        }
    }

    printf("program will exit");
    close(tty_fd);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值