到目前为止,我已经编写了代码,如果1然后输入按下或发送点击,然后再次输入1并输入按下或发送点击导致LED 1打开,如果'1''0'以类似的方式输入然后LED 1关闭,依此类推LED 2和3,即:'2''1'打开LED 2,'3''0'关闭LED 3。
int incomingVal;
int ledPin = 16;
int ledPin2 = 15;
int ledPin3 = 14;
void setup()
{
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
Serial.println("starting");
pinMode(ledPin,OUTPUT);
pinMode(ledPin2,OUTPUT);
pinMode(ledPin3,OUTPUT);
}
void loop()
{
if (Serial.available() > 0 ) //then chars are in the serial buffer
{
incomingVal = Serial.parseInt();
Serial.print("You entered: ");
Serial.println(incomingVal);
if (incomingVal == 10)//turns off led 1
{
digitalWrite(ledPin, LOW);
}
if (incomingVal == 11)//turns on led 1
{
digitalWrite(ledPin, HIGH);
}
if (incomingVal == 20)//turns off led 2
{
digitalWrite(ledPin2, LOW);
}
if (incomingVal == 21)//turns on led 2
{
digitalWrite(ledPin2, HIGH);
}
if (incomingVal == 30)//turns off led 3
{
digitalWrite(ledPin3, LOW);
}
if (incomingVal == 31)//turns on led 3
{
digitalWrite(ledPin3, HIGH);
}
}
}
我怎么能改变代码所以我可以输入第三个值来将亮度从0改为250?例如,输入“2,1,125”会使LED 2以50%的亮度点亮。
答案 0 :(得分:1)
要使LED亮起一半亮度,您需要使用pulse width modulation。确保您使用的引脚位于它们旁边(Uno上的引脚3,5,6,9,10,11)。
我会略微改变你的输入法,因为0亮度基本上与关掉LED一样,你应该只需要2个数字。第一个数字对应LED,第二个数字对应亮度。
int led_pins[3] = {9,10,11};
int incomingVal;
int brightness;
int parsed_value;
int x = 0;
void setup()
{
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
Serial.println("starting");
pinMode(led_pins[0],OUTPUT); // You could also use a loop here
pinMode(led_pins[1],OUTPUT);
pinMode(led_pins[2],OUTPUT);
}
void loop()
{
if (Serial.available() > 0 ) //then chars are in the serial buffer
{
incomingVal = Serial.parseInt();
Serial.print("You entered: ");
Serial.println(incomingVal);
//figure out which LED we selected
parsed_value = incomingVal;
while (parsed_value > 9){
/*
because of integer division, this line will remove the last
number from the integer. ie 11 / 10 = 1 (the result is rounded down)
The loop will continue until only 1 digit remains
*/
x++;
parsed_value = parsed_value / 10;
}
// x represents the number of times parsed_value was divided by 10
// this line removes the first digit of the incoming value, leaving
// the brightness
brightness = incomingVal - pow(10,x)*parsed_value;
/*parsed_value will be 1 greater than the array key value because
the array is 0 based.*/
//set the LED to the right brightness
analogWrite(led_pins[parsed_value-1],brightness);
}
}