#include "sevenseg.h"

//-Timer---------------------------------------

volatile uint32_t systemClock = 0;

ISR(TIMER0_COMPA_vect) {
	systemClock++;  
}

uint32_t getSystemClock(){
	return systemClock;
}

void waitFor(uint32_t ms) {
	uint32_t endTime = getSystemClock() + ms;
	while (getSystemClock() != endTime);
}

//-Counter-------------------------------------

volatile int count = 0;

ISR(PCINT0_vect) {											// every 10ms interrupt is triggered
	
	if (!(PINB & (1<<PINB1))) {								// count down => sw1 is pressed
		if (count == 0) count = 100;						// 100 - 1 = 99
		count--;
	}
	
	if (!(PINB & (1<<PINB2))) {								// count up => sw2 is pressed
		if (count == 99) count = -1;						// -1 + 1 = 0
		count++;
	}
}

//-Display--------------------------------------

void display() {
	/*
	logical 0: on
	logical 1: off

		.gfe dcba	HEX	int
	0 : 1100 0000 = C0	192
	1 : 1111 1001 = F9	249
	2 : 1010 0100 = A4	164
	3 :	1011 0000 = 30	48
	4 : 1001 1001 = 99	153
	5 : 1001 0010 = 92	146
	6 : 1000 0010 = 82	130
	7 : 1111 1000 = F8	248
	8 : 1000 0000 = 80	128
	9 : 1001 0000 = 90	144
	*/

	int numbersAsSegments[10] = { 192, 249, 164, 48, 153, 146, 130, 248, 128, 144 };		// display number from 0 to 9;
	
	volatile int led_Einer = numbersAsSegments[(int) count % 10];							// Segmentanzeige für Zehner
	volatile int led_Zehner =  numbersAsSegments[(int) (count - (count % 10)) / 10];		// Segmentanzeige für Einer
	
	PORTD = led_Einer;
	//_delay_ms(10);
	waitFor(10);
	PORTB ^= (1 << PINB0);
	
	PORTD = led_Zehner;
	//_delay_ms(10);
	waitFor(10);
	PORTB ^= (1 << PINB0);
}
