使用c代码读取AT命令输出



我想读取使用c代码发送到GSM调制解调器的AT命令的输出。我做了一个代码,但在这个代码缓冲区没有显示正确的输出。请帮帮我。我想用这个代码打印单元格信息。我使用的AT命令是"AT+CCED=0,2"。

int main()
{
  int fd;  // File descriptor
  int n,i;
  char buf[1000]={""}; 
  char com[20]={"at+cced=0,2r"};       
  fd = open_port();
  // Read the configureation of the port
  struct termios options;
  tcgetattr( fd, &options );
  /* SEt Baud Rate */
  cfsetispeed( &options, B115200 );
  cfsetospeed( &options, B115200 );
  //I don't know what this is exactly
  options.c_cflag |= ( CLOCAL | CREAD );
  // Set the Charactor size
  options.c_cflag &= ~CSIZE; /* Mask the character size bits */
  options.c_cflag |= CS8;    /* Select 8 data bits */
  // Set parity - No Parity (8N1)
  options.c_cflag &= ~PARENB;
  options.c_cflag &= ~CSTOPB;
  options.c_cflag &= ~CSIZE;
  options.c_cflag |= CS8;
  options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
  // Disable Software Flow control
  options.c_iflag &= ~(IXON | IXOFF | IXANY);
  // Chose raw (not processed) output
  options.c_oflag &= ~OPOST;
  if ( tcsetattr( fd, TCSANOW, &options ) == -1 )
    printf ("1Error with tcsetattr = %sn", strerror ( errno ) );
  else
    printf ( "%sn", "tcsetattr succeed" );
  fcntl(fd, F_SETFL, FNDELAY);

  // Write some stuff !!!
  n = write(fd, com, strlen(com));
  if (n < 0)
    fputs("write() of 4 bytes failed!n", stderr);
  else
    printf ("Write succeed n  = %in", n );
  n=0;
  i=0;
  while (1) 
  {
    n = read( fd, buf, sizeof(buf) );
    if(n>0)
    {   
      printf("%s", buf);    
      fflush(stdout);
    }
    //   i=i+1;
  }
  close( fd );
  return 0;
}           
int open_port(void)
{
  int fd; /* File descriptor for the port */
  fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);
  if (fd == -1)
  {
    perror("open_port: Unable to open /dev/ttyUSB0 - ");
  }
  else
    fcntl(fd, F_SETFL, FNDELAY);
  printf ( "In Open port fd = %in", fd); 
  return (fd);
}

我以前做过这样的项目,但我使用Java!这是非常相似的(和痛苦)。

我来告诉你我是怎么做的:

  1. 您是否设置了正确的串口速率和位标志?
  2. 使用PuttySuper Terminal来确保在尝试编码任何东西之前您可以与GSM调制解调器通信。
  3. 确保你给一些空闲时间等待GSM调制解调器启动(也就是预热时间)。
  4. 一些特殊的chars引起问题-你是否正确处理它们?
  5. 您在通信结束时发送EOF, rn(取决于GSM调制解调器)?->有时你不会收到任何消息,直到你发送这个特殊的字符。

也要使用经过测试的库:

  • 串行库c++
  • RS-232 for Win and Linux
  • Lib Serial Port <-推荐

如果你的整个项目依赖于服务而不是调制解调器本身,你也可以使用在线GSM/SMS服务。

最新更新