Thursday, 23 November 2017

[Distance measurement] Arduino with Hc-sr04


Schematic using frizting: 

Math related: 

Sound velocity = 34300 cm/s
Microsecond = 1 x 10^-6
Clock cycle (8051 series) = 1.085 x Microsecond
Signal catch = signal produced by sensor ultrasonic

Signal merging = Clock cycle x Sound velocity
Distance (cm) = (Signal catch x Signal merging) / 2 

Flow Chart: 

Block Diagram: 

Code: 

#include <LiquidCrystal.h> // includes the LiquidCrystal Library
#include <math.h>                // math library
#define sound_velocity 34300      // declate sound velocity fact
#define period_in_us pow(10,-6)    //microsec declare on graph
#define Clock_period 1.085*period_in_us //declare clock period
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);// LCD setup pin
const int trigPin = 9; // HC-SR04 triger pin output
const int echoPin = 10; // HC-SR04 echo pin input
const int led = 7;      // set led
long duration;          // set long for duration
float distance, value;  // set float for distance and value
void setup() {
lcd.begin(16,2); // Initializes the interface to the LCD screen, and specifies the dimensions (width and height) of the display
pinMode(trigPin, OUTPUT);      //trig set output
pinMode(echoPin, INPUT);      //echo set input
pinMode(led, OUTPUT);          //led set output
}
void loop() {
digitalWrite(trigPin, LOW);      //trig set low
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);    // trig set high
delayMicroseconds(10);
digitalWrite(trigPin, LOW);      // trig set low
value = Clock_period * sound_velocity; //formula for sound merging
duration = pulseIn(echoPin, HIGH);      //take time when echo is high
distance = (duration*value)/2.0;        // formula for distance
lcd.setCursor(0,0); // Sets the location at which subsequent text written to the LCD will be displayed
lcd.print("Distance: "); // Prints string "Distance" on the LCD
lcd.setCursor(0,1); // Sets the location at which subsequent text written to the LCD will be displayed
lcd.print(distance); // Prints the distance value from the sensor
lcd.setCursor(14,1); // Sets the location at which subsequent text written to the LCD will be displayed
lcd.print("CM");
delay(10);
if (distance >= 15)   //set  limit to 15
{
  // do Thing A
  digitalWrite(led, HIGH); // set turn on when more than 15 cm
}
else
{
  // do Thing A
  digitalWrite(led, LOW); // set off when less than 15
}
delay(1000);
lcd.clear();         // LCD clear.
}



Picture: 


Video:

No comments:

Post a Comment