forked from JayaSurya-27/GSM_Module
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgps_thinkspeak_1.txt
91 lines (74 loc) · 2.21 KB
/
gps_thinkspeak_1.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
#include <AltSoftSerial.h>
#define SIM_RX_PIN 17
#define SIM_TX_PIN 16
#define GPS_RX_PIN 8
#define GPS_TX_PIN 9
SoftwareSerial simSerial(SIM_RX_PIN, SIM_TX_PIN);
AltSoftSerial gpsSerial(GPS_RX_PIN, GPS_TX_PIN);
TinyGPSPlus gps;
unsigned long previousMillis = 0;
long interval = 60000;
const char* apiKey = "FZ4KI6X4RE9P41QN"; // ThingSpeak API Key
void setup() {
Serial.begin(115200);
simSerial.begin(115200);
gpsSerial.begin(9600);
delay(1000);
Serial.println("Initializing...");
sendATcommand("AT", "OK", 2000);
}
void loop() {
while (simSerial.available()) {
Serial.println(simSerial.readString());
}
while (Serial.available()) {
simSerial.println(Serial.readString());
}
unsigned long currentMillis = millis();
if (currentMillis - previousMillis > interval) {
previousMillis = currentMillis;
sendGpsToThingSpeak();
}
}
void sendGpsToThingSpeak() {
while (gpsSerial.available() > 0) {
if (gps.encode(gpsSerial.read())) {
float latitude = gps.location.lat();
float longitude = gps.location.lng();
Serial.print("Latitude: ");
Serial.println(latitude, 6);
Serial.print("Longitude: ");
Serial.println(longitude, 6);
String url = "GET https://api.thingspeak.com/update?api_key=";
url += apiKey;
url += "&field1=";
url += String(latitude, 6);
url += "&field2=";
url += String(longitude, 6);
sendATcommand("AT+HTTPINIT", "OK", 2000);
sendATcommand("AT+HTTPPARA=\"URL\",\"" + url + "\"", "OK", 1000);
sendATcommand("AT+HTTPACTION=0", "200", 10000);
sendATcommand("AT+HTTPREAD", "+HTTPREAD:", 10000);
sendATcommand("AT+HTTPTERM", "OK", 2000);
Serial.println("Data sent to ThingSpeak.");
}
}
}
int8_t sendATcommand(String ATcommand, String expected_answer, unsigned int timeout) {
String response = "";
simSerial.println(ATcommand);
unsigned long previous = millis();
while (millis() - previous < timeout) {
if (simSerial.available() > 0) {
char c = simSerial.read();
response += c;
if (response.indexOf(expected_answer) != -1) {
return 1;
}
}
}
Serial.println(response);
return 0;
}