用GSM发送消息的C ++代码

时间:2013-05-20 06:29:37

标签: c++ sms raspberry-pi gsm

我刚刚将覆盆子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 definitionss
 #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 failed\n");
}
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

1 个答案:

答案 0 :(得分:0)

打开相关的串口(/ dev / ttySx,其中x很可能是一个数字),使用write或fwrite写入端口,关闭端口,退出程序。