// Pins connected to the A-G segments of the 7-segment display
const int segmentPins[] = {D2, D3, D4, D5, D6, D7, D8};
// Turn-on patterns for digits 0 to 9 (common anode display)
// Bit order: G F E D C B A
// 0 = ON (LOW), 1 = OFF (HIGH)
const byte digitPatterns[10] = {
0b1000000, // 0
0b1111001, // 1
0b0100100, // 2
0b0110000, // 3
0b0011001, // 4
0b0010010, // 5
0b0000010, // 6
0b1111000, // 7
0b0000000, // 8
0b0010000 // 9
};
// Custom sequence of numbers to display
int numberSequence[] = {8, 1, 1, 4, 1, 4, 5, 1, 8};
// Total number of digits in the sequence
int sequenceLength = 9;
// Current index within the sequence
int sequenceIndex = 0;
void setup() {
Serial.begin(115200);
// Configures each display pin as an output and turns it off (HIGH in common anode)
for (int i = 0; i < 7; i++) {
pinMode(segmentPins[i], OUTPUT);
digitalWrite(segmentPins[i], HIGH);
}
Serial.println("7 SEGMENT DISPLAY - CLEAN AND COMMENTED");
Serial.println("Sequence: 8, 1, 1, 4, 1, 4, 5, 1, 8");
}
// Function that displays a number from 0 to 9 on the display
void displayDigit(int value) {
// If the value is out of range, everything is turned off
if (value < 0 || value > 9) {
for (int i = 0; i < 7; i++) {
digitalWrite(segmentPins[i], HIGH);
}
return;
}
// The binary pattern corresponding to the number is obtained
byte pattern = digitPatterns[value];
// The pattern is written to the display pins
// (In common anode: HIGH = off, LOW = on)
for (int i = 0; i < 7; i++) {
// Check if the i-th bit is 1 (Turn OFF) or 0 (Turn ON)
if ((pattern >> i) & 1) {
digitalWrite(segmentPins[i], HIGH); // Turn segment OFF
} else {
digitalWrite(segmentPins[i], LOW); // Turn segment ON
}
}
}
void loop() {
// Gets the current number from the sequence
int currentNumber = numberSequence[sequenceIndex];
// Displays it on the display
displayDigit(currentNumber);
// Prints the current state to the serial monitor
Serial.print("Number [");
Serial.print(sequenceIndex + 1);
Serial.print("/");
Serial.print(sequenceLength);
Serial.print("]: ");
Serial.println(currentNumber);
// Moves to the next number in the sequence
sequenceIndex++;
// If it reaches the end, it restarts
if (sequenceIndex >= sequenceLength) {
sequenceIndex = 0;
Serial.println("Restarting sequence");
}
// Waits 1 second before showing the next one
delay(1000);
}