简体   繁体   English

如何在Linux中使用C ++代码读取AT命令

[英]how to read AT commands with c++ code in linux

I wrote the following code in which I am trying to send a message from a SM5100b GSM(which is connected to a Rasberry Pi) to my mobile. 我编写了以下代码,其中我试图从SM5100b GSM(已连接到Rasberry Pi的手机)发送消息到我的手机。 It is working but I can check the results of AT commands for example Ok, Ok, +CME ERROR: 4, Ok only when I have Cutecom emulator opened. 它正在工作,但是我可以检查AT命令的结果,例如,确定,确定,+ CME错误:4,仅当我打开Cutecom模拟器时才能确定。 How can I write a "read" function in this code to give me these results during the compiling line by line? 如何在此代码中编写“读取”函数,以便在逐行编译期间为我提供这些结果? I tried something like out = read(fd, n, sizeof(n)) but I did not have results. 我尝试了类似out = read(fd,n,sizeof(n))的方法,但没有结果。 I am using Raspian a Debian OS and Codeblocks. 我正在使用Raspian,Debian OS和Codeblock。

#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();
  }

You could make a function called like sendAT, which would do something like this: 您可以创建一个名为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
}

At the moment you have a lot of duplicated code that does the same thing for every command that you send to the phone. 目前,您有很多重复的代码,对于您发送到手机的每个命令,它们都执行相同的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM