/* DARLAN VIVIAN
   EDUARDO A. P. ALCHIERI
   THIAGO MEREGE PEREIRA */

/* I/O PORT B, DATA DIRECTION REGISTER (0 -> in, 1 -> out) */
#define DDRB    (*(volatile unsigned char *)(0x17 + 0x20))

/* I/O PORT B, DATA REGISTER */
#define PORTB   (*(volatile unsigned char *)(0x18 + 0x20))

/* SREG, STATUS REGISTER */
#define SREG (*(volatile unsigned char *)(0x5F))

/* I/O PORT D, INPUT PINS */
#define PIND   (*(volatile unsigned char *)(0x30))

/* GIMSK, IRQ */
#define GIMSK   (*(volatile unsigned char *)(0x5B))

/* MCUCR, MCU CONTROL REGISTER */
#define MCUCR (*(volatile unsigned char *)(0x55))
                                                                                
/* TIMER/COUNTER0 CONTROL REGISTER */
#define TCCR0 (*(volatile unsigned char *)(0x53))

/* TIMER COUNTER 0 */
#define TCNT0 (*(volatile unsigned char *)(0x52))

/* TIMSK, TIMER INTERRUPT MASK */
#define TIMSK (*(volatile unsigned char *)(0x59))

#define TIMER0 __vector_7

#define IRQ0 __vector_1

#define SIGNAL __attribute__ ((signal))

unsigned char count = 0x00;

int main(void) {
 
    /* Enable External Interrupt Request 0 */
    GIMSK = 0x40;
                                                                                
    /* Falling edge of INT 0 generates a IRQ */
    MCUCR = 0x02;
 
    /* Enable interrupts */
    SREG = 0x80;

    /* Stop the time counter */
    TCCR0 = 0x00;
  
    /* Enable timer/counter0 overflow interrupt*/
    TIMSK = 0x02;

    /* Set the whole port (all bits) to "output" */
    DDRB = 0xff;

    /* Turns off all PORTB leds */
    PORTB = 0xff;

    while(1) {}
        return 0;

}

void IRQ0 (void) SIGNAL;
                                                                                
void IRQ0 (void) {
    if(MCUCR == 0x02){
        
        /* Define timer/counter0 prescaling = CK/1024 */
        TCCR0 = 0x05;

        /* Rising edge of INT 0 generates a IRQ */
        MCUCR = 0x03;
    
    }else{

        /* Falling edge of INT 0 generates a IRQ */
        MCUCR = 0x02;

        /* Stop the time counter */
        TCCR0 = 0x00;

        /* Timer counter = 0 */
        TCNT0 = 0x00;
        
        /* Turns off all PORTB leds */
	PORTB = 0xff;        

	count = 0;
    }
}

void TIMER0 (void) SIGNAL;

void TIMER0 (void) {
    count++;

    if (count == 61) {
       /* Turns on all PORTB leds */
       PORTB = 0x00;
       
       count = 0;
       
       /* Stop the time counter */
       TCCR0 = 0x00;
   }
}