23,120
社区成员
发帖
与我相关
我的任务
分享
44 int fd;
45 struct termios options;
46
47 //open
48 if((fd=open("/dev/ttyS0",O_RDWR|O_NOCTTY|O_NDELAY))==-1){
49 perror("Unable to open /dev/ttyS0 - ");
50 return -1;
51 }
52 fcntl(fd,F_SETFL,0);
53
54 //config
55 printf("\nconfig port start……\t");
56
57 tcgetattr(fd,&options);
58
59 /*
60 * Set the baud rates to 9600
61 */
62 cfsetispeed(&options,B9600);
63 cfsetospeed(&options,B9600);
64
65 /*
66 * disable RTS and CTS
67 */
68 options.c_cflag &= ~CRTSCTS;
69
70 /*
71 * Enable the receiver and set local mode
72 */
73 options.c_cflag |= (CLOCAL|CREAD);
74
75 /*
76 * Set Character Size,1 stop bit, disable parity bit
77 */
78 options.c_cflag &= ~CSIZE;
79 options.c_cflag |= CS8;
80 options.c_cflag &= ~CSTOPB;
81 options.c_cflag &= ~PARENB;
82
83 /*
84 * Raw input
85 */
86 options.c_lflag &= ~(ICANON|ECHO|ECHOE|ISIG|IEXTEN);
87
88 /*
89 * Raw output
90 */
91 options.c_oflag &= ~OPOST;
92
93 /*
94 * 1 byte at a time, no timer
95 */
96 options.c_cc[VMIN] = 0;
97 options.c_cc[VTIME] = 1;
98
99 /*
100 * Set the new options for the port
101 */
102 tcsetattr(fd,TCSANOW,&options);
103
104 printf("done!\n");
105
106
107 return fd;
49 while(1){
50 rec_data_index = 0; //每次收到的数据量
51
52 n = write(fd,command,sizeof(command)); //command是一个命令,这里发命令到板子上
53 if(n<0)
54 fputs("write command failed!\n",stderr);
55 else{
56 printf("\nwrite %d bytes!\n",n);
57 send_times++; //debug用
58 }
59
60 if(tcdrain(fd)==-1) //程序运行一段时间后,在这个地方阻塞
61 perror("tcdrain() error - ");
62 else
63 printf("write OK!\n");
64 /*deubg用
65 if(write_delay){
66 write_delay = 0;
67 sleep(1);
68 }
69 */
70 while((n=read(fd,rec_buf,MAX_RECV_BUF))>0){ //开始接收板子发过来的数据
71 for(i=0;i<n;i++)
72 rec_data[rec_data_index++] = rec_buf[i]; //接收到的数据存在rec_data中
73 }
74
75 tcflush(fd,TCIOFLUSH); //一开始没加这行,后来加上这行也还是出错
76
//…… 略去处理数据的代码
102 sleep(2);
103 }