使用 3 个 LED 的串行通信更改亮度



到目前为止,我已经编写了代码,如果 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% 的亮度点亮。

为了使LED以一半的亮度点亮,您需要使用脉冲宽度调制。确保您使用的引脚旁边有 ~(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);
  }
}

最新更新