|
发表于 2002-12-7 18:46:00
|
显示全部楼层
举一个例子,参考一下。:-)
- #include <sys/ioctl.h>
- #include <string.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <termio.h>
- #include <sys/time.h>
- int fd;
- char writebuf[128];
- char readbuf[64];
- void flush232();
- int writegpib();
- void flush232()
- {
- printf("in flush232\n");
- ioctl(fd,TCFLSH, 0);
- ioctl(fd,TCFLSH, 1);
- }
- int writegpib()
- {
- int n;
- int retry =0;
- printf("in writegpib writing %s\n",writebuf);
- printf("length of writebuf: %d\n",strlen(writebuf));
- do {
- n = write(fd,writebuf, strlen(writebuf));
- printf ("error = %d\n",errno);
- printf("wrote %d characters to %d\n",n,fd);
- } while ((n<=0) && retry++ < 5);
- retry = 0;
- do {
- n = write(fd,"\r",1);
- printf ("error = %d\n",errno);
- printf("wrote %d characters to %d\n",n,fd);
- } while ((n<=0) && retry++ < 5);
- if (n<0) n = 0;
- return n;
- }
- void
- delay(int t) {
- struct timeval tp,to;
- struct timezone tzp;
- printf("in delay for %d\n",t);
- if (gettimeofday(&tp,&tzp) == 0) {
- to.tv_usec=tp.tv_usec+t;
- to.tv_sec=tp.tv_sec+(to.tv_usec/1000000);
- to.tv_usec%=1000000;
- while (tp.tv_sec < to.tv_sec) {
- gettimeofday(&tp,&tzp);
- }
- while (tp.tv_usec < to.tv_usec && tp.tv_sec == to.tv_sec) {
- gettimeofday(&tp,&tzp);
- }
- } else {
- printf("gettimeofday failed\n");
- }
- }
-
- void
- main(void)
- {
- printf ("in main()\n");
- printf ("error = %d\n",errno);
- struct termio term;
- int stat = 1;
- int n;
- int retry = 0;
- int flags;
- do {
- printf("opening serial port\n");
- fd = open("/dev/tty00", O_RDWR|O_NONBLOCK, int(0));
- printf ("error = %d\n",errno);
- } while ((fd<=0) && retry++ < 5);
- if (fd < 0) {
- printf("failed to open serial port\n");
- stat = 0;
- }
- if (stat) {
- ioctl(fd,TCGETA, &term);
- printf ("error = %d\n",errno);
- term.c_iflag=(IGNPAR|IGNBRK|IXON|IXOFF);
- term.c_cflag=(B9600|HUPCL|CREAD|CS8);
- term.c_oflag=0;
- term.c_lflag=0;
- term.c_cc[4]=100;
- term.c_cc[5]=1;
- ioctl(fd,TCSETA, &term);
- printf ("error = %d\n",errno);
- ioctl(fd,TCFLSH, 2);
- printf ("error = %d\n",errno);
- }
- if (stat) {
- flush232();
- sprintf(writebuf,"id");
- if (!writegpib()) stat=0;
- delay(2000000);
- do {
- printf("reading from fd(%d)\n",fd);
- n = read(fd,readbuf,56);
- printf ("error = %d\n",errno);
- printf("read %d from fd(%d)\n",n,fd);
- } while ((n<=0) && retry++ < 5);
- printf("readbuf = %s\n",readbuf);
- if (n<=0) {
- stat=0;
- } else {
- if (strstr(readbuf,"GPIB")) {
- printf("got GPIB\n");
- }
- }
- }
- if (stat) {
- fcntl(fd,F_GETFL,&flags);
- flags=flags & (~O_NONBLOCK);
- fcntl(fd,F_SETFL,&flags);
- } else {
- close(fd);
- }
- }
复制代码 |
|