int redLED = 2;
int greenLED = 3;
int blueLED = 4;
#define trigPin 5
#define echoPin 6
long duration;
int distance;
void setup() {
pinMode(redLED, OUTPUT);
pinMode(greenLED, OUTPUT);
pinMode(blueLED, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
}
void loop() {
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
if(distance <5){
digitalWrite(trigPin, HIGH);
digitalWrite(redLED, HIGH);
digitalWrite(greenLED, LOW);
digitalWrite(blueLED, LOW);
delayMicroseconds(10);
}
else if(distance >5 && distance <10){
digitalWrite(trigPin, HIGH);
digitalWrite(redLED, LOW);
digitalWrite(greenLED, HIGH);
digitalWrite(blueLED, LOW);
delayMicroseconds(10);
}
else if(distance >10 && distance <15){
digitalWrite(trigPin, HIGH);
digitalWrite(redLED, LOW);
digitalWrite(greenLED, LOW);
digitalWrite(blueLED, HIGH);
delayMicroseconds(10);
}
}
Hi,
To add code please click this link;
See also FAQ - Arduino Forum for general rules on forum behaviour and etiquette.
Hello,
Welcome to the Arduino Forum.
This guide explains how to get the best out of this forum. Please read and follow the instructions below.
Being new here you might think this is having rules for the sake of rules, but that is not the case. If you don’t follow the guidelines all that happens is there is a long exchange of posts while we try to get you to tell us what we need in order to help you, which is fru…
Can you please post a copy of your circuit, in CAD or a picture of a hand drawn circuit in jpg, png?
Hand drawn and photographed is perfectly acceptable.
Please include ALL hardware, power supplies, component names and pin labels.
What model Arduino are you using?
Have you looked at NewPing library to simplify your distance measurement?
https://playground.arduino.cc/Code/NewPing/
Tom..
Suggest you add a couple of lines, as follows:
duration = pulseIn(echoPin, HIGH);
Serial.print("Duration: "); //new
Serial.println(duration); //also new
distance = (duration/2) / 29.1;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
Then, look at the output, see if your calculation is correct.
You have to pulse the Trigger pin before you can measure the length of the Echo pulse.
You can do that with:
void loop() {
digitalWrite(trigPin, HIGH);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
system
Closed
June 6, 2023, 5:18pm
5
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.