/*
 * This code utilizes the AVR libraries for I2C and UART communication.
 * Make sure to connect the SDA and SCL pins of the ATmega328P to the
 * corresponding pins of your I2C temperature sensor. Additionally, you might
 * need pull-up resistors for the I2C lines.
 */

#define LED_PIN PB5  // Define the pin connected to the LED

#include <avr/io.h>
#include <avr/sleep.h>
#include <avr/interrupt.h>
#include <avr/wdt.h>
#include <math.h>
#include <util/delay.h>

#include "MPU6050.h"
#include "i2c.h"
#include "uart.h"

void blink() {
    // Set the LED pin as output
    DDRB |= (1 << LED_PIN);

    while (1) {
        // Turn on the LED by setting the pin high
        PORTB |= (1 << LED_PIN);
        // Delay for 500 milliseconds
        _delay_ms(500);

        // Turn off the LED by setting the pin low
        PORTB &= ~(1 << LED_PIN);
        // Delay for 500 milliseconds
        _delay_ms(500);
    }
}

ISR(TIMER1_COMPA_vect) {
    UART_println("Interrupt detected!");

    // Clear the interrupt flag
    TIFR1 |= (1 << TOV1);
}

// We will use Timer1 for the interrupt
void configure_interrupt() {
    TCNT1 = 0; // Initialize the counter value to 0
    TCCR1A = 0; // Set the timer to normal mode
    TCCR1B = 0; // Set the timer to normal mode
    OCR1A = 31250; // 31250 for a 2 second delay, 15624 for a 1 second delay
    TCCR1B |= (1 << WGM12); // Set the timer to CTC mode
    TCCR1B |= (1 << CS02) | (1 << CS00); // Set the prescaler to 1024
    TIMSK1 |= (1 << OCIE1A); // Enable overflow interrupt
    sei(); // Enable global interrupts (cli() to disable)
}   

int main(void) {
    int16_t accel_data[3]; // Array to store accelerometer data (X, Y, Z)
    int32_t iteration = 0;

    // Set the watchdog timer to 8 seconds
    wdt_enable(WDTO_8S);
    
    // Set the sleep mode to idle
    set_sleep_mode(SLEEP_MODE_IDLE);

    initUART();

    // Clear the screen
    UART_println("\033[2J");
    UART_println("UART Initialized!");

    DEBUG("DEBUG mode enabled!");

    I2C_init(100000);
    UART_println("I2C Initialized!");

    MPU6050_Init();
    UART_println("MPU6050 Initialized!");

    while (1) {
        // Pat the dog
        wdt_reset();

        UART_println("%d Hello, World!", iteration++);

        // Read accelerometer data
        UART_println("Reading MPU6050 accelerometer data...");
        MPU6050_Read_Accel(accel_data);

        UART_println("Accelerometer (mg): X=%d, Y=%d, Z=%d", accel_data[0], accel_data[1], accel_data[2]);
        sleep_mode();
    }

    return 0;
}