首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 操作系统 > UNIXLINUX >

LInux停的串口通信

2013-03-26 
LInux下的串口通信我在Linux下写了下面这样一个串口通信的程序:#include stdio.h#include string.h#in

LInux下的串口通信
我在Linux下写了下面这样一个串口通信的程序:


#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h> /* File control definitions */
#include <errno.h>
#include <termios.h> /* POSIX terminal control definitions */


int main(void)
{
int fd; /* File descriptor for the port */
    char buf[100];

fd = open("/dev/ttyS0", O_RDWR);
if (fd == -1)
{

fputs("open_port: Unable to open /dev/ttyS0 -\n", stderr);
        return -1;
}


struct termios oldoptions;
struct termios options;
memset(&options, 0, sizeof(options));
  
if(tcgetattr(fd, &oldoptions) != 0)   

printf("getting options failed!\n");   
return -1;
}


tcflush(fd, TCIOFLUSH);
cfsetispeed(&options, B9600);
cfsetospeed(&options, B9600);
options.c_cflag |= (CLOCAL | CREAD);

if(tcsetattr(fd, TCSANOW, &options) != 0)   

printf("setting options failed!\n");   
return -1;
}

options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;

options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_oflag &= ~OPOST;


if(tcsetattr(fd, TCSANOW, &options) != 0)   

printf("setting options failed!\n");   
return -1;
}

int n, i;
char tmp[] = "serial port test...\n";
for(i = 0; i < 5; i++)
{
/*
   printf("write to the serial port...\n");
       n = write(fd, tmp, sizeof(tmp));
   if (n < 0)
       {
           fputs("write()  failed!\n", stderr);
           return -1;
   }
*/
   printf("read the serial port...\n");
       n = read(fd, buf, sizeof(buf));
       if (n < 0)
       {
           fputs("read()  failed!\n", stderr);
   return -1;
      }
       printf("receive %d characters\n", n);
       buf[n] = '\0';
           
       printf("%s\n", buf);
}
if(tcsetattr(fd, TCSANOW, &oldoptions) != 0)   

printf("setting options failed!\n");   
return -1;
}
        


close(fd);
}



上面的程序交叉编译后放在arm开发板上,准备和PC的串口进行通信。PC上使用串口调试助手。测试的结果是,在串口调试助手没有发送任何字符时,上面的串口程序中的read函数不会阻塞,直接返回,打印收到0个字符。请问如果我想让read函数阻塞在那里,应该怎么做?
另外,这个串口程序只能正确接收一次PC发送的字符,后面不管PC端发送什么,上面的程序就一直显示收到0个字符。但是如果我在read之前再加个write函数,也就是write和read交替执行,那么read函数能正确读取串口的输入,不过此时read函数还是非阻塞的。请问该怎么解决?
[解决办法]
引用:
在对串口进行读取操作的时候,如果是使用的RAW模式,每个read系统调用将返回当前串行输入缓冲区中存在的字节数。如果没有数据,将会一致阻塞到有字符达到或者间隔时钟到期,或者发生错误

options.c_oflag = 0   //RAW模式
 
你试试看看
[解决办法]
Raw input is unprocessed. Input characters are passed through exactly as they are received, when they are received. Generally you'll deselect the ICANON, ECHO, ECHOE, and ISIG options when using raw input:

        options.c_lflag &= ~(ICANON 
[解决办法]
 ECHO 
[解决办法]
 ECHOE 
[解决办法]
 ISIG);

热点排行