/*
HC-SR04 NewPing Iteration Demonstration
HC-SR04-NewPing-Iteration.ino
Demonstrates using Iteration function of NewPing Library for HC-SR04 Ultrasonic Range Finder
Displays results on Serial Monitor
*/
// This uses Serial Monitor to display Range Finder distance readings
// Include NewPing Library
#include "NewPing.h"
// Hook up HC-SR04 with Trig to Arduino Pin 10, Echo to Arduino pin 13
// Maximum Distance is 400 cm
#define TRIGGER_PIN 3
#define ECHO_PIN 6
#define MAX_DISTANCE 400
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
float duration, distance, volume, volume_of_air, max_volume, volume_litre, volume_percent;
int iterations = 5;
void setup() {
Serial.begin (9600);
}
void loop() {
duration = sonar.ping_median(iterations);
// Determine distance from duration
// Use 343 metres per second as speed of sound
distance = (duration / 2) * 0.0343;
volume_of_air = (22 / 7) * (5 * 5) * distance;
max_volume = (22 / 7) * (5 * 5) * 400;
volume = (max_volume - volume_of_air);
volume_litre = volume * 0.001;
volume_percent = round((volume/max_volume)*100);
// -------
// String tmp = JSON.stringify(volume_litre);
// Serial.print("Value: ");
// Serial.println(tmp);
// ------
// Send results to Serial Monitor
// Serial.print("{");
// Serial.print("Distance: ");
if (distance >= 400 || distance <= 2) {
Serial.println("Out of range");
}
else {
// Serial.print(distance);
// Serial.print(", ");
// Serial.print(" cm, ");
// Serial.print("Max Volume: ");
// Serial.print(max_volume);
// Serial.print(", ");
// Serial.print(" cm3, ");
// Serial.print("Volume of Air: ");
// Serial.print(volume_of_air);
// Serial.print(", ");
// Serial.print(" cm3, ");
// Serial.print("Volume: ");
// Serial.print(volume);
// Serial.print(", ");
// Serial.print(" cm3 ");
// ---
// Serial.print("Volume: ");
// Serial.print(volume_litre);
// Serial.print(" ltr.");
// Serial.print(", ");
// Serial.print("Percent: ");
// Serial.print(volume_percent);
// Serial.println(" %");
// Serial.println("}");
Serial.print("{\"Volume\":\"");
Serial.print(volume_litre);
Serial.print(" ltr.\"");
Serial.print(",\"");
Serial.print("Percent\":\"");
Serial.print(volume_percent);
Serial.print("%\"");
Serial.println("}");
delay(1000);
}
delay(1000);
}