Reputation: 75
I have a question about my Arduino Leonardo. What I want to do with my Arduino is that the higher the value of AnalogWrite is, the more lights will go on. I've used a if else
statement but I need a 'until value' function. Now all the lights will go on because I only used a < > but not a value from 0 till 50, 50 till 100 etc. Can somebody figure out how I need to write this?
int analogInPin = A3;
int sensorValue = 0;
int ledPin1 = 3;
int ledPin2 = 5;
int ledPin3 = 6;
int ledPin4 = 9;
int ledPin5 = 10;
int analogPin = 3;
void setup() {
Serial.begin(9600);
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);
pinMode(ledPin4, OUTPUT);
pinMode(ledPin5, OUTPUT);
}
void loop() {
sensorValue = analogRead(analogInPin);
Serial.println("sensor = ");
Serial.println(sensorValue);
delay(2);
if ( sensorValue < 50 ) {
analogWrite(ledPin1, sensorValue);
} else if ( sensorValue > 50 ) {
analogWrite(ledPin2, sensorValue);
}
if ( sensorValue < 100 ) {
analogWrite(ledPin2, sensorValue);
}
if ( sensorValue < 150 ) {
analogWrite(ledPin3, sensorValue);
}
}
Upvotes: 1
Views: 190
Reputation: 1690
First your else if and your if (sensorValue < 100) will make two both if the value is between 50 and 100.
If I understand, you want to turn on the ledPin1 in range 0-50, led pin2 in range 50-100 and led pin 3 100-150?
if (sensorValue >= 0 && sensorValue <= 50 ) {
analogWrite(ledPin1, sensorValue);
analogWrite(ledPin2, LOW);
analogWrite(ledPin3, LOW);
}
else if (sensorValue > 50 && sensorValue <= 100) {
analogWrite(ledPin2, sensorValue);
analogWrite(ledPin1, LOW);
analogWrite(ledPin3, LOW);
}
else if (sensorValue > 100 && sensorValue <= 150) {
analogWrite(ledPin3, sensorValue);
analogWrite(ledPin1, LOW);
analogWrite(ledPin2, LOW);
}
Let me know if it's results!
Upvotes: 1