2014-02-23 44 views
0

我想通过串口发送下一个命令“at”给我的gprs。 gprs应该回应“ok”,但我无法弄清楚下面的代码。 当我在gtkterm(在我的Debian中)“at”发送命令时,我按下输入gprs响应“ok” 没有问题,但在我的代码中有些问题是错误的。我以为这是\r,但我不知道。通过串口向gprs写入命令C

新代码,但具有相同的结果:

#include <string.h> 
#include <stdlib.h> 
#include <stdio.h> 
#include <unistd.h> 
#include <fcntl.h> 
#include <termios.h> 
#include <stdbool.h> 

int main(int argc,char** argv) 
{ 
    char comando[]={'a','t','\r','\0'}; 
     comunicacion(comando); 

     return EXIT_SUCCESS; 
} 
comunicacion(char data[]) 
{ 
    struct termios tio; 
     struct termios stdio; 
     struct termios old_stdio; 
     int tty_fd; 

     unsigned char c ='d'; 
     tcgetattr(STDOUT_FILENO,&old_stdio); 

     printf("Please start with /dev/ttyS1 (for example)\n"); 
     memset(&stdio,0,sizeof(stdio)); 
     stdio.c_iflag=0; 
     stdio.c_oflag=0; 
     stdio.c_cflag=0; 
     stdio.c_lflag=0; 
     stdio.c_cc[VMIN]=1; 
     stdio.c_cc[VTIME]=0; 
     tcsetattr(STDOUT_FILENO,TCSANOW,&stdio); 
     tcsetattr(STDOUT_FILENO,TCSAFLUSH,&stdio); 
     fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);  // make the reads non-blocking 

     memset(&tio,0,sizeof(tio)); 
     tio.c_iflag=0; 
     tio.c_oflag=0; 
     tio.c_cflag=CS8|CREAD|CLOCAL;   // 8n1, see termios.h for more information 
     tio.c_lflag=0; 
     tio.c_cc[VMIN]=1; 
     tio.c_cc[VTIME]=5; 

     tty_fd=open("/dev/ttyUSB0", O_RDWR | O_NONBLOCK);  
     cfsetospeed(&tio,B115200);   // 115200 baud 
     cfsetispeed(&tio,B115200);   // 115200 baud 

     tcsetattr(tty_fd,TCSANOW,&tio); 
     // enter \r 


     int i =0; 
     char caracter = ' '; 
     bool ciclo = true; 

     while(ciclo) 
     { 
      c=data[i]; 
      i++; 
      if(c != '\0') 
      { 
       write(tty_fd,&c,1);  
      } 
      else 
      { 
       if(read(tty_fd,&c,1)>0) 
       { 
        write(STDOUT_FILENO,&c,1); 
       } 
       else 
       { 
        ciclo = false; 
       } 
      } 
     } 

     // if new data is available on the serial port, print it out 
     // if new data is available on the console, send it to the serial port 

     close(tty_fd); 
     tcsetattr(STDOUT_FILENO,TCSANOW,&old_stdio); 
} 

回答

0

您的循环可以轻松地运行您的数据阵列的末端,导致未定义的行为。当data[i]为0时,您需要始终设置ciclo=false,因此您应该删除(通常是无用的)ciclo变量,并使用while (data[i] != 0)作为循环。

如果你想发送你的数据,然后读取响应(这看起来很可能),那么你需要TWO循环 - 第一个循环写入命令,然后第二个非嵌套循环读取响应。

+0

是准确,另外我有做纳米的睡眠,因为GPRS时发送的响应花了几纳秒响应。 – Premier

0

你的循环while (ciclo)是无限的:ciclo永远不会成为false。 基本上,您应该发送命令然后读取响应(并且响应可能包含每个发送字符多个字符)。

此外,我不知道如何检测到data的结尾:目前您的command只包含3个字符,而没有终止'\0'

+0

是的我做了porpuse上的无限循环等待响应,代码是从外壳按键读 – Premier

+0

我的新代码,但具有相同的结果,同时(ciclo) c = data [i]; i ++; 如果(C!= '\ 0') { 写(tty_fd,&c,1); } 别的 { 如果(读(tty_fd,&amp; C,1)> 0) { 写(STDOUT_FILENO,&c,1); } 其他 { CICLO = FALSE; }} } – Premier