2015-10-15 42 views
1

我有一個GSM調制解調器,並通過膩子進行測試。有用。然後我發送AT與我的C++程序,但調制解調器回覆AT。它只是迴應我的命令,沒有回答好。
這是我的代碼:爲什麼我的AT命令在我的GSM調制解調器中回聲?

#include <QCoreApplication> 
#include <stdio.h> 
#include <string.h> 
#include <unistd.h> 
#include <fcntl.h> 
#include <errno.h> 
#include <termios.h> 
#include <iostream> 
int fd; 
int openport(void) 
{ 

fd=open("/dev/ttyUSB0",O_RDWR|O_NOCTTY|O_NDELAY); 

     if (fd==-1) 
       { 
       perror("open_port: unable to open port /dev/ttyUSB0\n"); 
       return -1; 
       } 
     else 
       { 
       printf("open_port: succesfully open port /dev/ttyUSB0\n"); 
       fcntl(fd,F_SETFL,0); 
       return 1; 
       } 
} 
void closeport(void) 
{ 
    close(fd); 
} 
void configport(void) 
{ 
struct termios options; 
tcgetattr(fd,&options); 
cfsetispeed(&options,B9600); 
cfsetospeed(&options,B9600); 
options.c_cflag |= (CLOCAL | CREAD); 
tcsetattr(fd,TCSANOW,&options); 
options.c_cflag &= ~CSIZE; 
options.c_cflag |= CS8; 
options.c_cflag &= ~ PARENB; 
options.c_cflag &= ~CSTOPB; 
options.c_cflag &= ~CSIZE; 
options.c_cflag |= CS8; 
options.c_iflag &= ~(IXON|IXOFF|IXANY); 
} 
void writeport1(void) 
{ 
    char w[]="AT\r\n"; 

    //std::cout << strlen(w); 
    //std::cout << w; 

    write(fd,w,sizeof(w)); 
} 



int main(int argc, char *argv[]) 
{ 
    QCoreApplication a(argc, argv); 
    int aa ; 
    char i[10]; 
    aa=openport(); 
    if (aa==1) 
    { 
     configport(); 
     writeport1(); 
     printf("start reading ..... \n"); 
     aa=read(fd,i,sizeof(i)); 
     i[aa]=0;//terminate the string 
     //std::cout << i << std::endl; 
     printf("finish reading ..... \n"); 

    } 

    closeport(); 
    return a.exec(); 
} 

輸出是這樣的:

轉到打開端口open_port:
成功地打開的端口的/ dev/ttyUSB0端口
[根@ FriendlyARM /]# ./SerialPort -qws
open_port:成功打開端口/ dev/ttyUSB0
開始閱讀.....

我的錯誤在哪裏?

+0

找到一些工具可以讓你準確地看到串行端口傳輸的字節,這可能很有用。我有一個硬件設備,可以與串行電纜串聯並捕獲數據,並且存在允許您在數據通過串行端口驅動程序時查看數據的軟件。觀察*上的*實際數據對於解決這類問題非常有用。很可能你會看到來自你的程序的字節並不完全符合你的期望,或者「確定」真的回來了,就像其他人暗示的那樣遲到。 – Steve

+0

如何查看串口的字節傳輸?我認爲這是我的問題。 (我的意思是也許我發送的數據有問題)。當我將AT與我的電腦發送到我的調制解調器時,立即回答OK。 –

回答

1

您還沒有終止字符串w,因此而write電話是好的,你得到了一個未定義的行爲,當你把它傳遞給cout - 變化:

char w[4]; 
w[0]=65; 
w[1]=84; 
w[2]=13; 
w[3]=10; 
//sprintf(i,"2f9",k); 
std::cout << w; 
write(fd1,w,sizeof(w)); 

到:

char w[5]; 
w[0]='A'; 
w[1]='T'; 
w[2]=13; 
w[3]=10; 
w[4]=0;     // <<< 
//sprintf(i,"2f9",k); 
std::cout << w; 
write(fd1,w,strlen(w)); // <<< 

或者可能更簡潔:

char w[] = "AT\r\n" 
std::cout << w; 
write(fd1,w,strlen(w)); 
+0

感謝我的朋友。但在更改代碼後。它仍然不起作用:( –

+0

)你可能有多個bug,但至少可以修復其中一個bug。請注意,大多數調制解調器默認情況下都會回顯命令,所以如果你發送「AT」,你會得到「AT」回顯,然後是「OK」 –

+1

回聲命令可能會混淆控制檯,所以關閉命令回顯 AT命令是ATE0,然後回聲關閉 –

0

它tak es調制解調器回覆OK的時間,嘗試等待一段時間然後讀取,或者將讀取放入循環中。

+0

當我在膩子測試,調制解調器立即回覆我確定。 (5),但沒有任何變化。 –

相關問題