Code error in smart irrigation system, using dht11 sensor - arduino

I have wrtitten a code for automatically watering plant using esp8266, dht11, moisture sensor but my code has some error, i dont know how to fix it
#include <DHT.h>
#include <ESP8266WiFi.h>
String apiKey = "X5AQ3EGIKMBYW31H"; // Enter your Write API key here
const char* server = "api.thingspeak.com";
const char *ssid = "CircuitLoop"; // Enter your WiFi Name
const char *pass = "circuitdigest101"; // Enter your WiFi Password
#define DHTPIN D3 // GPIO Pin where the dht11 is connected
DHT dht(DHTPIN, DHT11);
WiFiClient client;
const int moisturePin = A0; // moisteure sensor pin
const int motorPin = D0;
unsigned long interval = 10000;
unsigned long previousMillis = 0;
unsigned long interval1 = 1000;
unsigned long previousMillis1 = 0;
float moisturePercentage; //moisture reading
float h; // humidity reading
float t; //temperature reading
void setup()
{
Serial.begin(115200);
delay(10);
pinMode(motorPin, OUTPUT);
digitalWrite(motorPin, LOW); // keep motor off initally
dht.begin();
Serial.println("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print("."); // print ... till not connected
}
Serial.println("");
Serial.println("WiFi connected");
}
void loop()
{
unsigned long currentMillis = millis(); // grab current time
h = dht.readHumidity(); // read humiduty
t = dht.readTemperature(); // read temperature
if (isnan(h) || isnan(t))
{
Serial.println("Failed to read from DHT sensor!");
return;
}
moisturePercentage = ( 100.00 - ( (analogRead(moisturePin) / 1023.00) * 100.00 ) );
if ((unsigned long)(currentMillis - previousMillis1) >= interval1) {
Serial.print("Soil Moisture is = ");
Serial.print(moisturePercentage);
Serial.println("%");
previousMillis1 = millis();
}
if (moisturePercentage < 50) {
digitalWrite(motorPin, HIGH); // tun on motor
}
if (moisturePercentage > 50 && moisturePercentage < 55) {
digitalWrite(motorPin, HIGH); //turn on motor pump
}
if (moisturePercentage > 56) {
digitalWrite(motorPin, LOW); // turn off mottor
}
if ((unsigned long)(currentMillis - previousMillis) >= interval) {
sendThingspeak(); //send data to thing speak
previousMillis = millis();
client.stop();
}
}
void sendThingspeak() {
if (client.connect(server, 80))
{
String postStr = apiKey; // add api key in the postStr string
postStr += "&field1=";
postStr += String(moisturePercentage); // add mositure readin
postStr += "&field2=";
postStr += String(t); // add tempr readin
postStr += "&field3=";
postStr += String(h); // add humidity readin
postStr += "\r\n\r\n";
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(postStr.length()); //send lenght of the string
client.print("\n\n");
client.print(postStr); // send complete string
Serial.print("Moisture Percentage: ");
Serial.print(moisturePercentage);
Serial.print("%. Temperature: ");
Serial.print(t);
Serial.print(" C, Humidity: ");
Serial.print(h);
Serial.println("%. Sent to Thingspeak.");
}
}
This is the error which i get
Arduino: 1.8.9 (Windows 8.1), Board: "Generic ESP8266 Module, 80 MHz, Flash, Disabled, All SSL ciphers (most compatible), ck, 26 MHz, 40MHz, DOUT (compatible), 512K (no SPIFFS), 2, nonos-sdk 2.2.1 (legacy), v2 Lower Memory, Disabled, None, Only Sketch, 115200"
sketch_oct03a:7:16: error: 'D3' was not declared in this scope
#define DHTPIN D3 // GPIO Pin where the dht11 is connected
^
C:\Users\Shweta\Desktop\Libraries\sketch_oct03a\sketch_oct03a.ino:8:9: note: in expansion of macro 'DHTPIN'
DHT dht(DHTPIN, DHT11);
^
sketch_oct03a:12:22: error: 'D0' was not declared in this scope
const int motorPin = D0;
^
exit status 1
'D3' was not declared in this scope
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Digital pins are not prefixed with D, unlike their analog counterparts.
#define DHTPIN 3
const int motorPin = 0;

Related

ESP12F, cant get a relay to work with data from dht11

i've been trying to build a system that detects in one room of the house the temperature using an esp8266 and a dht11 sensor, this esp sends the data to a webserver while the ESP12F grabs this data and should turn the relay on when a certain value is reached, however i can't get the relay to work, as soon as i upload the code, the led on the module turns but not at its full power, i tried with another code to see if it was just a faulty relay, but it works perfectly with the same connections. The code from the client side of the system is below:
#include "ESP8266WiFi.h"
#include "ESP8266HTTPClient.h"
#include "WiFiClient.h"
#include "ESP8266WiFiMulti.h"
ESP8266WiFiMulti WiFiMulti;
const char* ssid = "*******";
const char* password = "********";
//Your IP address or domain name with URL path
const char* serverNameTemp = "http://192.168.1.188/temperature";
const char* serverNameHumi = "http://192.168.1.188/humidity";
const char* serverNamePres = "http://192.168.1.188/pressure";
#include "Wire.h"
#include "Adafruit_GFX.h"
#include "Adafruit_SSD1306.h"
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
String temperature;
String humidity;
String pressure;
const int relay = 5;
float temp_int = temperature.toFloat();
unsigned long previousMillis = 0;
const long interval = 2000;
void setup() {
Serial.begin(115200);
Serial.println();
pinMode(relay,OUTPUT);
digitalWrite(relay,LOW);
// Address 0x3C for 128x64, you might need to change this value (use an I2C scanner)
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
display.clearDisplay();
display.setTextColor(WHITE);
int int_temp = temperature.toFloat();
WiFi.mode(WIFI_STA);
WiFiMulti.addAP(ssid, password);
while((WiFiMulti.run() == WL_CONNECTED)) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected to WiFi");
}
void loop() {
unsigned long currentMillis = millis();
if(currentMillis - previousMillis >= interval) {
// Check WiFi connection status
if ((WiFiMulti.run() == WL_CONNECTED)) {
int int_temp = temperature.toFloat();
temperature = httpGETRequest(serverNameTemp);
humidity = httpGETRequest(serverNameHumi);
pressure = httpGETRequest(serverNamePres);
if(int_temp < 26){
digitalWrite(relay,LOW);
}
else if (int_temp > 26){
digitalWrite(relay,HIGH);
}
Serial.println("Temperature: " + temperature + " *C - Humidity: " + humidity + " % - Pressure: " + pressure + " hPa");
Serial.println(int_temp);
Serial.println(temperature.toFloat());
display.clearDisplay();
// display temperature
display.setTextSize(2);
display.setCursor(0,0);
display.print("T: ");
display.print(temperature);
display.print(" ");
display.setTextSize(1);
display.cp437(true);
display.write(248);
display.setTextSize(2);
display.print("C");
// display humidity
display.setTextSize(2);
display.setCursor(0, 25);
display.print("H: ");
display.print(humidity);
display.print(" %");
// display pressure
display.setTextSize(2);
display.setCursor(0, 50);
display.print("P:");
display.print(pressure);
display.setTextSize(1);
display.setCursor(110, 56);
display.print("hPa");
display.display();
// save the last HTTP GET Request
previousMillis = currentMillis;
}
else {
Serial.println("WiFi Disconnected");
}
}
}
String httpGETRequest(const char* serverName) {
WiFiClient client;
HTTPClient http;
// Your IP address with path or Domain name with URL path
http.begin(client, serverName);
// Send HTTP POST request
int httpResponseCode = http.GET();
String payload = "--";
if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
payload = http.getString();
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
return payload;
}

Arduino MQTT disconnect

I have a ESP32 board with 2 relays and a DHT22 sensor and the bellow code in Arduino running on the ESP32
MQTT Broker is running on Pi4 with mosquitto and node-red dashboard.
#include <WiFi.h>
#include <PubSubClient.h>
#include "DHT.h"
#define DHTTYPE DHT22
const char* ssid = "MY SSID";
const char* password = "1234";
const char* mqtt_server = "192.168.1.118";
WiFiClient espClient;
PubSubClient client(espClient);
const int DHTPin = 14;
const int lamp = 25;
const int lamp1 = 26;
DHT dht(DHTPin, DHTTYPE);
long now = millis();
long lastMeasure = 0;
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
delay(1000);
WiFi.disconnect();
delay(1000);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.print("WiFi connected - ESP IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
String message;
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
char c = (char)payload[i];
message += c;
}
Serial.println();
if ((char)payload[0] == '0' || message == "false") {
digitalWrite(lamp, HIGH);
delay(100);
digitalWrite(lamp1, LOW);
Serial.println("lamp, HIGH si lamp1, LOW");
} else if ((char)payload[0] == '1' || message == "true") {
digitalWrite(lamp1, HIGH);
delay(100);
digitalWrite(lamp, LOW);
Serial.println("lamp, LOW si lamp1, HIGH");
} else if ((char)payload[0] == '2') {
digitalWrite(lamp, HIGH);
digitalWrite(lamp1, HIGH);
Serial.println("lamp, LOW si lamp1, LOW > STOP");
}
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("ESP8266Client")) {
Serial.println("connected");
// Subscribe or resubscribe to a topic
// You can subscribe to more topics (to control more LEDs in this example)
client.subscribe("room/lamp");
client.subscribe("room/lamp1");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
pinMode(lamp, OUTPUT);
pinMode(lamp1, OUTPUT);
pinMode(LED,OUTPUT);
dht.begin();
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
// For this project, you don't need to change anything in the loop function. Basically it ensures that you ESP is connected to your broker
void loop() {
if (!client.connected()) {
reconnect();
}
if(!client.loop())
client.connect("ESP8266Client");
now = millis();
// Publishes new temperature and humidity every 30 seconds
if (now - lastMeasure > 5000) {
lastMeasure = now;
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
// float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
//if (isnan(h) || isnan(t) || isnan(f))
if (isnan(h) || isnan(t)){
Serial.println("Failed to read from DHT sensor!");
return;
}
// Computes temperature values in Celsius
float hic = dht.computeHeatIndex(t, h, false);
static char temperatureTemp[7];
dtostrf(t, 6, 2, temperatureTemp);
static char test[7];
dtostrf(hic, 6, 2, test);
static char humidityTemp[7];
dtostrf(h, 6, 2, humidityTemp);
client.publish("room/temperature", temperatureTemp);
client.publish("room/humidity", humidityTemp);
client.publish("room/test", test);
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t Temperature: ");
Serial.print(t);
Serial.print(" *C ");
//Serial.print(f);
Serial.print(" *F\t Heat index: ");
Serial.print(hic);
Serial.println(" *C ");
delay(500);
digitalWrite(LED,HIGH);
delay(500);
digitalWrite(LED,LOW);
}
}
The 2 relays are controlling a window in my bathroom. If I plug the ESP32 to power all is working, and I can open/close the window and sensor readings are ok.
But after ~24hours I can still see realtime sensor readings but when I try to open/close the window nothing is happening. On the MQTT broker I can see the mqtt messages but nothing is happening.
room/lamp1 1
room/lamp1 1
room/lamp 0
room/lamp 0
room/lamp 0
room/lamp 0
room/lamp 0
room/lamp 0
room/temperature 24.00
room/humidity 29.10
room/test 23.22
room/lamp 0
room/lamp 0
room/lamp 2
room/lamp1 2
room/lamp 2
room/lamp1 2
room/lamp 2
room/lamp1 2
room/lamp 2
Any suggestions.

ESP32 Radio - How to improve the sound quality?

I got this ESP32 Radio source code from this site.
I love it because its very simple radio and works fine on ESP32.
But sometime the sound is very choppy.
I suspect maybe because a lack of proper buffers, but I don't know how to fix it.
The code:
/*
WITHOUT OLED, only ESP32 & VS1053
VS1053 - connections detail
XRST = EN (D3)
MISO = D19
MOSI = D23
SCLK = D18
VCC = 5V / 3.3 V
Gnd = Gnd
*/
#include <VS1053.h> //ESP_VS1053_Library
#include <Preferences.h> //For reading and writing into the ROM memory
Preferences preferences;
unsigned int counter,old_counter,new_counter;
#include "helloMp3.h"
#include <WiFi.h>
#include <HTTPClient.h>
#include <esp_wifi.h>
char ssid[] = "SSID"; // your network SSID (name)
char pass[] = "PASSWORD"; // your network password
char *host[7] = {"184.95.47.178","us4.internet-radio.com","us3.internet-radio.com","us3.internet-radio.com","174.36.206.197","sj64.hnux.com","uk7.internet-radio.com"};
char *path[7] = {"/","/","/live.m3u","/","/","/","/"};
int port[7] = {9328,8266,8371,8297,8000,80,8226};
char *sname[7] = {"Love-Radio-USA","Smooth-Jazz-Florida","Best-Rock-Radio","Country-Radio","Venice-Classic-Radio","Smooth-Jazz-Global","UK-Top-40"};
int change=13;
bool x=true;
int status = WL_IDLE_STATUS;
WiFiClient client;
uint8_t mp3buff[32]; // vs1053 likes 32 bytes at a time
// Wiring of VS1053 board (SPI connected in a standard way)
#define VS1053_CS 32 //32
#define VS1053_DCS 33 //33
#define VS1053_DREQ 35 //15
#define VOLUME 100 // volume level 0-100
VS1053 player(VS1053_CS, VS1053_DCS, VS1053_DREQ);
void setup () {
pinMode(change,INPUT_PULLUP);
// initialize SPI
Serial.begin(115200);
delay(500);
// initialize SPI bus;
SPI.begin();
// initialize VS1053 player
player.begin();
// player.switchToMp3Mode(); // optional, some boards require this
player.setVolume(VOLUME);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
// display.drawString(0,15," Connecting..");
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");
Serial.print("IP address:");
Serial.println(WiFi.localIP());
preferences.begin("my-app", false);
counter = preferences.getUInt("counter", 0);
old_counter=counter;
Serial.printf("Current counter value1: %u\n", counter);
//if(counter>0) counter=0;
//Serial.printf("Current counter value2: %u\n", counter);
delay(100);
player.playChunk(hello2, sizeof(hello2)); //VS1053 is wake up & running
station_connect(counter);
}
void loop() {
if (client.available() > 0) {
uint8_t bytesread = client.read(mp3buff, 32);
player.playChunk(mp3buff, bytesread);
}
if(digitalRead(change)==0 and x==true){
x=false;
counter = counter+1;
if(counter>6) counter=0;
preferences.putUInt("counter",counter);
new_counter=counter;
Serial.printf("Old_Counter: %u\n",old_counter);
Serial.printf("New_Counter: %u\n",new_counter);
Serial.printf("Set counter to new_value: %u\n", counter);
delay(500);
if(old_counter != new_counter) {
player.softReset();
x=true;
station_connect(new_counter);
preferences.putUInt("counter",new_counter);
}
}
}
void station_connect (int station_no ) {
if (client.connect(host[station_no],port[station_no]) ) {
Serial.println("Connected now");
}
Serial.print(host[station_no]);
Serial.println(path[station_no]);
Serial.println(sname[station_no]);
client.print(String("GET ") + path[station_no] + " HTTP/1.1\r\n" +
"Host: " + host[station_no] + "\r\n" +
"Connection: close\r\n\r\n");
}
How to improve the sound quality? Please help
Thanks for all the helpers! :)

How to call more than one web service in Arduino/Galileo Gen 2

I'm working on Galileo gen 2;
And I'm trying to use the following two web services:
POST /dashboard/read_write_ard.php?temp="+tempValue
POST /dashboard/appinsert.php?valeur="+tempValue
The first one inserts into table one...
and the second one will be used only if (tempValue < 24).
This is my code so far:
#include <SPI.h>
#include <Ethernet.h>
#include <Wire.h>
#include "rgb_lcd.h"
rgb_lcd lcd;
const int pinLight = A1;
const int pinLed = 13;
const int thresholdvalue = 400;
const int idealLightValue = 400 ;
const int pinTemp = A0;
const int B = 3975;
int etat=0;
const int pinSound = A2;
byte mac[] = {
0x98, 0x4F, 0xEE, 0x05, 0x37, 0x33
};//adress mac du carte
EthernetClient client;
IPAddress server(192,168, 1,7);
void setup() {
Serial.begin(9600);
pinMode(pinLed, OUTPUT);
lcd.begin(16, 2);
delay(1000);
system("ifup eth0");
if (Ethernet.begin(mac) == 0) {
Serial.println("\nFailed to configure Ethernet using DHCP");
delay(500);
}
delay(1000);
Serial.println(Ethernet.localIP());
}
void loop() {
system("ifup eth0");
digitalWrite(pinLed, HIGH);
lcd.print("Starting to loop ");
delay(1000);
lcd.clear();
int TempSensorValue = analogRead(pinTemp);
int LightSensorValue = analogRead(pinLight);
int SoundSensorValue = analogRead(pinSound);
float resistance = (float)(1023-TempSensorValue)*10000/TempSensorValue;
int temperature = 1/(log(resistance/10000)/B+1/298.15)-273.15;
Serial.println( temperature);
Serial.println(SoundSensorValue);
Serial.println( LightSensorValue);
delay(1000);
String chEtat = "POST /dashboard/read_write_ard.php?temp=";
chEtat += temperature ;
chEtat += "&light=";
chEtat += LightSensorValue;
chEtat +="&sound=";
chEtat +=SoundSensorValue;
if (client.connect(server, 80) ) {
Serial.println("connected");
lcd.print("Connected ");
delay(500);
lcd.clear();
if (temperature <= 40 ){
String chEtat2 = "POST /dashboard/appinsert.php?valeur=";
chEtat2 += temperature ;
chEtat2 += "&type=temperature" ;
client.println(chEtat2);
client.println(chEtat);
}else{
client.println(chEtat);
client.println();
}
}
while (client.available()) {
char c = client.read();
Serial.print(c);
}
if(client.connected()) {
Serial.println();
Serial.println("disconnecting.");
lcd.print("Dissconnecting");
delay(1000);
lcd.clear();
client.stop();
for (;;);
}
}
I have a database containing 2 tables - one for alert values like temperature and the other for normal cases - so I want to put a code when my cart Galileo can add in table 1 : the normal one.
And in case of temperature, let's say more than 24, the value of that temperature will be added to the second table using the web service created for that.
I'd like to know how to get these data soon.

Sending GPS location via GSM module

I am using a SIM900A GSM module and a NEO-6m GPS module. I want to send the location via the GSM module when the GSM module receives a message.
My code is working when I am receiving and sending any message with the help of the GSM module, but it is not working when I join the two, i.e. GPS and GSM modules.
Here is my code for the two.
#include <SoftwareSerial.h>
// GPS
#include <TinyGPS.h>
// GSM
SoftwareSerial SIM900A(9, 10);
SoftwareSerial mySerial(5, 6);
TinyGPS gps;
void setup() {
Serial.begin(9600);
SIM900A.begin(9600);
SIM900A.println("AT+CNMI=2,2,0,0,0");
mySerial.begin(9600);
delay(1000);
}
void loop() {
bool newdata = false;
String buffer = readSIM900A();
if(SIM900A.available() > 0)
Serial.println(SIM900A.read());
if (buffer.startsWith("\r\n+CMT: ")) {
// printing the number
Serial.println(buffer.substring(9, 22));
// Remove first 51 characters
// buffer.remove(0, 51);
int len = buffer.length();
// printing message
Serial.println(buffer.substring(51, len-2));
if (buffer.substring(51, len-2) == "location") {
Serial.println("Sending location");
// GPS
if (mySerial.available()) {
char c = mySerial.read();
if (gps.encode(c)) {
newdata = true;
}
}
if (newdata) {
long int lat, lon;
unsigned long age, age1, date, time, chars;
gps.get_position(&lat, &lon, &age);
gps.get_datetime(&date, &time, &age);
Serial.print("Lat/Long(10^-5 deg): ");
Serial.print(lat);
Serial.print(", ");
Serial.print(lon);
Serial.print(" Fix age: ");
Serial.print(age); Serial.println("ms.");
Serial.print("Date(ddmmyy): "); Serial.print(date);
Serial.print(" Time(hhmmsscc): ");
Serial.print(time);
Serial.print(" Fix age: "); Serial.print(age);
Serial.println("ms.");
Serial.print("Alt(cm): "); Serial.print(gps.altitude());
Serial.print(" Speed(mps): "); Serial.print(gps.f_speed_mps());
// setting GSM module
SIM900A.println("AT+CMGF=1"); //Sets the GSM Module in Text Mode
delay(1000); // Delay of 1000 milli seconds or 1 second
// sending location from which code word had come
SIM900A.println("AT+CMGS=\"" + buffer.substring(9, 22) + "\"\r");
// Replace x with mobile number
Serial.println("AT+CMGS=\"" + buffer.substring(9, 22) + "\"\r");
delay(1000);
SIM900A.print("Lat/Long(10^-5 deg): ");
SIM900A.print(lat);
SIM900A.print(", ");
SIM900A.print(lon);
SIM900A.print(" Fix age: ");
SIM900A.print(age); SIM900A.println("ms.");
SIM900A.print("Date(ddmmyy): "); SIM900A.print(date);
SIM900A.print(" Time(hhmmsscc): ");
SIM900A.print(time);
SIM900A.print(" Fix age: "); SIM900A.print(age);
SIM900A.println("ms.");
SIM900A.print("Alt(cm): "); SIM900A.print(gps.altitude());
SIM900A.print(" Speed(mps): "); SIM900A.print(gps.f_speed_mps());
SIM900A.println((char)26);// ASCII code of CTRL+Z
delay(1000);
}
}
}
delay(100);
}
String readSIM900A() {
String buffer;
while (SIM900A.available()) {
char c = SIM900A.read();
buffer.concat(c);
delay(10);
}
return buffer;
}
Above is my final code when the GPS and GSM modules are handled together. They are working totally fine when they are handled separately.
Connections:
Connected Tx, Rx pin of SIM900A to 9, 10 of Arduino Nano respectively, and Tx, Rx of GPS module to 5, 6 respectively. And I also made ground common with Arduino.
#include <NeoSWSerial.h>
//#include <SoftwareSerial.h>
#include <AltSoftSerial.h>
// GPS
#include <TinyGPS.h>
// GSM
static const int RXPin = 8, TXPin = 9;
AltSoftSerial SIM900A(RXPin, TXPin);
NeoSWSerial mySerial(5, 6);
TinyGPS gps;
void setup()
{
Serial.begin(9600);
SIM900A.begin(9600);
SIM900A.println("AT+CNMI=2,2,0,0,0");
mySerial.begin(9600);
delay(1000);
}
void loop()
{
bool newdata = false;
String buffer = readSIM900A();
if(SIM900A.available() > 0)
Serial.println(SIM900A.read());
if (buffer.startsWith("\r\n+CMT: "))
{
// printing the number
Serial.println(buffer.substring(9, 22));
// Remove first 51 characters
// buffer.remove(0, 51);
int len = buffer.length();
// Remove \r\n from tail
// buffer.remove(len - 2, 2);
// printing message
Serial.println(buffer.substring(51, len-2));
if (buffer.substring(51, len-2) == "location")
{
Serial.println("Sending location");
// GPS
if (mySerial.available())
{
char c = mySerial.read();
if (gps.encode(c))
{
newdata = true;
}
}
if (newdata)
{
long int lat, lon;
unsigned long age, age1, date, time, chars;
gps.get_position(&lat, &lon, &age);
gps.get_datetime(&date, &time, &age);
Serial.print("Lat/Long(10^-5 deg): ");
Serial.print(lat);
Serial.print(", ");
Serial.print(lon);
Serial.print(" Fix age: ");
Serial.print(age); Serial.println("ms.");
Serial.print("Date(ddmmyy): "); Serial.print(date); Serial.print("
Time(hhmmsscc): ");
Serial.print(time);
Serial.print(" Fix age: "); Serial.print(age);
Serial.println("ms.");
Serial.print("Alt(cm): "); Serial.print(gps.altitude());
Serial.print(" Speed(mps): "); Serial.print(gps.f_speed_mps());
// setting GSM module
SIM900A.println("AT+CMGF=1"); //Sets the GSM Module in Text Mode
delay(1000); // Delay of 1000 milli seconds or 1 second
// sending location from which code word had come
SIM900A.println("AT+CMGS=\"" + buffer.substring(9, 22) + "\"\r"); //
Replace x with mobile number
Serial.println("AT+CMGS=\"" + buffer.substring(9, 22) + "\"\r");
delay(1000);
SIM900A.print("Lat/Long(10^-5 deg): ");
SIM900A.print(lat);
SIM900A.print(", ");
SIM900A.print(lon);
SIM900A.print(" Fix age: ");
SIM900A.print(age); SIM900A.println("ms.");
SIM900A.print("Date(ddmmyy): "); SIM900A.print(date);
SIM900A.print(" Time(hhmmsscc): ");
SIM900A.print(time);
SIM900A.print(" Fix age: "); SIM900A.print(age);
SIM900A.println("ms.");
SIM900A.print("Alt(cm): "); SIM900A.print(gps.altitude());
SIM900A.print(" Speed(mps): "); SIM900A.print(gps.f_speed_mps());
SIM900A.println((char)26);// ASCII code of CTRL+Z
delay(1000);
}
}
}
delay(100);
}
String readSIM900A()
{
String buffer;
while (SIM900A.available())
{
char c = SIM900A.read();
buffer.concat(c);
delay(10);
}
return buffer;
}
P.S : I have changed the pins for GSM and rest part is same. Except adding AltSoftSerial it is a library same as SoftwareSerial (Download it from manage libraries and it requires pins 8 and 9). Don't change pin number in sketch change the connections.

Resources