0% found this document useful (0 votes)
4 views

ahhhhhhhhh

This document contains an Arduino code for an ultrasonic sensor that measures distance and controls three LEDs based on the measured distance. The setup initializes the necessary pins for the sensor and LEDs, while the loop continuously reads the distance and activates the corresponding LED based on predefined distance thresholds. The code includes serial communication for debugging purposes to display the measured distance in centimeters.

Uploaded by

inyangeraissa79
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

ahhhhhhhhh

This document contains an Arduino code for an ultrasonic sensor that measures distance and controls three LEDs based on the measured distance. The setup initializes the necessary pins for the sensor and LEDs, while the loop continuously reads the distance and activates the corresponding LED based on predefined distance thresholds. The code includes serial communication for debugging purposes to display the measured distance in centimeters.

Uploaded by

inyangeraissa79
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

const int trigPin = 9; // Trigger pin for ultrasonic sensor

const int echoPin = 10; // Echo pin for ultrasonic sensor


const int ledPin1= 8;
const int ledPin2 = 6; // Pin for the LED
const int ledPin3= 7;

void setup() {
// Start the serial communication
Serial.begin(9600);
// Set the pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);

// Attach the servo motor to pin 9


}

void loop() {
// Clear the trigger
digitalWrite(trigPin, LOW);
delayMicroseconds(0);

// Trigger the sensor


digitalWrite(trigPin, HIGH);
delayMicroseconds(0);
digitalWrite(trigPin, LOW);

// Read the echo pin


long duration = pulseIn(echoPin, HIGH);

// Calculate the distance (in cm)


long distance = duration * 0.034 / 2;

// Print the distance for debugging


Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");

// Control the LED based on distance


if (distance < 20) { // If the distance is less than 10 cm
digitalWrite(ledPin1, HIGH);
// delay(100);
// digitalWrite(ledPin1, LOW);
// delay(100);
} // Turn on LED
else if (distance < 30)
{
digitalWrite(ledPin2, HIGH); // Turn off LED
}
else if (distance < 50)
{// Wait a bit before t
digitalWrite(ledPin3, HIGH);

// Wait for 1 second

} // Wait for 1 second

else if (distance < 70)


{
digitalWrite(ledPin3, HIGH);
// Wait for 1 second
}
else {
digitalWrite(ledPin1,LOW);
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin3, LOW);

}
}

You might also like