c++smsraspberry-pigsm

C++ code to send messages with GSM from a Raspberry Pi


I just connected my Raspberry Pi with a SM5100B GSM. I would like to test it sending a simple message in my mobile. I can do it with emulators like Cutecom and Minicom (because I have a Raspbian Linux version). But Is there any code in C++ which does this job?

I do not use Arduino, only a SM5100B. I wrote this code until now and of course it does not work yet:

 #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 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

Solution

  • Open the relevant serial port (/dev/ttySx, where x is most likely a number), use write or fwrite to write to the port, close the port, exit program.