/*开启一个线程,用于接收串口数据并打印*/
#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>
#include <pthread.h>
int fd;
fd_set rd;
void pthread_uartrecv(void)
{
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 10000;
int nread;
char buff[8];
bzero(buff,8);
while(1)
{
FD_ZERO(&rd);
FD_SET(fd,&rd);
//printf("here2\n");
if(FD_ISSET(fd,&rd))
{
//printf("here1\n");
select(fd+1,&rd,NULL,NULL,NULL);
nread = read(fd,buff,8);
buff[nread]='\0';
printf("nread = %d,%s\n",nread,buff);
}
}
}
int main()
{
struct termios opt;
fd = open("/dev/ttyUSB0", O_RDWR|O_NOCTTY|O_NDELAY);
fcntl(fd, F_SETFL, 0);
tcgetattr(fd, &opt);
cfsetispeed(&opt, B9600);
cfsetospeed(&opt, B9600);
if(tcsetattr(fd, TCSANOW, &opt) != 0 )
{
perror("tcsetattr error1");
return -1;
}
opt.c_cflag &= ~CSIZE;
opt.c_cflag |= CS8;
opt.c_cflag &= ~CSTOPB;
opt.c_cflag &= ~PARENB;
opt.c_iflag &= ~INPCK;//opt.c_cflag &= ~INPCK;the last this is fault set
opt.c_cflag |= (CLOCAL | CREAD);
opt.c_cflag &= ~CRTSCTS;
opt.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
opt.c_oflag &= ~OPOST;
opt.c_oflag &= ~(ONLCR | OCRNL); //添加的
opt.c_iflag &= ~(ICRNL | INLCR);
opt.c_iflag &= ~(IXON | IXOFF | IXANY); //添加的
opt.c_cc[VTIME] = 8;
opt.c_cc[VMIN] = 10;
tcflush(fd, TCIOFLUSH);
printf("configure complete\n");
if(tcsetattr(fd, TCSANOW, &opt) != 0)
{
perror("serial error");
return -1;
}
pthread_t id;
pthread_create(&id,NULL,(void*)pthread_uartrecv,NULL);
while(1)
{
sleep(2);
printf("this is main function\n");
}
}