如何在linux中使用c++代码读取AT命令
how to read AT commands with c++ code in linux
我编写了以下代码,其中我试图从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
}
现在你有很多重复的代码,对你发送给手机的每一个命令都做同样的事情。
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 代码在main()中运行,但在函数中出现错误
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 编译包含字符串的代码时遇到问题
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 在Linux for Windows上编译C++代码时出错
- 我的字符计数代码计算错误.为什么
- 孤立代码块在结构中引发异常
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 此代码是否违反一个定义规则
- 为什么我的代码在输出中增加了93天
- 我的简单if-else语句是如何无法访问的代码
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 为什么在这个代码结束循环中没有得到结束
- 在c代码之间共享数据的最佳方式
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值