How to Code Arduino Ultrasonic Sensor?

How to Code Arduino Ultrasonic Sensor?

Arduino Ultrasonic Sensor is a widely used sensor, many people use Ultrasonic Sensor for Distance Management Project.

Ultrasonic Sensor available with different ranges and capability, but in this code, we are going to use the HC-SR04 Model.

Arduino Ultrasonic Sensor Code is capable of doing or it will help you many projects by modifying with your project’s requirement.

There is a list of components that is required for the experiment with this code.

  1. Arduino Uno
  2. Breadboard
  3. Jumper Wire
  4. Ultrasonic Sensor(HC-SR04)
  5. Multi-Meter(Optional)

Code for your Experiment

#define trigPin 7
#define echoPin 8
#define led 13

void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(led, OUTPUT);
pinMode(fan, OUTPUT);

void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);  
digitalWrite(trigPin, HIGH);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance < 50) { 
 Serial.println("Light is ON");
else {
  Serial.println(" cm");
  Serial.println("Out of Range");

Circuit Design

Copyright © 2020-2021 Engineer Jagat All rights reserved. Developed by Ravindra Rana