Distance - Arduino Uno code


#include <DHT.h>
#include <DHT_U.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <NewPing.h>

#define DHTPIN 13
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal_I2C lcd(0x27,16,2);  // set the LCD address to 0x27 for a 16 chars and 2 line display

#define TRIGGER_PIN  10  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     9  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 300 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
#define iterations 5

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
float duration, cm, soundsp, soundcm;

void setup()
{
  lcd.init();                      // initialize the lcd
  lcd.backlight();
  dht.begin();
  delay(2000);
  float hum = dht.readHumidity();
  float temp = dht.readTemperature();
  soundsp = 331.4 + (0.606 * temp) + (0.0124 * hum);
   lcd.setCursor(0,0);
   lcd.print(temp);
   lcd.print("   ");
   lcd.print(hum);
   lcd.setCursor(0,1);
   lcd.print("sound:");
   lcd.print(soundsp);
   soundcm = soundsp / 10000;
   delay(3000);
}

void loop()
{
   duration = sonar.ping_median(iterations);
   cm = (duration /2) * soundcm;

   lcd.setCursor(0,0);
   lcd.print("Distance ");
   lcd.print(cm);
   lcd.print("  ");
   delay(500);
}