#include <avr/io.h>
#include <stdint.h>
#include <avr/interrupt.h>
/*****************************************Ausgänge***************/
#define a_auto			(1<<PB0)
#define a_hand			(1<<PB1)
#define a_pumpe			(1<<PB2)
/*****************************************TIMER******************/
#define timer_an		TCCR0 = (1<<CS01)
#define timer_aus		TCCR0 &= ~( (1<<CS00) | (1<<CS01) | (1<<CS02) )	
#define pumpe_zeit		2 
/****************************************Eingänge***************/
#define ein_hand		(PIND & (1<<PD5))
#define ein_sens		(PIND & (1<<PD4))

volatile unsigned int	einheit_overflow	= 0; 	// hier wird die Sekunde angenähert achtung Prescaler
volatile unsigned int	sekunde 			= 0;

ISR ( TIMER0_OVF_vect );
uint8_t laufZeit (void);


int main (void)	
{	
	TIMSK |= (1<<TOIE0);	

		DDRB = (1<<DDB0);		
							
	int taster = 0;
									
	while(1)
	{
/*********************************Auslösen Atumatikbetrieb***************************/
	
		if (!(ein_sens ))									// STK -- taste gedrückt
		{
			taster = 1;
		}
			
		while (taster == 1 )
		{
			PORTB &= ~( a_pumpe );
			sei();											//STK500 LED Pumpe an
			timer_an;
			DDRB = 0x05;			//<-- Warum muss ich hier ins DDRegister eingreifen??								

/***********Zusätzliches Blinken******************für bessere Erkannbarkeit*********/

			if ((( sekunde % 2 ) == 0 ) && (!( sekunde == 0 )))
			{
				PORTB = ( a_auto );						//STK -- LED aus
			}

			else
			{
				PORTB &= ~( a_auto );
			}

/******************************************Reset***************************************/

			if (( sekunde == laufZeit() ) || (!( ein_hand ))) // für STK 500 taste gedrückt
			{	
				taster = 0;
				sekunde = 0;
				timer_aus;
				cli();
			}

		}

/*********************************************Ruhezustand********************************/
		
		if ((taster == 0) && ( ein_hand ))			//STK NICHT gedrückt	
		{
		
			PORTB &= ~( a_auto );
			PORTB = ( a_pumpe ) | (a_hand);					//richtig
		}

/**********************************************Handbetrieb**************************/

		if (!( ein_hand ))									// STK -- taste gedrückt
		{	
			taster = 0;
			DDRB = 0x07;				//	<<--- 	Das DDB

			if ((taster == 0) && (!(PIND &  ( ein_hand ))))
			{
				PORTB &= ~(( a_pumpe ) | (a_hand));
				PORTB = ( a_auto );
			}				
		}
   }
	return 0;
}

ISR ( TIMER0_OVF_vect )
{
	einheit_overflow++;

	if ( einheit_overflow == 488 )
	{
		sekunde++;
		einheit_overflow = 0;
	}
}

uint8_t laufZeit (void)
{	
	uint8_t temp = ((pumpe_zeit * 60) / 15);	
	uint8_t dippBelegung = PIND & 0x0f; 		
	uint8_t MaxPumpenLauf =	dippBelegung * temp;	

	return MaxPumpenLauf;
}