[問題] rs232接收byte不穩定

看板LinuxDev作者 (小強)時間10年前 (2015/07/07 16:56), 編輯推噓1(102)
留言3則, 3人參與, 最新討論串1/1
小弟寫 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 -- -- -- -- -- -- |abcdefghij------ s = abcdefghij rcv = 10 [root@localhost aa]# ./new_rs232 0000 | 61 62 63 64 -- -- -- -- -- -- -- -- -- -- -- -- |abcd------------ s = abcd rcv = 4 [root@localhost aa]# ./new_rs232 0000 | 61 62 63 64 65 66 67 68 69 6a -- -- -- -- -- -- |abcdefghij------ s = abcdefghij rcv = 10 [root@localhost aa]# ./new_rs232 0000 | 61 62 63 64 65 66 67 68 69 6a -- -- -- -- -- -- |abcdefghij------ s = abcdefghij rcv = 10 [root@localhost aa]# ./new_rs232 0000 | 61 62 63 64 65 66 67 -- -- -- -- -- -- -- -- -- |abcdefg--------- s = abcdefg rcv = 7 為何有時會漏掉後面的資料? 收發操作我是用手動發送己有用示波器確定有發滿10byte 但linux read 有時會漏掉後面byte 是設定有設錯? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 220.133.28.13 ※ 文章網址: https://www.ptt.cc/bbs/LinuxDev/M.1436259388.A.CDA.html

07/07 21:37, , 1F
我猜termios有些flag可以解決
07/07 21:37, 1F

07/08 09:54, , 2F
那應該修改那裡的設定比較好?
07/08 09:54, 2F

07/14 16:57, , 3F
cflag 加這CRTSCTS看看~或者VMIN=1試試看~
07/14 16:57, 3F
文章代碼(AID): #1LcvGypQ (LinuxDev)
文章代碼(AID): #1LcvGypQ (LinuxDev)