// ตัวอย่าง การเขียนโปรแกรมบอร์ด Multi Function - Arduino uno r3
// LAB31 HC-SR04 & TM1637
// ครูวิบูลย์ กัมปนาวราวรรณ จันทร์ 1 กรกฏาคม 2567
#include <TM1637.h>
const int CLK = 10;// Pin definitions for TM1637
const int DIO = 11;
TM1637 tm(CLK, DIO);// Create an instance of the TM1637 class
const int trigPin = 3;// Pin definitions for HC-SR04
const int echoPin = 2;
// Pin definitions for LED and Buzzer
const int ledPin = 13;
const int buzzerPin = 12;
long duration;
float distance;
void setup() {
Serial.begin(9600); // Initialize the Serial Monitor
// Set up the pins for the ultrasonic sensor, LED, and Buzzer
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
// Initialize the TM1637 display
tm.init();
tm.set(7); // Set brightness (0-7)
}
void loop() {
digitalWrite(trigPin, LOW); // Clear the trigPin
delayMicroseconds(5);
// Set the trigPin HIGH for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distance = duration * 0.034 / 2;
// Display the distance on Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Display the distance on the 7-segment display
int displayValue = (int)distance;
int digit1 = displayValue / 1000 % 10; // Thousands place
int digit2 = displayValue / 100 % 10; // Hundreds place
int digit3 = displayValue / 10 % 10; // Tens place
int digit4 = displayValue % 10; // Units place
tm.display(0, digit1); // Display thousands place
tm.display(1, digit2); // Display hundreds place
tm.display(2, digit3); // Display tens place
tm.display(3, digit4); // Display units place
// Control the LED and Buzzer based on distance
if (distance > 30) {
digitalWrite(ledPin, HIGH); // LED on
tone(buzzerPin, 1000); // Buzzer sound at 1kHz
} else {
digitalWrite(ledPin, LOW); // LED off
noTone(buzzerPin); // Buzzer off
}
delay(300);
}