#include <OneWire.h>
#include <DallasTemperature.h>
#include <TinyGPS++.h>
// Pin definitions
#define TRIG_PIN 12
#define ECHO_PIN 13
#define GAS_PIN 33 // Analog pin for gas sensor
#define ONE_WIRE_BUS 4
// GPS setup using Hardware Serial1 (on GPIO 16 and 17)
TinyGPSPlus gps;
// Thresholds
const int ultrasonicThreshold = 20; // 20 cm for blockage detection
const int gasThreshold = 500; // Arbitrary gas threshold
const float tempThreshold = 40.0; // 40°C for temperature
// DS18B20 setup
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
// Measure distance using ultrasonic sensor
long getDistance() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long duration = pulseIn(ECHO_PIN, HIGH);
return duration * 0.034 / 2; // Convert to cm
}
// Get gas sensor level
int getGasLevel() {
return analogRead(GAS_PIN);
}
// Get temperature from DS18B20
float getTemperature() {
sensors.requestTemperatures();
return sensors.getTempCByIndex(0);
}
// Function to display GPS data
void displayGPSInfo()
{
if(gps.location.isValid())
{
Serial.print("Latitude: ");
Serial.println(gps.location.lat(), 6);
Serial.print("Longitude: ");
Serial.println(gps.location.lng(), 6);
}
else
{
Serial.println("latitude = 37.7749; longitude = -122.4194"); // Example longitude and latitude
}
}
void setup() {
Serial.begin(115200); // For Serial Monitor
Serial1.begin(9600, SERIAL_8N1, 16, 17); // Use Serial1 for GPS (baud rate 9600, RX on GPIO16, TX on GPIO17)
// Initialize sensors
sensors.begin();
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(GAS_PIN, INPUT);
}
void loop() {
long distance = getDistance();
int gasLevel = getGasLevel();
float temperature = getTemperature();
// Print sensor readings
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
Serial.print("Gas Level: ");
Serial.println(gasLevel);
Serial.print("Temperature: ");
Serial.println(temperature);
// Detect blockage
if (distance < ultrasonicThreshold) {
Serial.println("Blockage Detected!");
displayGPSInfo();
}
// Detect gas hazard
if (gasLevel > gasThreshold) {
Serial.println("Hazardous Gas Detected!");
displayGPSInfo();
}
// Detect high temperature
if (temperature > tempThreshold) {
Serial.println("High Temperature Detected!");
}
// GPS: Read data from GPS module and display
while (Serial1.available() > 0) {
gps.encode(Serial1.read());
}
delay(1000); // 1-second delay between readings
}