// Declare ESP32 GPIO pins
const int latchPin = 18; // Pin connected to ST_CP of all 74HC595s
const int clockPin = 19; // Pin connected to SH_CP of all 74HC595s
const int dataPin = 23; // Pin connected to DS of the first 74HC595
// Inverted seven-segment display codes for digits 0-9 (common anode)
const byte digitCodes[10] = {
0b11000000, // 0
0b11111001, // 1
0b10100100, // 2
0b10110000, // 3
0b10011001, // 4
0b10010010, // 5
0b10000010, // 6
0b11111000, // 7
0b10000000, // 8
0b10010000 // 9
};
int counter = 0; // Variable to hold the current count
unsigned long lastUpdate = 0; // Variable to track the last time the display was updated
const unsigned long interval = 1000; // Interval in milliseconds for the count update
void setup() {
pinMode(latchPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(dataPin, OUTPUT);
// Initialize display with 0
displayNumber(counter);
}
void loop() {
unsigned long currentMillis = millis();
// Check if it's time to update the display
if (currentMillis - lastUpdate >= interval) {
lastUpdate = currentMillis; // Save the last update time
counter++; // Increment the counter
if (counter > 999) { // Reset the counter after 999
counter = 0;
}
displayNumber(counter); // Update the display with the new count
}
}
void displayNumber(int number) {
int hundreds = number / 100; // Get the hundreds digit
int tens = (number / 10) % 10; // Get the tens digit
int units = number % 10; // Get the units digit
digitalWrite(latchPin, LOW);
// Shift out data for the hundreds digit (third display)
shiftOut(dataPin, clockPin, MSBFIRST, digitCodes[hundreds]);
// Shift out data for the tens digit (second display)
shiftOut(dataPin, clockPin, MSBFIRST, digitCodes[tens]);
// Shift out data for the units digit (first display)
shiftOut(dataPin, clockPin, MSBFIRST, digitCodes[units]);
digitalWrite(latchPin, HIGH); // Latch the data to the displays
}