// ตัวอย่าง การเขียนโปรแกรมบอร์ด Multi Function - Arduino uno r3
// LAB27 TM1637 S1INC S2DEC S3CLR
// ครูวิบูลย์ กัมปนาวราวรรณ เสาร์ 28 มิถุนายน 2567
#include <TM1637.h> //เรียกใช้ไลบรารี TM1637
int CLK = 10;//ขา CLK ของจอ TM1637 ต่อกับขา 10 ของ arduino
int DIO = 11;//DIO ของจอ TM1637 ต่อกับขาขา 11 ของ arduino
int buttonS1 = A1;// S1 เชื่อมต่อขา A1 ของ arduino
int buttonS2 = A2;// S2 เชื่อมต่อขา A2 ของ arduino
int buttonS3 = A3;// S3 เชื่อมต่อขา A3 ของ arduino
TM1637 tm(CLK, DIO);//สร้างอ็อบเจกต์ tm จากคลาส TM1637 ใช้ขา CLK และ DIO
int number = 0;//กำหนดตัวแปร number เก็บค่าที่จะแสดงบนจอ TM1637 โดยเริ่มต้นที่ 0
void setup() {
tm.init();//เรียกใช้เมธอด init() ของอ็อบเจกต์ tm เพื่อเริ่มต้นการทำงาน
tm.set(7);// ตั้งค่าความสว่างให้กับจอ TM1637 (0-7)
tm.display(0, 0); // แสดงค่าเริ่มต้น 0000
tm.display(1, 0);
tm.display(2, 0);
tm.display(3, 0);
//ให้ขาbuttonS1 inputใช้งานการ Pull-up resistor ภายใน
pinMode(buttonS1, INPUT_PULLUP);
pinMode(buttonS2, INPUT_PULLUP);
pinMode(buttonS3, INPUT_PULLUP);
}
void loop() {
// ตรวจสอบการกดปุ่ม S1
if (digitalRead(buttonS1) == LOW) {
delay(50); // รอเพื่อป้องกันการกดซ้ำ
if (digitalRead(buttonS1) == LOW) {
number++; //เพิ่มค่า
if (number > 9999) number = 9999;
displayNumber(number);// แสดงค่าตัวเลข
}
}
// ตรวจสอบการกดปุ่ม S2
if (digitalRead(buttonS2) == LOW) {
delay(50); // รอเพื่อป้องกันการกดซ้ำ
if (digitalRead(buttonS2) == LOW) {
number--;// ลดค่า
if (number < 0) number = 0;
displayNumber(number);
}
}
// ตรวจสอบการกดปุ่ม S3
if (digitalRead(buttonS3) == LOW) {
delay(50); // รอเพื่อป้องกันการกดซ้ำ
if (digitalRead(buttonS3) == LOW) {
number = 0;//เคลียร์ค่าเป็น 0
displayNumber(number);
}
}
}
// ฟังก์ชันแสดงตัวเลขบนจอ TM1637
void displayNumber(int num) {
// แยกตัวเลขในแต่ละหลัก
int digit4 = num / 1000 % 10; // หลักพัน
int digit3 = num / 100 % 10; // หลักร้อย
int digit2 = num / 10 % 10; // หลักสิบ
int digit1 = num % 10; // หลักหน่วย
// แสดงผลบนจอ TM1637
tm.display(0, digit4); // แสดงหลักพันที่ตำแหน่ง 0
tm.display(1, digit3); // แสดงหลักร้อยที่ตำแหน่ง 1
tm.display(2, digit2); // แสดงหลักสิบที่ตำแหน่ง 2
tm.display(3, digit1); // แสดงหลักหน่วยที่ตำแหน่ง 3
delay(10); // หน่วงเวลาเพื่อการแสดงผล
}