#include <Arduino.h>
// 7 세그먼트에 표시할 숫자 패턴
const byte invertedNumbers[10] = {
 B00000011, // 0
 B10011111, // 1
 B00100101, // 2
 B00001101, // 3 
 B10011001, // 4
 B01001001, // 5
 B01000001, // 6
 B00011111, // 7
 B00000001, // 8
 B00001001 // 9
};
// 각 7 세그먼트에 연결된 디지털 핀
const byte segmentPins[8] = {8,7,6,5,4,3,2};
volatile unsigned int FndCnt;
// 각 7 세그먼트의 공통 핀에 연결된 트랜지스터의 베이스 핀
const byte transistorPins[4] = {9, 10, 11, 12};
// 타이머 인터럽트가 발생할 때 실행될 함수이다. 
ISR(TIMER2_OVF_vect) // 타이머/카운터 인터럽트 서비스 루틴, Tick time per 1mS!
{ 
 // 이 함수는 1ms 마다 호출된다. 
 static unsigned int cnt = 0; // cnt 선언
 cnt++;
 if (cnt == 10) {
 cnt = 0;
 FndCnt++; // 10mS 마다 증가
 if (FndCnt == 9999) // 7 세그먼트 LED 가 9999 일 경우
 { 
 FndCnt = 0; // 7 세그먼트 LED 를 0 으로 초기화
 } 
 } 
 TCNT2 |= 0x06;
} 
void setup() {
 // 각 핀을 출력으로 설정
 for (int i = 0; i < 8; i++) {
 pinMode(segmentPins[i], OUTPUT);
 } 
 for (int i = 0; i < 4; i++) {
 pinMode(transistorPins[i], OUTPUT);
 } 
 
 //타이머/카운터 인터럽트 발생 레지스터 설정 
 TCCR2A = 0x00;
 TCCR2B = 0x04; // 타이머 카운터 2 노멀 모드, 64 분주 
 TIMSK2 = 0x01; // 타이머 카운터 2 인터럽트 허용
 TCNT2 = 0x06; // 타이머 카운터 2 초기값: 6
 SREG = 0x80; // 인터럽트 허용
} 
void loop() {
 static int cnt = 0;
 static char j, k, l, m = 0;
 cnt++; // 7 세그먼트 LED 자리수 변경
 j = FndCnt / 1000; // 1000 의자리
 k = (FndCnt % 1000) / 100; // 100 의자리
 l = (FndCnt % 100) / 10; // 10 의자리
m = (FndCnt % 10); // 1 의자리
//1000 의 자리 공통 애노드 핀 On
 digitalWrite(transistorPins[0], HIGH);
 digitalWrite(transistorPins[1], LOW);
 digitalWrite(transistorPins[2], LOW);
 digitalWrite(transistorPins[3], LOW);
 displayNumber(m);
delay(5); // 휘도 유지를 위한 지연
//100 의 자리 공통 애노드 핀 On
 digitalWrite(transistorPins[0], LOW);
 digitalWrite(transistorPins[1], HIGH);
 digitalWrite(transistorPins[2], LOW);
 digitalWrite(transistorPins[3], LOW);
 displayNumber(l);
delay(5); // 휘도 유지를 위한 지연
//10 의 자리 공통 애노드 핀 On
 digitalWrite(transistorPins[0], LOW);
 digitalWrite(transistorPins[1], LOW);
 digitalWrite(transistorPins[2], HIGH);
 digitalWrite(transistorPins[3], LOW);
 displayNumber(k);
delay(5); // 휘도 유지를 위한 지연
//1 의 자리 공통 애노드 핀 On
 digitalWrite(transistorPins[0], LOW);
 digitalWrite(transistorPins[1], LOW);
 digitalWrite(transistorPins[2], LOW);
 digitalWrite(transistorPins[3], HIGH);
 displayNumber(j);
 delay(5); // 휘도 유지를 위한 지연
} 
void displayNumber(int num) { // 숫자 표시 함수
 // 각 트랜지스터를 활성화하여 특정 7 세그먼트 선택
 for (int j = 0; j < 8; j++) {
 digitalWrite(segmentPins[j], bitRead(invertedNumbers[num], j));
 } 
 delay(1); // 안정화 시간
}