// Define the pins for each segment (a to g) and the common cathode pin
const int segmentPins[7] = {2, 3, 4, 5, 6, 7, 8}; // Pins for a, b, c, d, e, f, g
const int commonCathodePin = 9; // Common cathode pin
// Define the numbers to display on the seven-segment display
const byte numbers[10] = {
B00111111, // 0
B00000110, // 1
B01011011, // 2
B01001111, // 3
B01100110, // 4
B01101101, // 5
B01111101, // 6
B00000111, // 7
B01111111, // 8
B01101111 // 9
};
void setup() {
// Set segment pins as outputs
for (int i = 0; i < 7; i++) {
pinMode(segmentPins[i], OUTPUT);
}
// Set common cathode pin as output
pinMode(commonCathodePin, OUTPUT);
}
void loop() {
// Count down from 9 to 0
for (int i = 9; i >= 0; i--) {
displayNumber(i);
delay(1000); // Display each number for 1 second
}
}
// Function to display a digit on the seven-segment display
void displayNumber(int num) {
// Turn off all segments
for (int i = 0; i < 7; i++) {
digitalWrite(segmentPins[i], LOW); // Start with all segments off
}
// Activate segments based on the number to be displayed
for (int i = 0; i < 7; i++) {
if (bitRead(numbers[num], i) == 1) {
digitalWrite(segmentPins[i], HIGH); // Turn on the segment if the bit is 1
} else {
digitalWrite(segmentPins[i], LOW); // Turn off the segment if the bit is 0
}
}
// Turn on the common cathode to display the digit
digitalWrite(commonCathodePin, LOW); // Common cathode pin is active low
delay(5); // Short delay to stabilize the display
digitalWrite(commonCathodePin, HIGH); // Turn off common cathode to refresh display
}