HC-SR04 Ultrasonic sensor based DC motor mini fan
As shown above the HC-SR04 Ultrasonic (US) sensor is a 4 pin module, whose pin names are Vcc, Trigger, Echo and Ground respectively. This sensor is a very popular sensor used in many applications where measuring distance or sensing objects are required. The module has two eyes like projects in the front which forms the Ultrasonic transmitter and Receiver. The sensor works with the simple high school formula that
Distance = Speed × Time
The Ultrasonic transmitter transmits an ultrasonic wave, this wave travels in air and when it gets objected by any material it gets reflected back toward the sensor this reflected wave is observed by the Ultrasonic receiver module as shown in the picture below
Now, to calculate the distance using the above formulae, we should know the Speed and time. Since we are using the Ultrasonic wave we know the universal speed of US wave at room conditions which is 330m/s. The circuitry inbuilt on the module will calculate the time taken for the US wave to come back and turns on the echo pin high for that same particular amount of time, this way we can also know the time taken. Now simply calculate the distance using a microcontroller or microprocessor.
Connection of DC-motor with Arduino and ultrasonic sensor:
code:
int pinTrig = 9; // connect the trigger pin of ultrasonic sensor -----> pin 6 .
int pinEcho = 10; // connect the echo pin of ultrasonic sensor ----> pin 7 .
int pinMotor = 11; // connect the motor pin 11 (Note: you can led, buzzer)
long duration;
int distance; // distance between object and ultrasonic sensor.
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(pinTrig, OUTPUT);
pinMode(pinEcho, INPUT);
pinMode(pinMotor, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(pinTrig, LOW);
delayMicroseconds(2);
digitalWrite(pinTrig, HIGH);
delayMicroseconds(10);
digitalWrite(pinTrig, LOW);
duration = pulseIn(pinEcho, HIGH);
distance = duration*0.034/2;
Serial.print("Distance: ");
Serial.println(distance);
if(distance <= 18){ // the distance is in centimeter you can set your value I select I select 18 because it my lucky number :)
digitalWrite(pinMotor, HIGH); // Start the motor
}else{
digitalWrite(pinMotor, LOW); // Stop the motor
}
}
Connection of Arduino with DC motor:
code:
int motorPlus = 5;
int motorMinus = 6;
void setup() {
// put your setup code here, to run once:
pinMode(motorPlus,OUTPUT);
pinMode(motorMinus,OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(motorPlus,HIGH);
digitalWrite(motorMinus,HIGH);
delay(2000);
digitalWrite(motorPlus,HIGH);
digitalWrite(motorMinus,HIGH);
delay(2000);
}
Happy reading.. Please follow us on blogger leave a comment below if have any queries