Arduino-led-bar-graph

提供:Dev Guides
移動先:案内検索

Arduino-LED棒グラフ

この例では、アナログピン0のアナログ入力を読み取り、analogRead()の値を電圧に変換し、Arduino Software(IDE)のシリアルモニターに出力する方法を示します。

必要なコンポーネント

次のコンポーネントが必要になります-

  • 1×ブレッドボード
  • 1×Arduino Uno R3
  • 1×5kオーム可変抵抗器(ポテンショメーター)
  • 2×ジャンパー
  • 8×LEDまたは使用可能(下の画像に示すようにLEDバーグラフ表示)

手順

以下の画像に示すように、回路図に従って、ブレッドボード上のコンポーネントを接続します。

バーブレッドボード

バーブレッドボードへの接続

スケッチ

コンピューターでArduino IDEソフトウェアを開きます。 Arduino言語でコーディングすると、回路が制御されます。 [新規]をクリックして、新しいスケッチファイルを開きます。

スケッチ

10セグメントLED棒グラフ

LEDバーグラフ

これらの10セグメント棒グラフLEDには多くの用途があります。 コンパクトな設置面積とシンプルな接続により、プロトタイプや完成品を簡単に作成できます。 基本的に、10個の個別の青色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-loop を設定します。 シリーズ内の出力の番号がマッピングされた入力範囲よりも小さい場合は、オンにします。 そうでない場合は、オフにします。

結果

アナログ読み取り値が増加するとLEDが1つずつ点灯し、読み取り値が減少している間に1つずつ消灯します。