Sending GPS coordinates continuously - arduino

I am trying to receive GPS coordinates on my number via GSM. My code sends them to me just once even though I have put it in loop but I want to receive them continuously after triggering my circuit by sending a character (e-g: '#') once only. Please let me know what's wrong.
#include <TinyGPS.h>
// create variable for latitude and longitude object
long lat,lon;
// create gps object
TinyGPS gps;
//for storing incoming character from sms
char inchar;
void setup()
{
Serial.begin(9600); // connect mega
Serial1.begin(9600); // connect GSM
Serial2.begin(9600); // connect gps
delay(1000);
Serial1.print("AT+CMGF=1\r"); //reads string instead of hexadecimal from incoming sms
Serial1.print("AT+CNMI=1,2,0,0,0"); //select storage to read sms from
Serial.println("Ready...");
delay(1000);
}
void loop()
{
while(true)
{
if(Serial1.available())
{
inchar = Serial1.read();
Serial.println(inchar);
}
if(inchar == '#')
{
getData();
}
}
}//finish loop
void getData()
{
while(true)
{
if(Serial2.available()>0) // check for gps data
{
if(gps.encode(Serial2.read())) // encode gps data
break;
}
}
gps.get_position(&lat,&lon); // get latitude and longitude
displayInfo();
sendInfo();
Serial.println("In getdata");
}
void displayInfo()
{
Serial.print("Position: ");
Serial.print("lat: "); Serial.print(lat); Serial.print(" ");// print latitude
Serial.print("lon: "); Serial.println(lon); // print longitude
} //end displayInfo()
void sendInfo()
{
Serial1.print("AA");
delay(1000); //delay of 1
Serial1.println("AT");
delay(1000);
Serial1.write("AT+CMGF=1\r\n"); //set GSM to text mode
delay(1500);
Serial1.write("AT+CPMS=\"SM\"\r\n"); //Preferred SMS Message Storage
delay(1000);
Serial1.write("AT+CMGS=\"03360234233\"\r"); //set GSM to text mode
delay(1500);
Serial1.print(lat); Serial1.print(" "); Serial1.print(lon);//set GSM to text mode
delay(1500);
Serial1.write(0x1A); // sends ctrl+z end of message
delay(1500);
Serial.println("sms sent ");
} //end sendInfo()

When you send '#' character it is probably followed by a newline character '\n', which replaces it in the inchar variable. Better approach would be to set a flag that will signal your code to send data:
bool sendData = false;
// setup etc.
void loop()
{
if(Serial1.available())
{
inchar = Serial1.read();
Serial.println(inchar);
if(inchar == '#') sendData = true;
}
if(sendData)
{
getData();
}
}
BTW: you don't need while(true) inside the loop() function. As the name suggests, it's already looping forever.

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.

Why does my sensor return 0 when using ESP-NOW Two-Way Communication?

I have connected an ESP32 LoRa to a moisture sensor. I have a script for reading data from the sensor, which works perfectly fine on its own:
#define SensorPin 27
float sensorValue = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println(analogRead(SensorPin));
delay(1000);
}
It returns about 1800-2000 when it is in some dirt.
I then want to send the data to another ESP32 LoRa, where i have used this tutorial: https://randomnerdtutorials.com/esp-now-two-way-communication-esp32/
It works fine in terms of sending data between the ESPs, but now my sensor constantly returns 0, which is super weird.
#include <esp_now.h>
#include <WiFi.h>
#include <Wire.h>
#define SensorPin 27
float sensorValue = 0;
// REPLACE WITH THE MAC Address of your receiver
uint8_t broadcastAddress[] = {0xA8, 0x03, 0x2A, 0xF3, 0x27, 0x88};
// Define variables to store BME280 readings to be sent
float temperature;
// Define variables to store incoming readings
float incomingTemp;
// Variable to store if sending data was successful
String success;
//Structure example to send data
//Must match the receiver structure
typedef struct struct_message {
float temp;
} struct_message;
// Create a struct_message called BME280Readings to hold sensor readings
struct_message BME280Readings;
// Create a struct_message to hold incoming sensor readings
struct_message incomingReadings;
esp_now_peer_info_t peerInfo;
// Callback when data is sent
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
Serial.print("\r\nLast Packet Send Status:\t");
Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
if (status ==0){
success = "Delivery Success :)";
}
else{
success = "Delivery Fail :(";
}
}
// Callback when data is received
void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) {
memcpy(&incomingReadings, incomingData, sizeof(incomingReadings));
Serial.print("Bytes received: ");
Serial.println(len);
incomingTemp = incomingReadings.temp;
}
void setup() {
// Init Serial Monitor
Serial.begin(115200);
// Set device as a Wi-Fi Station
WiFi.mode(WIFI_STA);
// Init ESP-NOW
if (esp_now_init() != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
return;
}
// Once ESPNow is successfully Init, we will register for Send CB to
// get the status of Trasnmitted packet
esp_now_register_send_cb(OnDataSent);
// Register peer
memcpy(peerInfo.peer_addr, broadcastAddress, 6);
peerInfo.channel = 0;
peerInfo.encrypt = false;
// Add peer
if (esp_now_add_peer(&peerInfo) != ESP_OK){
Serial.println("Failed to add peer");
return;
}
// Register for a callback function that will be called when data is received
esp_now_register_recv_cb(OnDataRecv);
}
void loop() {
Serial.println("Sensor readings:");
getReadings();
// Set values to send
BME280Readings.temp = analogRead(SensorPin); // This returned 1800-2000 before, now it returns 0
// Send message via ESP-NOW
esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &BME280Readings, sizeof(BME280Readings));
if (result == ESP_OK) {
Serial.println("Sent with success");
}
else {
Serial.println("Error sending the data");
}
//updateDisplay();
delay(5000);
}
void getReadings(){
temperature = analogRead(SensorPin);
}
void updateDisplay(){ // currently not using this method because I do not care about getting data from the other ESP right now.
// Display Readings in Serial Monitor
Serial.println("INCOMING READINGS");
Serial.print("Temperature: ");
Serial.print(incomingReadings.temp);
Serial.println(" ÂșC");
}
When using WiFi - you can't use the ADC2 pins for analog input. I've seen the same issue. Here's a link showing a discussion on the ESP32 github pages.
Switch your sensor to one of the ADC1 pins and it should work.

automating sending sms with arduino?

So, im using the example that comes with the arduino software, but with this example, i have to manually input the phone number that i want to send to everytime.
I've tried to put the phone number as an int = "mynumber" and replaced remoteNum, but i doesnt seem to work..
what else can I try?
#include <GSM.h>
#define PINNUMBER ""
// initialize the library instance
GSM gsmAccess;
GSM_SMS sms;
void setup() {
// initialize serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.println("SMS Messages Sender");
// connection state
boolean notConnected = true;
// Start GSM shield
// If your SIM has PIN, pass it as a parameter of begin() in quotes
while (notConnected) {
if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
notConnected = false;
} else {
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("GSM initialized");
}
void loop() {
Serial.print("Enter a mobile number: ");
char remoteNum[20]; // telephone number to send sms
readSerial(remoteNum);
Serial.println(remoteNum);
// sms text
Serial.print("Now, enter SMS content: ");
char txtMsg[200];
readSerial(txtMsg);
Serial.println("SENDING");
Serial.println();
Serial.println("Message:");
Serial.println(txtMsg);
// send the message
sms.beginSMS(remoteNum);
sms.print(txtMsg);
sms.endSMS();
Serial.println("\nCOMPLETE!\n");
}
/*
Read input serial
*/
int readSerial(char result[]) {
int i = 0;
while (1) {
while (Serial.available() > 0) {
char inChar = Serial.read();
if (inChar == '\n') {
result[i] = '\0';
Serial.flush();
return 0;
}
if (inChar != '\r') {
result[i] = inChar;
i++;
}
}
}
}
How can I write the phone number into the code, so that I dont have to input in manually everytime?
Your code reads the information from Serial and stores it as a character string an a char array:
Serial.print("Enter a mobile number: ");
char remoteNum[20]; // telephone number to send sms
readSerial(remoteNum);
Serial.println(remoteNum);
All you need to do is put the number in a character string in the code instead of getting it from serial:
Serial.print("Enter a mobile number: ");
char remoteNum[20] = "15558675309"; // telephone number to send sms
Serial.println(remoteNum);
I don't know for sure that is how your phone number should be formatted, but you can look at what it has been printing out to see if it should have any dashes or anything in it.

receiving and sending sms from arduino

Here is my code for sending message from arduino and receiving to it. I have tried to run both codes separately and they work fine (I mean arduino can separately receive and send) but when I have merged both codes arduino only seems to receive the message but does not send it.
Please let me know where I am making a mistake.
#include <TinyGPS.h>
#include <GSM.h>
long lat,lon;// create variable for latitude and longitude object
TinyGPS gps; // create gps object
GSM_SMS sms;
char inchar;
void setup()
{
Serial.begin(9600); // connect serial
Serial1.begin(9600); // GSM connect
Serial2.begin(9600); // connect gps sensor
Serial.println("AT+CMGF=1");
Serial.println("AT+CNMI=2,2,0,0,0");
}
void loop()
{
char one = receiveInfo();
if(one=='1')
{
Serial.println("SMS received");
Serial.println(one);
//code works fine upto here and doesn't enter the loop below
while(Serial2.available()>0) // check for gps data
{
if(gps.encode(Serial2.read())) // encode gps data
{
gps.get_position(&lat,&lon); // get latitude and longitude
displayInfo();
sendInfo();
delay(1000);
}
}
}
} //end loop
void displayInfo()
{
Serial.print("Position: ");
Serial.print("lat: "); Serial.print(lat); Serial.print(" ");// print latitude
Serial.print("lon: "); Serial.println(lon); // print longitude
} //end displayInfo()
void sendInfo()
{
Serial1.print("AA");
delay(1000); //delay of 1
Serial1.println("AT");
delay(1000);
Serial1.write("AT+CMGF=1\r\n"); //set GSM to text mode
delay(1500);
Serial1.write("AT+CPMS=\"SM\"\r\n"); //Preferred SMS Message Storage
delay(1000);
Serial1.write("AT+CMGS=\"03360234233\"\r"); //set GSM to text mode
delay(1500);
Serial1.print(lat); Serial1.print(" "); Serial1.print(lon);//set GSM to text mode
delay(1500);
Serial1.write(0x1A); // sends ctrl+z end of message
delay(1500);
Serial.println("sms sent ");
} //end sendInfo()
char receiveInfo()
{
if(Serial1.available()>0)
{
inchar=Serial1.read();
}
return inchar;
}

Unable to send sms Arduino GSM Shield 2

I can't connect and I don't know why, can somebody help me?
The console returns:
"/tmp/arduino_ca13faa5535f759e3ad5c18bb4094ecd/SendSMS.ino: In function 'void setup()':
/tmp/arduino_ca13faa5535f759e3ad5c18bb4094ecd/SendSMS.ino:48:34: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
if (gsmAccess.begin(PINNUMBER) == GSM_READY) { "
#include <GSM.h>
#define PINNUMBER ""
// initialize the library instance
GSM gsmAccess;
GSM_SMS sms;
void setup() {
// initialize serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
;// wait for serial port to connect. Needed for native USB port only
}
Serial.println("SMS Messages Sender");
// connection state
boolean notConnected = true;
// Start GSM shield
// If your SIM has PIN, pass it as a parameter of begin() in quotes
while (notConnected) {
if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
notConnected = false;
} else {
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("GSM initialized");
}
void loop() {
Serial.print("Enter a mobile number: ");
char remoteNum[20]; // telephone number to send sms
readSerial(remoteNum);
Serial.println(remoteNum);
// sms text
Serial.print("Now, enter SMS content: ");
char txtMsg[200];
readSerial(txtMsg);
Serial.println("SENDING");
Serial.println();
Serial.println("Message:");
Serial.println(txtMsg);
// send the message
sms.beginSMS(remoteNum);
sms.print(txtMsg);
sms.endSMS();
Serial.println("\nCOMPLETE!\n");
}
/*
Read input serial
*/
int readSerial(char result[]) {
int i = 0;
while (1) {
while (Serial.available() > 0) {
char inChar = Serial.read();
if (inChar == '\n') {
result[i] = '\0';
Serial.flush();
return 0;
}
if (inChar != '\r') {
result[i] = inChar;
i++;
}
}
}
}
That's just a warning. The sketch is building fine. What do you see on the Serial Monitor window? (drag-select, copy and paste into a comment below.)
You haven't set the PIN to anything, like "1234". Do you have a PIN?

Resources