/* uC: Attiny 25
	Fuse Settings for 4MHz external quarz:
	LOW  = 0xDC
	HIGH = 0xDF
	EXT  = 0xFF

	M.Berger: code developed starting from an example at www.mikrocontroller.net
*/

#define CLOCKPIN1	PB0
#define CLOCKPIN2	PB1
#define COUNTMAX	50
#define NFRAC		10000-24	// second term is for fine tuning

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

//Variablen für die Zeit
volatile uint16_t secfraction;
volatile uint8_t 	sekunde;
volatile uint8_t 	minute;
volatile uint8_t 	stunde;
volatile uint8_t	flag;
 
int main(void)
{
  // PORTB setzen
  DDRB |= (1<<CLOCKPIN1) | (1<<CLOCKPIN2);	// CLOCKPIN1, CLOCKPIN2 as output
  PORTB &= ~((1<<CLOCKPIN1) | (1<CLOCKPIN2));	// initialize both to 0
  // Timer 0 konfigurieren
  TCCR0A = (1<<WGM01); // CTC Modus
  TCCR0B |= (1<<CS01); // Prescaler 8
  // Sysclock / Prescaler / secfraction = COUNTMAX to finally achieve 1 Hz
  OCR0A = COUNTMAX;
 
  // Compare Interrupt erlauben
  TIMSK |= (1<<OCIE0A);
 
  sei();	// enable interrupts
  while(1)
  {
	if (flag) {	// another second is over...
		flag = 0;
		if (sekunde & 1) {
			PORTB |= (1<<CLOCKPIN1);	// pulse CLOCKPIN1 at odd seconds
		}
		else {
			PORTB |= (1<<CLOCKPIN2);	// pulse CLOCKPIN2 at even seconds
		} 
		_delay_ms(150);		// pulse width to be tested!
		PORTB &= ~((1<<CLOCKPIN1) | (1<<CLOCKPIN2));
	}
  }
}	// end of main
 
/*
Der Compare Interrupt Handler wird aufgerufen, wenn 
TCNT0 = OCR0A = COUNTMAX, d.h. genau alle 1 ms
*/
ISR (TIMER0_COMPA_vect)
{
  secfraction++;
  if(secfraction == NFRAC)
  {
    secfraction = 0;
    sekunde++;
    flag = 1;	
    if(sekunde == 60) { minute++; sekunde = 0; }
    if(minute == 60)  { stunde++; minute = 0; }
    if(stunde == 24)  stunde = 0;
  }
}
