c++ - 如何在linux中用c++代码读取AT命令

标签 c++ linux at-command

我编写了以下代码,其中我尝试从 SM5100b GSM(连接到 Rasberry Pi)向我的手机发送消息。它正在工作,但我只能在打开 Cutecom 模拟器时检查 AT 命令的结果,例如 Ok、Ok、+CME ERROR: 4、Ok。如何在这段代码中编写“读取”函数,以便在逐行编译过程中给出这些结果?我尝试了类似 out = read(fd, n, sizeof(n)) 的方法,但没有结果。我正在使用 Raspian、Debian 操作系统和 Codeblocks。

#include <stdio.h>   /* Standard input/output definitions */
#include <string.h>  /* String function definitions */
#include <unistd.h>  /* UNIX standard function definitions */
#include <fcntl.h>   /* File control definitions */
#include <errno.h>   /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */


int open_port(void)
{
 int fd; /* File descriptor for the port */
 int n,d,e,f,o,out;
 fd = open("/dev/ttyAMA0", O_RDWR | O_NOCTTY | O_NDELAY);
 if (fd == -1)
  {
  /* Could not open the port. */
   perror("open_port: Unable to open /dev/ttyAMA0");
  }
 else
  fcntl(fd, F_SETFL, 0);
  sleep(2);
  n = write(fd, "AT\r\n", 4);
  if (n < 0)
  fputs("write() of 4 bytes failed!\n", stderr);
  sleep(2);

  d = write(fd, "AT+CMGF=1\r", 10);
  if (d < 0)
  fputs("write() of 10 bytes failed!\n", stderr);
  sleep(2);

  e = write(fd, "AT+CMGS=\"6034****\"\r", 20);
  if (e < 0)
  fputs("write() of 20 bytes failed!\n", stderr);
  sleep(2);

  f = write(fd, "hello\r\x1A", 10);
  if (f < 0)
  fputs("write() of 10 bytes failed!\n", stderr);
  sleep(2);

  return (fd);
  }

  int main(void)
  {
  open_port();
  }

最佳答案

您可以创建一个名为 sendAT 的函数,它会执行如下操作:

int sendAT(char* command,int fd) {
  size_t cmdlen = strlen(command);

  int n = write(fd,command, cmdlen);
  if (n != cmdlen)
      return -1
  char reply[40];
  n = read(fd,reply,sizeof(reply));
  reply[n] = 0; //Terminate the string
  if (strcmp(reply, "OK")==0) 
      return 0; //All went well
  else
      return -1; //Some error occurred
}

目前,您有很多重复的代码,这些代码对您发送到手机的每个命令执行相同的操作。

关于c++ - 如何在linux中用c++代码读取AT命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16708121/

相关文章:

c++ - vector 矩阵乘法,浮点 vector ,二进制矩阵

regex - 使用shell脚本格式化文本文件内容

c - ESP-WROOM-02D 无法使用 AT 命令进行通信

c++ - 复制保护静态库

c++ - 如何重新设计 C++ 类?

java - 无法让 ZooKeeper 集群工作,选举永远不会发生

c++ - Linux 上的 C++ 在一行上打印 5000 个 float 时换行

android - 用于更改 IMSI android 的 AT 命令

http - 如何使用 ATCommands 检查我的 SIM800 模块默认拥有哪个 SSL 证书?如何使用 ATCommands 启用 HTTPS GET?

c++ - 带有模板的 lambda