Search code examples
arduinogpsgsm

Sending GPS coordinates continuously


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()

Solution

  • 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.