Howdy,
I have a ping distance sensor, and I'm simply (ha?) trying to have a RED led light up if X distance away, YELLOW led light up if another distance, and a GREEN led if another distance away. So far, I have this code:
// Example 45.1 - tronixstuff.com - CC by-sa-nc
// Connect Ping))) signal pin to Arduino digital 8
const int signal = 3;
const int redLED = 8;
const int yellowLED = 9;
const int greenLED = 10;
int whichLED;
int distance, indistance;
unsigned long pulseduration=0;
void setup()
{
// pinMode(signal, OUTPUT);
Serial.begin(9600);
pinMode(redLED,OUTPUT);
pinMode(yellowLED, OUTPUT);
pinMode(greenLED, OUTPUT);
}
void measureDistance()
{
// set pin as output so we can send a pulse
pinMode(signal, OUTPUT);
digitalWrite(signal, LOW);
delayMicroseconds(5);
digitalWrite(signal, HIGH);
delayMicroseconds(5);
digitalWrite(signal, LOW);
pinMode(signal, INPUT);
pulseduration=pulseIn(signal, HIGH);
}
void loop()
{
measureDistance();
pulseduration=pulseduration/2;
distance = int(pulseduration/29);
indistance = distance*.39;
if (indistance < 10){
whichLED = redLED;
}
if (indistance >11 && indistance < 30){
whichLED = yellowLED;
}
if (indistance > 31){
whichLED = greenLED;
}
digitalWrite(whichLED, HIGH);
// digitalWrite([the other two LEDs], LOW); THIS IS WHAT I'M TRYING TO FIGURE OUT ....
// Display on serial monitor
Serial.print("Distance - ");
Serial.print(distance);
Serial.print(" cm ");
Serial.print(indistance);
Serial.print(" in. LED lit up is ");
Serial.println(whichLED);
delay(500);
}
This works - almost. When it starts, I have my green one lit up, since the distance to the nearest object is greater than 31 inches. However, when I put something in the YELLOW and RED range, the LEDs stay lit up.
How would I code it so the other two LEDs go LOW? I have seen code before using variables like
int specialVar[3]; but am not sure what to look up to learn about that - would that work?
Does my question make sense? I am basically looking for a way to do
digitalWrite(whichLED, HIGH);
digitalWrite(the other inputs that aren't whichLED, LOW);
so if whichLED is 'redLED' (or 8 ),
digitalWrite([9,10], LOW);
Thanks for any help or ideas!
[Edit: Solved, thanks to BulldogLowell and here for code using "variable pass"]