/**
HC-SR04 Demo
Demonstration of the HC-SR04 Ultrasonic Sensor
Date: August 3, 2016
Description:
Connect the ultrasonic sensor to the Arduino as per the
hardware connections below. Run the sketch and open a serial
monitor. The distance read from the sensor will be displayed
in centimeters and inches.
Hardware Connections:
Arduino | HC-SR04
-------------------
5V | VCC
2 | Trig
3 | Echo
GND | GND
License:
Public Domain
*/
// Pinos
const int TRIG_PIN = 2;
const int ECHO_PIN = 3;
// 400 cm (23200 us pulse) distancia maxima suportada pelo sensor
// 100 cm (5800 us pulse) distancia segura
// Or over 50 cm (2900 us pulse) distancia de perigo
//2 cm (116 us pulse) distancia minima suportada pelo sensor ou choque
const unsigned int SAFE_DIST =5800;
const unsigned int MAX_DIST =2900;
const unsigned int MIN_DIST = 1000;
const unsigned int ACIDENT_DIST = 500;
void setup() {
// The Trigger pin will tell the sensor to range find
pinMode(TRIG_PIN, OUTPUT);
digitalWrite(TRIG_PIN, LOW);
//Set Echo pin as input to measure the duration of
//pulses coming back from the distance sensor
pinMode(ECHO_PIN, INPUT);
// We'll use the serial monitor to view the sensor output
Serial.begin(9600);
}
void loop() {
unsigned long t1;
unsigned long t2;
unsigned long pulse_width;
float cm;
// float inches;
// Hold the trigger pin high for at least 10 us
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Wait for pulse on echo pin
while ( digitalRead(ECHO_PIN) == 0 );
// Measure how long the echo pin was held high (pulse width)
// Note: the micros() counter will overflow after ~70 min
t1 = micros();
while ( digitalRead(ECHO_PIN) == 1);
t2 = micros();
pulse_width = t2 - t1;
// Calculate distance in centimeters and inches. The constants
// are found in the datasheet, and calculated from the assumed speed
//of sound in air at sea level (~340 m/s).
cm = pulse_width / 58.0;
//inches = pulse_width / 148.0;
// Print out results
if ( pulse_width > SAFE_DIST ) {
Serial.print(cm);
Serial.print(" cm \t");
Serial.println("Seguro");
}
else {
if ( MIN_DIST < pulse_width < MAX_DIST ) {
Serial.print(cm);
Serial.print(" cm \t");
Serial.println("Cuidado! Perigo de choque!");
}
else {
//( pulse_width == ACIDENT_DIST );
Serial.print(cm);
Serial.print(" cm \t");
Serial.println("Acidente detectado!");
}
// Serial.print(inches);
//Serial.println(" in");
}
// Wait at least 3000ms before next measurement
delay(3000);
}