/*
 * P2 Interrups.c
 *
 * Created: 11.11.2023 21:07:41
 * Author : Safak
 */ 

#include <avr/io.h>

#define F_CPU 16000000UL
#include <avr/interrupt.h>
#include <util/delay.h>
#include <stdbool.h>										// boolean type and values

#define LED0 PINB0
#define LED9 PINB1
#define SW1 PIND2
#define SW2 PIND3

volatile int activeLED = LED0;
volatile bool blink = true;

void setupPorts() {
	DDRB = 0xff;		
	PORTB = 0x00;
	
	DDRD = 0x00;
	PORTD |= (1 << SW1) | (1 << SW2); // Activate pull-up resistors

	// Falling edge of INT0 and INT1 generates an interrupt request
	EICRA |= (1 << ISC11) | (1 << ISC01);
	EIMSK |= (1 << INT0) | (1 << INT1);  // Enable external interrupt request
	sei(); // Set global interrupt enable
}

// SW1 is pressed
ISR(INT0_vect) {
	if (activeLED == LED0) {                                // if D0 is already on, switching from blink to steady light or vice versa
		blink = !blink;
	}
	else {                                                   // else D9 is on, turn off D9 and turn on D0
		PORTB = (1 << LED0);
	}
	
	activeLED = LED0;
}

// SW2 is pressed
ISR(INT1_vect) {
	if (activeLED == LED9) {
		blink = !blink;
	}
	else {
		PORTB = (1 << LED9);
	}
	
	activeLED = LED9;
}

int main(void) {
	setupPorts();
	while (1) {
		if (blink) {
			PORTB ^= (1 << activeLED); // Toggle active LED
		}
		_delay_ms(50);
	}
}