[問題] rs232接收byte不穩定

作者: liang168 (小強)   2015-07-07 16:56:26
小弟寫 linux rs232 接收程式
程式碼如下
#define BAUDRATE B115200
#define MODEMDEVICE "/dev/ttyUSB0"
#define _POSIX_SOURCE 1
//這是設定rs232
int rs232_init(void)
{
int fd_a;
struct termios old_tio, new_tio;
fd_a = open( MODEMDEVICE, O_RDWR | O_NOCTTY | O_SYNC);
if( fd_a < 0 )
{
printf("open rs232 error\n");
exit(-1);
}
// printf("rs232 %s is open \n",MODEMDEVICE);
tcgetattr(fd_a,&old_tio);
bzero(&new_tio, sizeof(new_tio));
new_tio.c_cflag = BAUDRATE | CS8 | CLOCAL | CREAD;
new_tio.c_iflag = IGNPAR;
new_tio.c_oflag = 0;
new_tio.c_lflag = 0; //ICANON;
new_tio.c_cc[VMIN] = 2;
new_tio.c_cc[VTIME] = 0;
tcflush(fd_a,TCIFLUSH);
cfsetospeed(&new_tio, B115200);
cfsetispeed(&new_tio, B115200);
tcsetattr(fd_a,TCSANOW,&new_tio);
return fd_a;
}
//這個是讀取
int read_port(int fd, char* buf, int imax)
{
int iin;
// printf("read port\n");
if( buf==NULL || fd < 1)
{
return -1;
}
strncpy(buf, "N/A", imax<4?imax:4);
while( (iin = read(fd, buf, imax-1)) < 0 )
{
if(errno == EAGAIN)
{
return 0;
}
else
{
printf("read error \n");
}
}
buf[iin<imax?iin:imax] = '\0';
return iin;
}
int main(void)
{
int fd ;
char rcv = 0;
char recvbuff[256];
init_flash_buffer();
fd = rs232_init();
rcv = read_port(fd,recvbuff,sizeof(recvbuff));
write_port(fd,"abcd",4);
memdump(recvbuff,rcv);
printf("s = %s\n",&recvbuff[0]);
printf("rcv = %d \n",rcv);
close(fd);
return 0;
}
硬體是使用 usb to rs232 接到 win7 pc 兩邊都是 pc
win7 發 61 62 63 64 65 66 67 68 69 6A << 都是16進制碼 共10 byte
linux 端讀五次結果
./new_rs232
0000 | 61 62 63 64 65 66 67 68 69 6a
作者: soso7885 (YOHO)   2015-07-07 21:37:00
我猜termios有些flag可以解決
作者: liang168 (小強)   2015-07-08 09:54:00
那應該修改那裡的設定比較好?
作者: dardar923 (CrazyDar)   2015-07-14 16:57:00
cflag 加這CRTSCTS看看~或者VMIN=1試試看~

Links booklink

Contact Us: admin [ a t ] ucptt.com