Technology
Using an Ultrasonic Sensor with Arduino to Light Up an LED
How to Make an LED Light Up Using an Ultrasonic Sensor with Arduino
To make an LED light up using an ultrasonic sensor with an Arduino, you need to follow a series of steps and write a specific code. In this guide, we will cover the necessary components, wiring setup, a detailed circuit diagram, sample Arduino code, and a step-by-step explanation of how it works. Additionally, we will provide a testing procedure to ensure everything is working as expected.
Components Required
Arduino board: e.g., Arduino Uno HC-SR04 ultrasonic sensor LED 220-ohm resistor for the LED Breadboard and jumper wiresWiring Setup
The wiring setup for the HC-SR04 ultrasonic sensor and the LED is critical for the project to work correctly. Here are the connections:
HC-SR04Arduino VCC5V GNDGND TrigDigital pin 9 (e.g., Pin 9) EchoDigital pin 10 (e.g., Pin 10) LED:Pin 1 (long leg, anode) connected to a digital pin (e.g., Pin 13) through a 220-ohm resistor
Pin 2 (short leg, cathode) connected to Arduino GND HC-SR04Arduino VCC5V GNDGND Trig9 LED --- --- 220Ω --- Pin 13 GND
Arduino Code
Here is a simple code example to make the LED light up when an object is detected within a specific distance:
// Define the pins attached to the ultrasonic sensor and LED #define TRIG_PIN 9 #define ECHO_PIN 10 #define LED_PIN 13 void setup () { // Set the baud rate to 9600 for serial communication (9600); // Set the Trig and Echo pins as output and input respectively pinMode(TRIG_PIN, OUTPUT); pinMode(ECHO_PIN, INPUT); pinMode(LED_PIN, OUTPUT); } void loop () { // Clear the trigger digitalWrite(TRIG_PIN, LOW); delayMicroseconds(2); // Send signal to Trig pin digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN, LOW); // Measure the time taken for the Echo to return long duration pulseIn(ECHO_PIN, HIGH); // Calculate the distance in centimeters float distance duration * 0.034 / 2; // Print the distance to the Serial Monitor ("Distance: "); (distance); (" cm"); // Check if the distance is less than 10 cm if (distanceExplanation of the Code
Setup Function
Initializes the serial communication Sets pin modes for the ultrasonic sensor and LEDLoop Function
Sends a trigger signal to the ultrasonic sensor Measures the time it takes for the echo to return Calculates the distance based on the duration of the echo Turns on the LED if the distance is less than 10 cm; otherwise, it turns it offTesting
1. Upload the code to your Arduino. 2. Open the Serial Monitor to observe the distance readings. 3. Move an object closer to the sensor to see if the LED lights up when the object is within 10 cm.
This setup allows you to control an LED based on distance measurements from the ultrasonic sensor. You can adjust the distance threshold in the code as needed for your application!