用直線燈條 長短(* ** *** **** ***** ****** ******* ********) 8X8 LED 顯示超音波測距距離

 #include <LedControl.h>


#define trigPin 9   // Trig 引腳 (接 HC-SR04)

#define echoPin 8   // Echo 引腳 (接 HC-SR04)


#define DATA_IN 5   // DIN

#define CLK_PIN 7   // CLK

#define LOAD_PIN 6  // CS


LedControl lc = LedControl(DATA_IN, CLK_PIN, LOAD_PIN, 1);


void setup() {

  Serial.begin(9600);

  pinMode(trigPin, OUTPUT);

  pinMode(echoPin, INPUT);


  lc.shutdown(0, false);

  lc.setIntensity(0, 8);

  lc.clearDisplay(0);

}


void loop() {

  long duration, distance;


  // 觸發超音波感測器

  digitalWrite(trigPin, LOW);

  delayMicroseconds(2);

  digitalWrite(trigPin, HIGH);

  delayMicroseconds(10);

  digitalWrite(trigPin, LOW);


  // 計算距離 (cm)

  duration = pulseIn(echoPin, HIGH);

  distance = duration * 0.034 / 2;


  Serial.print("Distance: ");

  Serial.print(distance);

  Serial.println(" cm");


  // 計算燈條長度

  int barLength = distance / 10;

  if (barLength > 8) barLength = 8; // 限制最大顯示長度為 8 格


  // 即時顯示燈條

  displayBar(barLength);


  delay(100); // 縮短更新間隔,確保動態測距

}


// 顯示燈條

void displayBar(int length) {

  lc.clearDisplay(0);


  for (int row = 0; row < length; row++) {

    lc.setRow(0, row, B11111111); // 顯示滿格燈條

  }

}


留言