c - 使用c代码读取AT COMMAND输出?

标签 c gsm at-command serial-communication

我想读取我的 AT 命令的输出,该命令使用 C 代码发送到 GSM 调制解调器。我编写了一个代码,但在此代码缓冲区中未显示正确的输出。请帮助我。 我想使用此代码打印单元格信息。我使用的 AT 命令是“AT+CCED=0,2”。

int main()
{
  int fd;  // File descriptor
  int n,i;
  char buf[1000]={"\0"}; 
  char com[20]={"at+cced=0,2\r"};       
  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 = %s\n", strerror ( errno ) );
  else
    printf ( "%s\n", "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  = %i\n", 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 = %i\n", fd); 
  return (fd);
}

最佳答案

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

我将向您介绍我为使其发挥作用所做的工作:

  1. 您是否设置了正确的串口速率和位标志?
  2. 在尝试编写任何代码之前,请使用 Putty super 终端 确保您可以与 GSM 调制解调器进行通信。
  3. 确保留出一些空闲时间来等待 GSM 调制解调器启动(又称:预热时间)。
  4. 一些特殊的字符会导致问题 - 您是否正确处理它们?
  5. 您在通信结束时是否发送 EOF\r\n\0(取决于 GSM 调制解调器) ? -> 有时,在发送这个特殊字符之前,您不会收到任何消息。

还可以使用经过测试的库:

Alternatively you can use online GSM/SMS services if your whole project depends on the service rather than the modem itself.

关于c - 使用c代码读取AT COMMAND输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25280186/

相关文章:

c - AT 命令 ESP8266 01 : AT+CIPSTART: How to fix response Link type Error/Can't connect with TCP

c - struct的正确使用方法

javascript - 如何在 Emscripten 中返回未知大小的数组?

c - 宏定义语法 "0000"

c++ - 如何计算尾数位数?

at-command - 移远EC25获取CQI

decode - 无法读取 AT 命令响应

android - 用于 LTE 和 GSM 网络的 eCGI 和 CGI

php - 使用 GSM 调制解调器在 PHP 中发送短信

android - 电话管理器 gsm 参数