how to use ultrasonic sensor hc sr04 and gps neogps 6m and gsm sim900 on arduino

’m trying to send an sms with the location when the ultrasonic sensor measures a certain distance but when I add the gpsSerial(9600) line in the void setup, the ultrasonic sensor readings become inconsistent such as it reads 24 cm then skips to 18 cm then back to 24 cm. i would really appreciate it if anyone familiar with arduino or has faced this problem before would help me out. here is my code:

#include <TinyGPS.h>
#include <SoftwareSerial.h>
#include “NewPing.h”
#define TRIGGER_PIN 7
#define ECHO_PIN 8
#define MAX_DISTANCE 100

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
float duration, distance;

SoftwareSerial gsmSerial(2, 3);
SoftwareSerial gpsSerial(5, 4);

TinyGPS gps; //Creates a new instance of the TinyGPS object

bool newData = false;

void setup()
{

Serial.begin(9600);
gsmSerial.begin(9600);
gpsSerial.begin(9600);

}

void loop()
{

// Send ping, get distance in cm
distance = sonar.ping_cm();

if (distance < 4 )
{
//sendSMS();
Serial.println(“Bin is full!!, SMS SENT!!”);
Serial.println(distance);
delay(1200);
}
else
{
Serial.println(distance);
delay(2000);
}

delay(2000);

}

void sendSMS(){

// For one second we parse GPS data and report some key values
for (unsigned long start = millis(); millis() - start < 1000;)
{
while (gpsSerial.available())
{
char c = gpsSerial.read();
//Serial.print(c);
if (gps.encode(c))
newData = true;
}
}

if (newData) //If newData is true
{
float flat, flon;
unsigned long age;
gps.f_get_position(&flat, &flon, &age);
gsmSerial.print(“AT+CMGF=1\r”);
delay(400);
gsmSerial.println(“AT + CMGS = “+26xxxxxxxx””);// recipient’s mobile
number
delay(300);
gsmSerial.print(“BIN IS FULL!, PLEASE COLLECT @ https://www.google.com
/maps/?q=”);
gsmSerial.print(flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : flat, 6);
gsmSerial.print(",");
gsmSerial.print(flon == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : flon, 6);
delay(200);
gsmSerial.println((char)26); // End AT command with a ^Z, ASCII code
26
delay(2000);
gsmSerial.println();

}
}

1 Like