#include <Arduino.h>
#include <cstdint>
// Pin assignments for the 7 segments (a-g)
const int segmentPins[] = {2, 3, 4, 5, 6, 7, 8}; // D2 to D8
/**
* @brief Generates the 8-bit segment pattern for a Common Cathode 7-segment display.
* Bit Map: [dp, g, f, e, d, c, b, a] (Bit 7 is dp, Bit 0 is a)
* A '1' turns the segment ON (Common Cathode logic).
* @param decimal_digit An integer from 0 to 9.
* @return uint8_t The 8-bit pattern required to display the digit.
*/
uint8_t get_segment_pattern(int decimal_digit) {
// Start with all segments OFF (0b00000000). dp is ignored.
uint8_t pattern = 0x00;
switch (decimal_digit) {
case 0: // 0: a, b, c, d, e, f (0x3F)
pattern |= 0b00111111;
break;
case 1: // 1: b, c (0x06)
pattern |= 0b00000110;
break;
case 2: // 2: a, b, d, e, g (0x5B)
pattern |= 0b01011011;
break;
case 3: // 3: a, b, c, d, g (0x4F)
pattern |= 0b01001111;
break;
case 4: // 4: b, c, f, g (0x66)
pattern |= 0b01100110;
break;
case 5: // 5: a, c, d, f, g (0x6D)
pattern |= 0b01101101;
break;
case 6: // 6: a, c, d, e, f, g (0x7D)
pattern |= 0b01111101;
break;
case 7: // 7: a, b, c (0x07)
pattern |= 0b00000111;
break;
case 8: // 8: a, b, c, d, e, f, g (0x7F)
pattern |= 0b01111111;
break;
case 9: // 9: a, b, c, d, f, g (0x6F)
pattern |= 0b01101111;
break;
default:
pattern = 0x00; // All OFF for invalid input
}
return pattern;
}
/**
* @brief Writes the 8-bit pattern to the designated Arduino pins.
* @param pattern The 8-bit segment pattern to display.
*/
void displayDigit(uint8_t pattern) {
// Iterate through segments a (Bit 0) to g (Bit 6)
for (int i = 0; i < 7; i++) {
// Check if the i-th bit (segment) is ON (1)
if ((pattern >> i) & 0x01) {
// Segment ON for Common Cathode
digitalWrite(segmentPins[i], HIGH);
} else {
// Segment OFF
digitalWrite(segmentPins[i], LOW);
}
}
}
void setup() {
// Initialize all segment pins (D2 through D8) as outputs
for (int i = 0; i < 7; i++) {
pinMode(segmentPins[i], OUTPUT);
}
}
void loop() {
// Cycle through digits 0 to 9
for (int i = 0; i <= 9; i++) {
uint8_t segment_data = get_segment_pattern(i);
displayDigit(segment_data);
delay(500); // Pause for 500ms (as required)
}
}