How to control an led from Thingspeak server using SIM900A and Arduino? - arduino

I am trying to control a LED from Thingspeak server by using the GSM module.
The data received is successfully being printed on serial monitor(which is '1' as last updated) but when I am trying to assign that data to a variable so as to control the inbuilt LED of Arduino, nothing happens.
#include <SoftwareSerial.h>
SoftwareSerial SIM900A(10, 11);
void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
SIM900A.begin(9600);
Serial.begin(9600);
while (!Serial)
;
Serial.println("Arduino is ready");
SIM900A.begin(9600);
Serial.println("SIM900A started at 9600");
delay(1000);
Serial.println("Setup Complete");
}
void loop()
{
SIM900A.println("AT");
delay(1000);
ShowSerialData();
SIM900A.println("AT+CIPSHUT");
delay(2000);
ShowSerialData();
SIM900A.println("AT+CIPMUX=0");
delay(2000);
ShowSerialData();
SIM900A.println("AT+CGATT=1");
delay(5000);
SIM900A.println("AT+CSTT=\"INTERNET\",\"\",\"\"");
delay(4000);
SIM900A.println("AT+CIICR");
delay(3000);
ShowSerialData();
SIM900A.println("AT+CIFSR");
delay(5000);
ShowSerialData();
SIM900A.println("AT+CIPSTART=\"TCP\",\"184.106.153.149\",\"80\"");
delay(4000);
ShowSerialData();
SIM900A.println("AT+CIPSEND");
delay(4000);
SIM900A.print("GET /channels/798173/fields/1/last");
SIM900A.print("\r\n\x1A");
ShowSerialData();
char led = SIM900A.read();
Serial.print(led);
if (led == '1')
{
digitalWrite(LED_BUILTIN, HIGH);
}
else if (led == '0')
{
digitalWrite(LED_BUILTIN, LOW);
}
delay(8000);
}
void ShowSerialData()
{
while (SIM900A.available() != 0)
Serial.print(char(SIM900A.read()));
}
Last portion of the output from the serial monitor:
CONNECT OK
AT+CIPSEND
> ⸮GET /channels/798173/fields/1/last
SEND OK
1

As pointed out by #Saurabh P Bhandari, you cannot read the same data from the serial twice, thus you'd need to read the data in a variable in the first place if you wish to use it.
String getSerialData(){
String buffer="";
while (SIM900A.available() ){
char c = SIM900A.read();
buffer+=c;
}
return buffer;
}
Then you can use String led = getSerialData() to populate led with the buffer.
Here, you need to beware that the function getSerialData would return anything present on the buffer and would look something like:
GET /channels/798173/fields/1/last
SEND
HTTP RESPONSE
It appears that you're only interested in HTTP RESPONSE, thus you can update your conditionals to be
if(led.endsWith("1"))
...
else if(led.endsWith("0"))

From what I have understood so far, in this snippet
SIM900A.print("GET /channels/798173/fields/1/last");
SIM900A.print("\r\n\x1A");
ShowSerialData();
ShowSerialData() is printing the output which is '1'. Then immediately your are reading data into the variable led. Since, the actual data received is being printed already from ShowSerialData(), the next time you call SIM900A.read() will return either nothing or next set of data being sent by your module.

You are likely getting rate limited because you are hitting ThingSpeak servers too frequently. You can only update a channel once every 15s with a free account. Obviously, it makes no sense to ask for a value faster than it can be updated, i.e., once every 15s with a free account.
Consider putting some required delays in your code to ensure your device is not blacklisted for abuse of terms.

Related

How can I create an automated GPS tracker using A9G AI Thinker module?

I have an AI Thinker A9G module connected to an ESP8266 D1 mini. I have the following script to send and receive AT commands to/from the module. The idea is to get a SMS with the Google maps GPS location of the module onto my mobile phone.
// GPS tracker with AI Thinker A9G module and AZ Delivery D1 Mini ESP8266 module
#include <SoftwareSerial.h>
#define rxPin D7
#define txPin D8
SoftwareSerial A9modem(rxPin, txPin); // Pins D7 Rx and D8 Tx are used as used as software serial pins
String incomingData; // For storing incoming serial data
String gpsData; // For storing location data
char msg;
char call;
void setup()
{
Serial.begin(115200); // Baud rate for serial monitor
A9modem.begin(115200); // Baud rate for GSM shield
Serial.println("GPS/GSM A9G BEGIN");
Serial.println("Enter character for control option: ");
Serial.println("h : to disconnect a call");
Serial.println("s : to send a message");
Serial.println("r : to receive a message");
Serial.println("c : to make a call");
Serial.println("l : to read location");
Serial.println("d : to disconnect gps");
Serial.println();
delay(100);
// Set SMS mode to text mode
A9modem.print("AT+CMGF=1\r");
delay(100);
// Set GSM module to TP show the output on serial out
A9modem.print("AT+CNMI=2,2,0,0,0\r");
delay(100);
}
void loop()
{
ReceiveMessage();
gpsData = incomingData.substring(33, 52);
Serial.print("Location: ");
Serial.println(gpsData);
delay(2000);
if (Serial.available() > 0)
switch(Serial.read())
{
case 's':
SendMessage();
break;
case 'r':
ReceiveMessage();
break;
case 'c':
MakeCall();
break;
case 'h':
HangupCall();
break;
case 'l':
ReadLocation();
break;
case 'd':
DisconnectGps();
break;
}
}
void ReceiveMessage()
{
if (A9modem.available() > 0)
{
incomingData = A9modem.readString(); // Get the data from the serial port
Serial.print(incomingData);
delay(100);
}
}
void SendMessage()
{
A9modem.println("AT+CMGF=1"); // Sets the GSM Module into text mode
delay(1000); // Delay of one second
A9modem.println("AT+CMGS=\"xxxxxxxxxxxxx\"\r"); // Replace your mobile number here
delay(1000);
String sms = "http://maps.google.com/maps?q=" + gpsData; // Create the SMS location string
A9modem.println(sms);
delay(100);
A9modem.println((char)26); // ASCII code of CTRL+Z
delay(1000);
}
void MakeCall()
{
A9modem.println("ATD+xxxxxxxxxxxxx;"); // Replace your mobile number here
Serial.println("Calling "); // Print response over serial port
delay(1000);
}
void HangupCall()
{
A9modem.println("ATH");
Serial.println("Hangup Call");
delay(1000);
}
void DisconnectGps()
{
A9modem.println("AT+GPS=0");
Serial.println("Disconnect GPS");
delay(1000);
}
void ReadLocation()
{
A9modem.println("AT+GPS=1");
delay(1000);
A9modem.println("AT+LOCATION=2"); // Check location every two seconds
delay(2000);
}
So if I use the commands "l" and "s" in Arduino IDE serial monitor everything is working well but I don't know how to change the code in a way that I get a fully automated GPS tracker. The idea is the following: Power on starts the tracker. When gpsData string is not empty the first SMS will be send to my mobile phone. The next SMS follows 20 minutes later and so on until power is switched off. Could you help please?
Thanks in advance!
Finally I came up with this solution but I'm not very happy with it (it is working but I have to restart the module from time to time because there are no GPS data). There are 3 reasons for this: There is no error handling for the GPS function, I set the delays in a more ore less random way to get everything working but I don't know if the values make sense and I don't know if the substring() function is the best way to get the location from the serial response.
// GPS tracker with AI Thinker A9G module and AZ Delivery D1 Mini
ESP8266 module
#include <SoftwareSerial.h>
#define rxPin D7
#define txPin D8
SoftwareSerial A9modem(rxPin, txPin); // Pins D7 Rx and D8 Tx are used as used as software serial pins
String incomingData; // For storing incoming serial data
String gpsData; // For storing location data
int runGps = 1;
int sendSms = 0;
void setup()
{
pinMode(LED_BUILTIN, OUTPUT); // Use builtin LED for correct GPS status
Serial.begin(115200); // Baud rate for serial monitor
A9modem.begin(115200); // Baud rate for GSM shield
// Set SMS mode to text mode
A9modem.print("AT+CMGF=1\r");
delay(300);
// Set GSM module to TP show the output on serial out
A9modem.print("AT+CNMI=2,2,0,0,0\r");
delay(1000);
Serial.end();
delay(500);
}
void loop()
{
Serial.begin(115200);
ReceiveMessage(); // Start a new serial stream
gpsData = incomingData.substring(33, 52); // Strip all unnessesary data from the stream
Serial.print("Location: "); // Check if the location data are correct
Serial.println(gpsData);
delay(1000);
if(runGps == 1) { // Start GPS
ReadLocation();
delay(20000); // Wait for GPS to be ready
}
if(gpsData.length() == 19 && sendSms == 0) { // If the location string is correct send SMS
if (isdigit(gpsData.charAt(0))) { // Check if the stream starts with a number
SendMessage();
digitalWrite(LED_BUILTIN, HIGH);
delay(300);
digitalWrite(LED_BUILTIN, LOW);
delay(300);
digitalWrite(LED_BUILTIN, HIGH);
delay(300);
digitalWrite(LED_BUILTIN, LOW);
delay(300);
digitalWrite(LED_BUILTIN, HIGH);
}
}
if(runGps == 0 && sendSms == 1) {
runGps = 1;
sendSms = 0;
delay(6000); // Make sure that all SMS serial communication is over
while (A9modem.available()) {
A9modem.read(); // Delete all data from serial buffer
}
delay(300000); // If SMS was sent wait 5 minutes before running the main loop again
Serial.end();
delay(500);
}
}
void ReceiveMessage()
{
if (A9modem.available() > 0)
{
incomingData = A9modem.readString(); // Get the data from the serial port
Serial.print(incomingData);
delay(500);
}
}
void SendMessage()
{
sendSms = 1; // Stop starting the SendMessage function
A9modem.println("AT+CMGF=1"); // Sets the GSM Module into text mode
delay(1000);
A9modem.println("AT+CMGS=\"xxxxxxxxxx\"\r"); // Replace your mobile number here
delay(1000);
String sms = "http://maps.google.com/maps?q=" + gpsData; // Create the SMS string
A9modem.println(sms);
delay(500);
A9modem.println((char)26); // ASCII code of CTRL+Z
delay(500);
}
void ReadLocation()
{
runGps = 0; // Stop starting the ReadLocation function
A9modem.println("AT+GPS=1");
delay(1000);
A9modem.println("AT+LOCATION=2"); // Check location every two seconds
delay(2000);
}
Try turning ON the NMEA stream from the A9G. Say you want to get the NMEA data every t seconds, you can add and then call the following function once in the void setup()
void TurnOnNMEA(int t)
{
if(t > 3600)
t = 3600; // Because the max time is 3600s
A9modem.print("AT+GPSRD=");
A9modem.println(t);
while(!A9modem.available()); // wait till the A9G sends a response
char c;
while(A9modem.available())
{
c = A9modem.read();
Serial.print(c);
delay(2); // Time needed for the next character
}
}
This will start the NMEA data stream every t seconds which you can print using the following function,
void ReadNMEA()
{
char c; // Read each character from the stream as it comes
if(A9modem.available())
{
c = A9modem.read();
Serial.print(c);
delay(2); // Time needed for the next character
}
}
Parsing and decoding the NMEA is a bit tricky thing to do. There is a lot of information inside it and the decoding depends on what you want to do with it. If you just want the location, you can parse the $GNGGA line.
When parsing the data, DO NOT USE Arduino String() class. It is a very bad idea when handling this kind of stream. Instead, use char array.

How to prevent other phone/mobile numbers to send SMS command to Arduino?

INTRO:
I'm a novice when it comes to Arduino programming and using AT commands. I already tried to search the whole internet and asked on Arduino forum, but I have no luck and nobody seems to give me a clear idea about it there.
PROBLEM:
So, I have this code where an SMS command can switch on and off the light and it will response to a specific phone number only. My problem is, the program response even when I'm using different phone numbers. I hope there's a way which it can only whitelist a specific number so no one can prank the program without the owner's knowledge.
FOR EXAMPLE:
The owner's phone number is +631234567890
Some random phone number: +63xxxxxxxxxx
The owner can switch on and off the light. [YES]
But supposedly, the random phone number CAN NOT and will never have the authority to switch the lights on and off. Only the owner can.
HERE'S MY CURRENT CODE: CCTO
#include <SoftwareSerial.h>
SoftwareSerial GPRS(10, 11);
String textMessage;
String lampState;
const int relay = 12;
void setup() {
pinMode(relay, OUTPUT);
digitalWrite(relay, HIGH);
Serial.begin(9600);
GPRS.begin(9600);
delay(5000);
Serial.print("GPRS ready...\r\n");
GPRS.print("AT+CMGF=1\r\n");
delay(1000);
GPRS.print("AT+CNMI=2,2,0,0,0\r\n");
delay(1000);
}
void loop(){
if(GPRS.available()>0){
textMessage = GPRS.readString();
Serial.print(textMessage);
delay(10);
}
if(textMessage.indexOf("ON")>=0){
// Turn on relay and save current state
digitalWrite(relay, HIGH);
lampState = "ON";
Serial.println("Lamp set to ON\r\n");
textMessage = "";
GPRS.println("AT+CMGS=\"+631234567890\"");
delay(500);
GPRS.print("Lamp was finally switched ON.\r");
GPRS.write( 0x1a );
delay(1000);
}
if(textMessage.indexOf("OFF")>=0){
// Turn off relay and save current state
digitalWrite(relay, LOW);
lampState = "OFF";
Serial.println("Lamp set to OFF\r\n");
textMessage = "";
GPRS.println("AT+CMGS=\"+631234567890\"");
delay(500);
GPRS.print("Lamp was finally switched OFF.\r");
GPRS.write( 0x1a );
delay(1000);
}
if(textMessage.indexOf("STATUS")>=0){
String message = "Lamp is " + lampState;
GPRS.print("AT+CMGF=1");
delay(1000);
Serial.println("Lamp state resquest");
textMessage = "";
GPRS.println("AT+CMGS=\"+631234567890\"");
delay(500);
GPRS.print("Lamp is currently ");
GPRS.println(lampState ? "ON" : "OFF");
GPRS.write( 0x1a );
delay(1000);
}
}
How can I do that?
Your textMessage must contain an information about sender and time of the message. Something like this:
+CMGL: 2,"REC UNREAD","+63xxxxxxxxxx",,"07/02/18,00:07:22+32" A simple demo of SMS text messaging.
So, you need to extract the phone number at compare it with the authorized one.
You can define the desired phone number in the code and compare it with the number assigned to the incoming SMS. If the number matches the one in your code, proceed with the algorithm. Otherwise, ignore the message.
Got this code from the official Arduino Forum, which you can check out from the link given at the end. You can code out these two functions:
String CellNumtemp;
String CellNum;
// check if there are incoming SMS
void ricezione(){
Serial.println ("controllo ricezione SMS");
// AT command to set mySerial to SMS mode
mySerial.print("AT+CMGF=1\r");
delay(100);
// Read the first SMS saved in the sim
mySerial.print("AT+CMGR=1\r");
delay(10);
if(mySerial.available()>0){
textMessage = mySerial.readString();
Serial.print(textMessage);
delay(10);
}
// check if the SMS is "STATO"
if(textMessage.indexOf("STATO")>=0){
Serial.println("Invio info stato arnia");
//save the phone number of the senders in a string (this works with italian region you must adapt to yours)
CellNumtemp = textMessage.substring(textMessage.indexOf("+39"));
CellNum = CellNumtemp.substring(0,13);
smsstato();
CellNumtemp = "";
textMessage = "";
}
mySerial.print("AT+CMGD=1\r");
delay(100);
mySerial.print("AT+CMGD=2\r");
delay(100);
}
// Send sms with all the information to the number stored
void smsstato(){
// delete the first SMS
mySerial.print("AT+CMGD=1\r");
delay(100);
mySerial.print("AT+CMGF=1\r");
delay(1000);
mySerial.print("AT+CMGS=\"");
mySerial.print(CellNum);
mySerial.print("\"\r");
delay(1000);
//The text of the message to be sent.
mySerial.print("INFO: Latitudine: ");
mySerial.print(latitude);
mySerial.print(", Longitudine: ");
mySerial.print(logitude);
mySerial.print(", Ampere: ");
mySerial.print(consumotemp);
delay(1000);
mySerial.write(0x1A);
delay(1000);
Serial.println("sms stato");
}```
Thanks to the user ilteo85 on the https://forum.arduino.cc.
Check this out for reference: https://forum.arduino.cc/index.php?topic=637264.0
you could just use the whitelisting function in gsm module
the cmd is
AT+CWHITELIST=mode,index,number
Parameters
0 Disable
1 Enable only call white list
2 Enable only SMS white list
3 Enable call and SMS white list
The index of phone number, scope: 1-30
Phone number to be set
example
AT+CWHITELIST=2,1,+9198xxxxxxx

Store value in variable after HTTPREAD

I am working with a GSM SIM900 and an Arduino Uno. I am using AT commands for the SIM900. I am successfully getting data from GET requests and showing on the serial monitor, but after the AT+HTTPREAD command I want to store data into a variable. How can I do this? I am getting a JSON Object from the web server and I want to get the Status property from that object and save it into a variable.
#include <SoftwareSerial.h>
SoftwareSerial gprsSerial(2,3);
void setup() {
gprsSerial.begin(9600);
Serial.begin(9600);
Serial.println("Con");
delay(2000);
Serial.println("Done!...");
gprsSerial.flush();
Serial.flush();
// See if the SIM900 is ready
gprsSerial.println("AT");
delay(1000);
toSerial();
// SIM card inserted and unlocked?
gprsSerial.println("AT+CPIN?");
delay(1000);
toSerial();
// Is the SIM card registered?
gprsSerial.println("AT+CREG?");
delay(1000);
toSerial();
// Is GPRS attached?
gprsSerial.println("AT+CGATT?");
delay(1000);
toSerial();
// Check signal strength
gprsSerial.println("AT+CSQ ");
delay(1000);
toSerial();
// Set connection type to GPRS
gprsSerial.println("AT+SAPBR=3,1,\"Contype\",\"GPRS\"");
delay(2000);
toSerial();
// Set the APN
gprsSerial.println("AT+SAPBR=3,1,\"APN\",\"wap.mobilinkworld.com\"");
delay(2000);
toSerial();
// Enable GPRS
gprsSerial.println("AT+SAPBR=1,1");
delay(10000);
toSerial();
// Check to see if connection is correct and get your IP address
gprsSerial.println("AT+SAPBR=2,1");
delay(2000);
toSerial();
}
void loop() {
// initialize http service
gprsSerial.println("AT+HTTPINIT");
delay(2000);
toSerial();
// set http param value
// ToDO : send dynamic value
gprsSerial.println("AT+HTTPPARA=\"URL\",\"http://smockfyp.azurewebsites.net/api/Device/GetStatus?did=1\"");
delay(4000);
toSerial();
// set http action type 0 = GET, 1 = POST, 2 = HEAD
gprsSerial.println("AT+HTTPACTION=0");
delay(6000);
toSerial();
// read server response
gprsSerial.println("AT+HTTPREAD");
delay(1000);
toSerial();
gprsSerial.println("AT+HTTPTERM");
toSerial();
delay(300);
gprsSerial.println("");
delay(10000);
}
void toSerial() {
while(gprsSerial.available()!=0) {
Serial.write(gprsSerial.read());
}
}
This is piece of output I want to store in a variable:
AT+HTTPINIT
OK
AT+HTTPPARA="URL","http://smockfyp.azurewebsites.net/api/DeviceAT+HTTPACTION=0
OK
+HTTPACTION: 0,200,17
AT+HTTPREAD
+HTTPREAD: 17
[{"Status":true}]
OK
Start by acquiring a large A3 sheet of paper, find a red pen and write 1000 times
I will never use delay as a substitute for reading and parsing responses from a modem.
I will never use delay as a substitute for reading and parsing responses from a modem.
I will never use delay as a substitute for reading and parsing responses from a modem.
I will never use delay as a substitute for reading and parsing responses from a modem.
I will never use delay as a substitute for reading and parsing responses from a modem.
...
Then read this answer, following the instructions regarding V.250. And when you have properly digested all information from the answer (it probably takes some time to let all sink in), then follow the link to another answer in the comment below it (which contains information to capture response content).
Of course the first part was meant to be funny, but I am dead serious about the rest; you have some huge AT command knowledge "holes" you must fill. You will not be able to get any information out until you do. It should not be very difficult, but it will require some effort.
First you should initialize a char array named a for storing the value and also declare a variable int flag=0;.
Then modify your toSerial() function as follows:
void toSerial() {
while(gprsSerial.available()!=0) {
if( gprsSerial.read() == '[' )
flag=2;
else if(flag == 2 && gprsSerial.read() == ':')
while(gprsSerial.read() != '}') {
a[i]= gprsSerial.read();
i++;
}
else if(flag == 0)
Serial.write(gprsSerial.read());
else
flag--;
}
}

LED on Arduino won't turn on / off based on condition

I have an Arduino UNO R3 that reads a specific value from my Web Page.
I have an LED attached to the PIN 13 & GND of my Arduino.
When the Arduino reads 1 from my Web Page, it should turn the LED ON. When it reads 0, it should turn it off.
Following is the code for that:
#include "SIM900.h"
#include <SoftwareSerial.h>
#include "inetGSM.h"
InetGSM inet;
#define ledPin 13
char msg[165];
char store[2];
char a;
char b;
char* disp;
boolean started=false;
void setup()
{
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
//Serial connection.
Serial.begin(9600);
Serial.println("GSM Shield testing.");
//Start configuration of shield with baudrate.
//For http uses is raccomanded to use 4800 or slower.
if (gsm.begin(2400)) {
Serial.println("\nstatus=READY");
started=true;
} else Serial.println("\nstatus=IDLE");
if(started)
{
//GPRS attach, put in order APN, username and password.
//If no needed auth let them blank.
if (inet.attachGPRS("TATA.DOCOMO.INTERNET", "", ""))
Serial.println("status=ATTACHED");
else Serial.println("status=ERROR");
delay(1000);
//TCP Client GET, send a GET request to the server and
//save the reply.
//Print the results.
}
}
void loop()
{
inet.httpGET("www.boat.esy.es", 80, "/retrieve.php", msg, 165);
disp = strstr(msg,"\r\n\r\n");
disp = disp+4;
a = disp[0];
b = disp[1];
Serial.println(b);
if(b=='1')
{
digitalWrite(ledPin, HIGH);
}
if(b=='0');
{
digitalWrite(ledPin, LOW);
}
}
Problem here is, when I disable the digitalWrite(ledPin,LOW), that is when I comment it out, the LED turns on & stays that way.
But the moment I enable it & load the code on my Arduino, it won't even turn on.
I'm wondering if it's a logical error or something else. Because the turning on & off of the LED depends completely on the conditions being satisfied. And for now, my Web Page returns only 1, hence the LED should stay on. But when I include both digitalWrite(ledPin, HIGH) and digitalWrite(ledPin, LOW) in the same code and run it, it doesn't work. I can see the Serial printing out the messages associated with the LED ON, but I don't see the LED turning ON.
Thank You for your time!!
First of all you have a semicolon that I think should not be in your second if-statement?
if(b=='0'); <--
{
digitalWrite(ledPin, LOW);
}
Start by trying to remove that and see if there is a difference.

How to read an SMS from Arduino and get LED to switch on or off

#include <SoftwareSerial.h>
char inchar; //Will hold the incoming character from the serial port.
SoftwareSerial cell(2,3); //Create a 'fake' serial port. Pin 2 is the Rx pin, pin 3 is the Tx pin.
int led1 = A2;
void setup()
{
// Prepare the digital output pins
pinMode(led1, OUTPUT);
digitalWrite(led1, HIGH);
//Initialize GSM module serial port for communication.
cell.begin(19200);
delay(30000); // Give time for GSM module to register on network, etc.
cell.println("AT+CMGF=1"); // Set SMS mode to text
delay(200);
cell.println("AT+CNMI=3,3,0,0"); // Set module to send SMS data to serial out upon receipt
delay(200);
}
void loop()
{
//If a character comes in from the cellular module...
if(cell.available() >0)
{
delay(10);
inchar=cell.read();
if (inchar=='a')
{
delay(10);
inchar=cell.read();
if (inchar=='0')
{
digitalWrite(led1, LOW);
}
else if (inchar=='1')
{
digitalWrite(led1, HIGH);
}
delay(10);
delay(10);
}
cell.println("AT+CMGD=1,4"); // Delete all SMS
}
}
This is the code for receiving SMSes from the cellular network. I am using the Arduino Gboard with SIM900. There is no error in the code, but the LED on the board doesn't switch on or off in response to an SMS.
Why?
Here's a fully functional code for sending a command thru SMS using Arduino and GSM, it will also reply the state of the light.
#include <SoftwareSerial.h>
SoftwareSerial GPRS(10, 11);
String textMessage;
String lampState;
const int relay = 12; //If you're using a relay to switch, if not reverse all HIGH and LOW on the code
void setup() {
pinMode(relay, OUTPUT);
digitalWrite(relay, HIGH); // The current state of the light is ON
Serial.begin(9600);
GPRS.begin(9600);
delay(5000);
Serial.print("GPRS ready...\r\n");
GPRS.print("AT+CMGF=1\r\n");
delay(1000);
GPRS.print("AT+CNMI=2,2,0,0,0\r\n");
delay(1000);
}
void loop(){
if(GPRS.available()>0){
textMessage = GPRS.readString();
Serial.print(textMessage);
delay(10);
}
if(textMessage.indexOf("ON")>=0){ //If you sent "ON" the lights will turn on
// Turn on relay and save current state
digitalWrite(relay, HIGH);
lampState = "ON";
Serial.println("Lamp set to ON\r\n");
textMessage = "";
GPRS.println("AT+CMGS=\"+631234567890\""); // RECEIVER: change the phone number here with international code
delay(500);
GPRS.print("Lamp was finally switched ON.\r");
GPRS.write( 0x1a );
delay(1000);
}
if(textMessage.indexOf("OFF")>=0){
// Turn off relay and save current state
digitalWrite(relay, LOW);
lampState = "OFF";
Serial.println("Lamp set to OFF\r\n");
textMessage = "";
GPRS.println("AT+CMGS=\"+631234567890\""); /// RECEIVER: change the phone number here with international code
delay(500);
GPRS.print("Lamp was finally switched OFF.\r");
GPRS.write( 0x1a );
delay(1000);
}
if(textMessage.indexOf("STATUS")>=0){
String message = "Lamp is " + lampState;
GPRS.print("AT+CMGF=1");
delay(1000);
Serial.println("Lamp state resquest");
textMessage = "";
GPRS.println("AT+CMGS=\"+631234567890\""); // RECEIVER: change the phone number here with international code
delay(500);
GPRS.print("Lamp is currently ");
GPRS.println(lampState ? "ON" : "OFF"); // This is to show if the light is currently switched on or off
GPRS.write( 0x1a );
delay(1000);
}
}
Change
AT+CNMI=3,3,0,0
to:
AT+CNMI=2,2,0,0,0
The simplest way is the best way.
// if You use SoftwareSerial lib, declare object for GSM
SoftwareSerial gsm(8,9); // TX, RX
void setup(){
// initialise UART and GSM communication between Arduino and modem
Serial.begin(115200);
gsm.begin(115200);
// wait 5-10sec. for modem whitch must connect to the network
delay(5000);
// configure modem - remember! modem didn't remeber Your's configuration!
gsm.print("at+cmgf=1\r"); // use full functionality (calls, sms, gprs) - see app note
gsm.print("at+clip=1\r"); // enable presentation number
gsm.print("at+cscs=\"GSM\"\r"); // configure sms as standard text messages
gsm.print("at+cnmi=1,2,0,0,0\r"); // show received sms and store in sim (probobly, I don't compre this settings with app note but it's working :)
}
void loop(){
String response = gsmAnswer();
if(response.indexOf("+CMT:") > 0 ) { // SMS arrived
// Now You can parse Your Message, if You wont controll only LED, just write
if(response.indexOf("LED ON") > 0) {
digitalWrite(LED_PIN, HIGH); // enable it
}else if(response.indexOf("LED OFF") > 0) {
digitalWrite(LED_PIN, LOW); // turn off
}
delay(1000);
}
}
String gsmAnswer(){
String answer;
while(!gsm.available());
while(gsm.available()){
delay(5);
if(Serial.available() > 0){
char s = (char)gsm.read();
answer += s;
}
}
return answer;
}
One think more, incomming sms has the following format:
+CMT: "+48xxxxxxxxx","","17/07/07,21:57:04+08"
Test of arrived messages
You should first know exactly what the response is before attempting to parse it.
Try something simple like the following code (note: untested!) to get a feeling of what you should look for:
void loop() {
if(cell.available() > 0) {
char ch = cell.read();
Serial.print(ch);
}
}
My guess is you'll see more than just a '0' or a '1' :)
void loop() {
while(cell.available() > 0) {inchar = cell.read(); readString+=c;delay(1);} ///can be a delay up to (10) so you can get a clear reading
Serial.print(readString); /// Declare a string " String readString; "
for (i=0; i<200; i++){ /// Serch for the txt you sent up to (200) times it depends how long your ""readString" is
if(readString.substring(i,i+4)=="RING"){ //// I am looking for the word RING sent from my phone
digitalWrite(13,HIGH);
break;
}
}
}
this will help you find the specific word ir your reading (text message)

Resources