嵌入式串口操作

2019-07-13 07:15发布

这是一个简易的嵌入式linux对多单片机的测试程序: 下位机如下工作:接收到正确的地址码,返回#? OKv否则什么也不返回 教训:上一个程序VMIN设置成6,当只有上下位机的时候,地址码错误,程序就会阻塞在那里。 一对多通信,VMIN必须为0,VTIME的单位是百毫秒,这里30就代表3秒。表示上位机最多等待三秒。若无任何响应,则返回。 如同http://bbs.csdn.net/topics/320133315这里所讲  我自己测试下来发现设置c_cc[VMIN] > 0后,不管open的时候带不带O_NODELY/O_NOBLOCK ,都为阻塞型了
#include #include #include #include #include #include #define DEVICE "/dev/ttyS1" /****globals****/ struct termios opt; void OptTermi(struct termios*); int fd, c ,res; struct termios old; char buf[7]; char sent; char STOP =0; /******************/ int main() { fd =open(DEVICE,O_RDWR|O_NDELAY); if(fd>0) printf("Device Opened Successfully! "); tcgetattr(fd,&old); bzero(&opt,sizeof(opt)); OptTermi(&opt); fcntl(fd,F_SETFL,0); tcflush(fd,TCIFLUSH); if(tcsetattr(fd,TCSANOW,&opt)==0) printf("Init done...... "); do{ memset(buf,0,7); printf("enter a char: "); scanf("%c",&sent); if('q'==sent) STOP=1; write(fd,&sent,1); res =read(fd,buf,6); if(buf[5]=='v') { printf("incoming... "); buf[6]=0; printf("%d ",res); printf(":%s ",buf); } if(buf[5]!='v') printf("NO device available. "); tcflush(fd,TCIFLUSH); }while(STOP==0); tcsetattr(fd,TCSANOW,&old); close(fd); } void OptTermi(struct termios* termios_p) { //set to RAW mode ,according to man page termios_p->c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON); termios_p->c_oflag &= ~OPOST; termios_p->c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN); termios_p->c_cflag &= ~(CSIZE | PARENB); termios_p->c_cflag |= CS8; //plus termios_p->c_iflag &= ~(IXON | IXOFF | IXANY); //parity setting: operations above has done something ,more to go //no input parity checking termios_p->c_iflag &=~INPCK; //1 stop bit termios_p->c_cflag &=~CSTOPB; /* Enable the receiver and set local mode...*/ termios_p->c_cflag |= (CLOCAL | CREAD); //set standard speed cfsetispeed(termios_p,B9600); cfsetospeed(termios_p,B9600); // termios_p->c_cc[VTIME]=30; termios_p->c_cc[VMIN]=0; }


http://bbs.ednchina.com/BLOG_ARTICLE_1809186.HTM
http://wenku.baidu.com/view/56467805cc175527072208bc.html

http://blog.csdn.net/wushihua/article/details/5733790