0

我编写了以下代码,其中我试图将消息从 SM5100b GSM(连接到 Rasberry Pi)发送到我的手机。它正在工作,但我可以检查 AT 命令的结果,例如 Ok、Ok、+CME ERROR: 4,只有在我打开 Cutecom 模拟器时才可以。如何在此代码中编写“读取”函数以在逐行编译期间为我提供这些结果?我尝试了类似 out = read(fd, n, sizeof(n)) 但没有结果。我正在使用 Raspian 一个 Debian 操作系统和代码块。

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

1 回答 1

1

您可以创建一个名为 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
}

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

于 2013-05-23T07:42:19.640 回答