现象:在arm中集成的linux系统上,应用程序访问串口设备,可以正常写字符串,但是读取字符串时,只能接收到一个字节数据,而且值为0。
当设置为至少读取3个字符时,需要接收三个字符串,而且总共只接收了3个字符,且均为0。
请问哪位兄台遇到过类似的问题?麻烦您指点一二,不胜感激,谢谢!
c程序代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
int set_attr(int fd)
{
struct termios newtio,oldtio;
if ( tcgetattr( fd,&oldtio) != 0) {
perror("SetupSerial 1");
return -1;
}
bzero(&newtio, sizeof(newtio));
newtio.c_cflag &= ~PARENB;
newtio.c_cflag &= ~CSTOPB;
newtio.c_cflag &= ~CSIZE;
newtio.c_cflag |=CS8|CLOCAL | CREAD;
cfsetispeed(&newtio, B115200);
newtio.c_cc[VMIN]=0;
newtio.c_cc[VTIME]=0;
tcflush(fd,TCIOFLUSH);
sleep(2);
if((tcsetattr(fd,TCSANOW,&newtio))!=0)
{
perror("com set error");
return -1;
}
printf("set done!\n\r");
return 0;
}
void main()
{
int fd,nByte,count;
char *dev = "/dev/s3c2410_serial1";
char sendStr[]="please input:\n";
char buf[256];
memset(buf, 0, 256);
//open the serial port
if((fd = open(dev, O_RDWR | O_NOCTTY))<0)
printf("open com2 failed\n");
else{
printf("open com2 successfully\n");
}
set_attr(fd);
//write data to com2
write(fd,&sendStr, strlen(sendStr));
//read data from com2
count = 0;
while(count<5){
if((nByte = read(fd, buf, 256))>0){
printf("Read successfully : %d bytes\n", nByte);
printf("len : %d, buf[0] = %d\n", strlen(buf), buf[0]);
nByte = 0;
count++;
}
}
close(fd);
printf("关闭串口2\n");
}
运行之后,串口1接收到如下数据:
# ./uart_test1
open com2 successfully
set done!
串口2接收到如下数据:
please input:
当串口2输入字符串“hello”时,串口1输出如下:
# ./uart_test1
open com2 successfully
set done!
Read successfully : 1 bytes
len : 0, buf[0] = 0
说明arm的com2口并没有接收到字符串"hello"。
当改变c文件中newtio.c_cc[VMIN]的值为3,即最少接收到3个字节数据,read函数才能返回,则pc端需要发送3个"hello"字符串,才能显示接收到数据,如下所示:
# ./uart_test1
open com2 successfully
set done!
Read successfully : 3 bytes
len : 0, buf[0] = 0, buf[1] = 0, buf[2] = 0
串口外面硬件是接的回环吗?