// ghosts

#define dig1 5
#define dig2 A3
#define dig3 A4
#define dig4 A5

#define segA A2
#define segF A1
#define segB A0

#define segE 6
#define segD 7
#define segDP 8
#define segC 9
#define segG 10

byte segPinTable[8] = {segA, segB, segC, segD, segE, segF, segG, segDP};

byte digitTable[4] = {dig1, dig2, dig3, dig4};

byte segTable[10] = {0b00111111, 0b00000110, 0b01011011, 0b01001111, 0b01100110,
                     0b01101101, 0b01111101, 0b00000111, 0b01111111, 0b01101111};

volatile uint8_t dispNumber[4]={7,5,3,2};

void allSegmnentsOFF()
{
   for(int i = 0;i<8; i++) digitalWrite(segPinTable[i],LOW);
}

void segmentWrite(int n)
{
  allSegmnentsOFF();
  byte bitmask = 0b00000001;
  for(int i = 0;i<8; i++)
  {
     if(segTable[n] & bitmask) digitalWrite(segPinTable[i],HIGH);
     bitmask = bitmask << 1;
  }
}



// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin 13 as an output.
  for(int i=0;i<8;i++) pinMode(segPinTable[i],OUTPUT);

  for(int i=0;i<4;i++) pinMode(digitTable[i],OUTPUT);
  
  for(int i=0;i<4;i++) digitalWrite(digitTable[i], HIGH);

  cli();//stop interrupts
  TCCR1A = 0;
  TCNT1  = 0;
  TCCR1B = 0b00011011; // _BV(WGM12) | _BV(WGM13)  | _BV(CS10);// CTC mode2 (top=ICR1), prescaler 64
  ICR1  = 49999;  // =  200ms
  OCR1A = 0;      // kada se aktivira prekid
  TIMSK1 = 0b00000010; // _BV(OCIE1A); // enable int. on OCR1A
  sei();//allow interrupts
}

uint8_t digitCounter=0;

ISR(TIMER1_COMPA_vect)
{
  //digitalWrite(digitTable[(digitCounter+2)%3],HIGH);
  segmentWrite(dispNumber[digitCounter]);
  for(int i=0;i<3;i++) 
    if(digitCounter==i) digitalWrite(digitTable[i], LOW);
      else digitalWrite(digitTable[i], HIGH);

 
  digitCounter = (digitCounter + 1)%3;
}


// the loop function runs over and over again forever
void loop() {

}