连续发送GPS坐标

时间:2016-09-12 15:15:40

标签: arduino gps gsm

我正试图通过GSM接收我号码的GPS坐标。我的代码只是将它们发送给我一次,即使我把它放在循环中但是我希望在触发电路之后通过仅发送一次字符(e-g:'#')来连续接收它们。请让我知道错误。

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

1 个答案:

答案 0 :(得分:0)

当你发送#&#39;#&#39;字符后面可能跟一个换行符&#39; \ n&#39;,它在inchar变量中替换它。更好的方法是设置一个标志,指示您的代码发送数据:

bool sendData = false;
// setup etc.
void loop()
{

  if(Serial1.available())
  {
    inchar = Serial1.read();
    Serial.println(inchar);
    if(inchar == '#') sendData = true;
  }
  if(sendData)
  {
      getData();  
  }

}

顺便说一句:你不需要while(true)功能中的loop()。顾名思义,它已经永远循环。