我对我的Arduino Leonardo有疑问。我想用Arduino做的是,AnalogWrite的值越高,灯光就越多。我使用了if else
语句,但我需要一个'until value'函数。现在所有的灯都会继续,因为我只使用了一个< >但不是0到50之间的值,50到100之间的等等。有人可以弄清楚我需要写这个吗?
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);
}
}
答案 0 :(得分:1)
首先你的其他if和你的if(sensorValue&lt; 100)如果值介于50和100之间,则会产生两个。
如果我理解,你想在0-50范围内打开ledPin1,在50-100范围内打开pin2,在100-150范围内打开引脚3?
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);
}
请告诉我它的结果!