Arduino - LED 條形圖

此示例顯示如何讀取模擬引腳 0 處的模擬輸入,將 analogRead() 中的值轉換為電壓,並將其列印到 Arduino 軟體(IDE)的序列監視器。

需要的元件

你將需要以下元件 -

  • 1×麵包板
  • 1×Arduino Uno R3
  • 1×5k 歐姆可變電阻(電位器)
  • 2×跳線
  • 8×LED 或你可以使用(LED 條形圖顯示如下圖所示)

程式

按照電路圖並連線面包板上的元件,如下圖所示。

麵包板

連線到麵包板

草圖

在你的計算機上開啟 Arduino IDE 軟體。用 Arduino 語言編碼將控制你的電路。單擊“新建”開啟新的草圖檔案。

草圖

10 段 LED 條形圖

LED 條形圖

這些 10 段條形圖 LED 具有許多用途。憑藉緊湊的外形,簡單的連線,它們易於原型或成品。基本上,它們是 10 個單獨的藍色 LED,每個 LED 都裝在一起,每個 LED 都有一個獨立的陽極和陰極連線。

它們還有黃色,紅色和綠色可供選擇。

- 這些條形圖上的引腳可能與資料手冊中列出的不同。將裝置旋轉 180 度將糾正更改,使引腳 11 成為第一個引腳。

Arduino 程式碼

/*
   LED bar graph
   Turns on a series of LEDs based on the value of an analog sensor. 
   This is a simple way to make a bar graph display. 
   Though this graph uses 8LEDs, you can use any number by
      changing the LED count and the pins in the array.
   This method can be used to control any series of digital
      outputs that depends on an analog input.
*/

// these constants won't change:
const int analogPin = A0; // the pin that the potentiometer is attached to
const int ledCount = 8; // the number of LEDs in the bar graph
int ledPins[] = {2, 3, 4, 5, 6, 7, 8, 9}; // an array of pin numbers to which LEDs are attached

void setup() {
   // loop over the pin array and set them all to output:
   for (int thisLed = 0; thisLed < ledCount; thisLed++) {
      pinMode(ledPins[thisLed], OUTPUT);
   }
}

void loop() {
   // read the potentiometer:
   int sensorReading = analogRead(analogPin);
   // map the result to a range from 0 to the number of LEDs:
   int ledLevel = map(sensorReading, 0, 1023, 0, ledCount);
   // loop over the LED array:
   for (int thisLed = 0; thisLed < ledCount; thisLed++) {
      // if the array element's index is less than ledLevel,
      // turn the pin for this element on:
      if (thisLed < ledLevel) {
         digitalWrite(ledPins[thisLed], HIGH);
      }else { // turn off all pins higher than the ledLevel:
         digitalWrite(ledPins[thisLed], LOW);
      }
   }
} 

程式碼注意

草圖的工作方式如下:首先,你讀取輸入。將輸入值對映到輸出範圍,在本例中為 10 個 LED。然後設定 for 迴圈以迭代輸出。如果系列中的輸出數字低於對映的輸入範圍,則將其開啟。如果沒有,請將其關閉。

結果

當模擬讀數值增加時,你會看到 LED 逐一亮起,當讀數減小時,LED 逐一關閉。