c++代码发送消息与GSM从树莓派
C++ code to send messages with GSM from a Raspberry Pi
我刚刚将我的树莓派与SM5100B GSM连接起来。我想测试一下,用我的手机发一条简单的信息。我可以用像Cutecom和Minicom这样的模拟器来做(因为我有一个Raspbian Linux版本)。但是在c++中有任何代码可以完成这项工作吗?
我不使用Arduino,只有SM5100B。我写了这段代码,当然它还不能工作:
#include <stdio.h> // Standard input / output functions
#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
#include <time.h> // Time calls
int open_port(void)
{
int fd; // File description for the serial port
fd = open("/dev/ttyAMA0", O_RDWR | O_NOCTTY | O_NDELAY);
if(fd == -1) // if open is unsucessful
{
//perror("open_port: Unable to open /dev/ttyAMA0 - ");
printf("open_port: Unable to open /dev/ttyAMA0. n");
}
else
{
fcntl(fd, F_SETFL, 0);
printf("port is open.n");
}
return(fd);
} //open_port
int configure_port(int fd) // Configure the port
{
struct termios port_settings; // Structure to store the port settings in
cfsetispeed(&port_settings, B9600); // Set baud rates
cfsetospeed(&port_settings, B9600);
port_settings.c_cflag &= ~PARENB; // Set no parity, stop bits, data bits
port_settings.c_cflag &= ~CSTOPB;
port_settings.c_cflag &= ~CSIZE;
port_settings.c_cflag |= CS8;
tcsetattr(fd, TCSANOW, &port_settings); // Apply the settings to the port
return(fd);
} //configure_port
int query_modem(int fd) // Query modem with an AT command
{
char n;
fd_set rdfs;
struct timeval timeout;
// Initialise the timeout structure
timeout.tv_sec = 10; // Ten second timeout
timeout.tv_usec = 0;
unsigned char send_bytes[] = "AT+CMGF=1";
unsigned char send_bytes1[] = "AT+CMGS="603*****"";
unsigned char send_bytes3[] = "TEST";
//puts(send_bytes);
write(fd, send_bytes, 13); // Send data
write(fd, send_bytes1, 13);
write(fd, send_bytes3, 13);
//printf("Wrote the bytes. n");
// Do the select
n = select(fd + 1, &rdfs, NULL, NULL, &timeout);
// Check if an error has occured
if(n < 0)
{
perror("select failedn");
}
else if (n == 0)
{
puts("Timeout!");
}
else
{
printf("nBytes detected on the port!n");
}
return 0;
} //query_modem
int main(void)
{
int fd = open_port();
configure_port(fd);
query_modem(fd);
return(0);
} //main
打开相关的串行端口(/dev/ttySx,其中x很可能是一个数字),使用write或fwrite向端口写入,关闭端口,退出程序。
相关文章:
- 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++代码发送消息与GSM从树莓派
- 如何与GSM调制解调器通信的c++代码