#include <SPI.h>
int pinLatch = 4; // pin D0 (GPIO4) -> pin SH_CP của HC595
const int pinDigit[4] = {
26, // pin D4 (GPIO26) -> LED D4
25, // pin D3 (GPIO25) -> LED D3
33, // pin D2 (GPIO33) -> LED D2
32 // pin D1 (GPIO32) -> LED D1
};
// Binary codes for displaying 0 -> 9 on a 7-seg display
const int code[10] = {
0b1000000, // digit 0
0b1111001, // digit 1
0b0100100, // digit 2
0b0110000, // digit 3
0b0011001, // digit 4
0b0010010, // digit 5
0b0000010, // digit 6
0b1111000, // digit 7
0b0000000, // digit 8
0b0010000 // digit 9
};
int count = 0; // The number to display
int digits[4]; // 4 digits splitted from count
unsigned long last = 0; // Previous count time
// Mỗi bước sẽ tăng count từ 0 -> 9999 sau mỗi 300ms
void nextStep() {
unsigned long t = millis();
if (t - last > 300) {
if (count > 9999) count = 0;
else count++;
last = t;
}
}
// Mỗi count sẽ tách thành 4 digit
void countToDigits() {
int rem, div = count;
for (int i=0; i < 4; i++) {
rem = div % 10;
div /= 10;
digits[i] = rem;
}
}
void selectDigit(int di) {
for (int i=0; i < 4; i++)
if (i == di) digitalWrite(pinDigit[i], HIGH);
else digitalWrite(pinDigit[i], LOW);
}
void setup() {
// Khởi tạo SPI
SPI.begin();
// Thiết lập chế độ xuất cho pin Latch nối đến HC595
pinMode(pinLatch, OUTPUT);
for (int i=0; i < 4; i++)
pinMode(pinDigit[i], OUTPUT);
}
void loop() {
// Lấy 4 digit cần hiển thị từ count
countToDigits();
// Hiển thị từng digit
for (int i=0; i < 4; i++) {
selectDigit(4); // Tắt hết D1, D2, D3, D4
digitalWrite(pinLatch, LOW); // Tắt Latch
SPI.transfer(code[digits[i]]); // Đưa data vào HC595
digitalWrite(pinLatch, HIGH); // Bật Latch xuất ra các LED
selectDigit(i); // Bật D[i]
delay(2); // Delay ngắn để mắt lưu ảnh
}
// Chuẩn bị count kế tiếp
nextStep();
}