#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;
}
Linux串口通信
最新推荐文章于 2024-10-11 19:36:23 发布