This circuit integrates an Arduino Nano microcontroller with an HC-SR04 Ultrasonic Distance Sensor and an RGB LED. The purpose of the circuit is to measure distances using the ultrasonic sensor and visually indicate the distance range through the color of the RGB LED. The RGB LED changes color based on the distance measured: red for close distances, green for intermediate distances, and blue for farther away. The Arduino Nano controls the sensor and the LED, and it also sends distance information to a connected computer via serial communication.
/*
* Arduino Nano with HC-SR04 Ultrasonic Sensor and RGB LED
* This code initializes the sensor and reads the distance
* measured by the sensor, then changes the color of the RGB LED
* based on the distance. The RGB LED is connected to pins D5, D6, and D7.
*/
const int trigPin = 9; // TRIG pin connected to D9
const int echoPin = 10; // ECHO pin connected to D10
const int redPin = 5; // Red LED pin connected to D5
const int greenPin = 6; // Green LED pin connected to D6
const int bluePin = 7; // Blue LED pin connected to D7
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set the TRIG pin as an OUTPUT
pinMode(trigPin, OUTPUT);
// Set the ECHO pin as an INPUT
pinMode(echoPin, INPUT);
// Set the RGB LED pins as OUTPUT
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}
void loop() {
// Clear the TRIG pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Set the TRIG pin HIGH for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the ECHO pin
long duration = pulseIn(echoPin, HIGH);
// Calculate the distance
long distance = duration * 0.034 / 2;
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Change the color of the RGB LED based on distance
if (distance < 10) {
setColor(255, 0, 0); // Red
} else if (distance < 20) {
setColor(0, 255, 0); // Green
} else {
setColor(0, 0, 255); // Blue
}
// Wait for a short period before the next measurement
delay(500);
}
void setColor(int red, int green, int blue) {
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}
This code is designed to be uploaded to an Arduino Nano. It initializes the pins connected to the HC-SR04 Ultrasonic Distance Sensor and the RGB LED, performs distance measurements, and sets the color of the RGB LED based on the measured distance. Serial communication is used to output the distance values to a connected computer for monitoring.