#define F_CPU 8000000UL
#include <avr/io.h>
#include <util/delay.h>

// Global variables to store latched BCD values
uint8_t bcd1_latched = 0;
uint8_t bcd2_latched = 0;

// Segment decoder function
uint8_t getSegment(uint8_t bcd) {
    switch (bcd) {
        case 0x0: return 0b00111111; // 0
        case 0x1: return 0b00000110; // 1
        case 0x2: return 0b01011011; // 2
        case 0x3: return 0b01001111; // 3
        case 0x4: return 0b01100110; // 4
        case 0x5: return 0b01101101; // 5
        case 0x6: return 0b01111101; // 6
        case 0x7: return 0b00000111; // 7
        case 0x8: return 0b01111111; // 8
        case 0x9: return 0b01101111; // 9
        case 0xA: return 0b01110111; // A
        case 0xB: return 0b01111100; // B
        case 0xC: return 0b00111001; // C
        case 0xD: return 0b01011110; // D
        case 0xE: return 0b01111001; // E
        case 0xF: return 0b01110001; // F
        default: return 0b00000000; // Blank
    }
}

int main(void) {
    // Port initialization
    DDRC = 0x03; // PC0 and PC1: Kijelző választás
    DDRD = 0x00; // PD2: LE
    PORTD |= (1 << PD2); // Enable pull-up resistor on PD2
    DDRB = 0xFF; // PB0-PB7: Kijelző szegmensek

    uint8_t button_state = 0;
    uint8_t previous_button_state = 1; // Alapból magas szint

    while (1) {
        // Read button state
        button_state = (PIND & (1 << PD2)) == 0; // Low when button is pressed

        if (button_state && !previous_button_state) { // Detect falling edge
            // Update latched BCD values
            bcd1_latched = (PINC & 0x0F); // Read BCD1 from PC0-PC3
            bcd2_latched = (PINC >> 4) & 0x0F; // Read BCD2 from PC4-PC7

            // Update first display
            PORTC = (1 << PC0);                // Select first display
            PORTB = getSegment(bcd1_latched); // Send BCD1 to segments
            _delay_ms(5);

            // Update second display
            PORTC = (1 << PC1);                // Select second display
            PORTB = getSegment(bcd2_latched); // Send BCD2 to segments
            _delay_ms(5);
        }

        // Save button state for edge detection
        previous_button_state = button_state;
    }

    return 0;
}

