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

how to read AT commands with c++ code in linux

本文关键字:代码 c++ 读取 AT 命令 linux      更新时间:2023-10-16

我编写了以下代码,其中我试图从SM5100b GSM(连接到Rasberry Pi)发送消息到我的手机。它正在工作,但我可以检查AT命令的结果,例如Ok, Ok, +CME ERROR: 4, Ok,只有当我打开Cutecom模拟器时。我怎么能写一个"读"函数在这段代码给我这些结果在逐行编译?我尝试了out = read(fd, n, sizeof(n))之类的东西,但没有结果。我使用的是Raspian、Debian OS和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, "ATrn", 4);
  if (n < 0)
  fputs("write() of 4 bytes failed!n", stderr);
  sleep(2);
  d = write(fd, "AT+CMGF=1r", 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, "hellorx1A", 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
}

现在你有很多重复的代码,对你发送给手机的每一个命令都做同样的事情。