// https://forum.arduino.cc/t/help-with-tm1637-6-digit-and-button/1416196/279
// https://wokwi.com/projects/450964521677860865
const int N = 2 ; // display width
// Pin definitions for 7-segment display chosen for ease of routing in Wokwi
const int segmentPins[] = {7, 8, 6, 3, 4, 11, 2, 5}; // A, B, C, D, E, F, G, DP
const int digitPins[N] = {9, 10}; // Digit 1 (tens), Digit 2 (units)
// This matches 1:1 what appears on the display say show seconds 00 to 59
volatile byte displayImage[N] ;
// 7-segment display patterns for digits 0-9 (common cathode)
// Format: {A, B, C, D, E, F, G, DP}
const byte digitPatterns[10][8] = {
{1, 1, 1, 1, 1, 1, 0, 0}, // 0
{0, 1, 1, 0, 0, 0, 0, 0}, // 1
{1, 1, 0, 1, 1, 0, 1, 0}, // 2
{1, 1, 1, 1, 0, 0, 1, 0}, // 3
{0, 1, 1, 0, 0, 1, 1, 0}, // 4
{1, 0, 1, 1, 0, 1, 1, 0}, // 5
{1, 0, 1, 1, 1, 1, 1, 0}, // 6
{1, 1, 1, 0, 0, 0, 0, 0}, // 7
{1, 1, 1, 1, 1, 1, 1, 0}, // 8
{1, 1, 1, 1, 0, 1, 1, 0} // 9
};
void setup() {
Serial.begin(115200);
Serial.println("\nhi Mom!\n");
// test data
displayImage[0] = 4 ;
displayImage[1] = 6 ;
for (int i = 0; i < 8; i++) pinMode(segmentPins[i], OUTPUT ) ; // segments
for (int i = 0; i < N; i++) pinMode(digitPins[i], OUTPUT) ; // commons
cli();
// Reset Timer1 control registers
TCCR1A = 0;
TCCR1B = 0;
TCNT1 = 0;
OCR1A = 249; // Compare match value for 4ms
TCCR1B |= (1 << WGM12); // Turn on CTC mode (Clear Timer on Compare Match)
TCCR1B |= (1 << CS12); // Set prescaler to 256
TIMSK1 |= (1 << OCIE1A); // Enable timer compare interrupt
sei() ;
}
// we really don't need to do anything in the loop
void loop0(){}
int counter;
int speed;
void loop()
{
static unsigned long lastIncrement;
unsigned long now = millis();
int reading = analogRead(A0);
speed = map(reading, 0, 1023, 200, 0);
if (now - lastIncrement < 2000) return;
lastIncrement = now;
counter++;
noInterrupts();
displayImage[1] = counter % 10;
displayImage[0] = (counter / 10) % 10;
interrupts();
Serial.print(displayImage[0]); Serial.print(" ");
Serial.print(displayImage[1]); Serial.println("");
}
ISR(TIMER1_COMPA_vect)
{
static byte skipper;
if (skipper++ < speed) return;
skipper = 0;
// called every say 4 ms from timer1
static byte currentSegment = 0;
if (++currentSegment == 7) currentSegment = 0;
digitalWrite(digitPins[0], HIGH); // turn off digits to prevent ghosting
digitalWrite(digitPins[1], HIGH); // turn off digits to prevent ghosting
for (int seg = 0; seg < 8; seg++)
digitalWrite(segmentPins[seg], LOW);
digitalWrite(segmentPins[currentSegment], HIGH);
for (int dig = 0; dig < N; dig++) {
int digitValue = displayImage[dig];
if (digitPatterns[digitValue][currentSegment]) digitalWrite(digitPins[dig], LOW);
}
}