/*
 * Intro to SW Design with Zynq-7000 and Vitis
 * Adds Buttons check
 */

#include <stdio.h>
#include "xil_printf.h"
#include "xparameters.h"
#include "xgpio.h"
#include "xtmrctr.h"

#define TIMER_COUNTER_0	 0

int main()
{
    XGpio GpioLeds, GpioBtn;
    XTmrCtr Timer;
    int Status, Btn_val = 0, Btn_prev = 0;
    uint32_t i=0;

    // Start program
    printf("Intro to SW Design with Zynq-7000 and Vitis Classic\n\r");

    // Initialize LEDs GPIO
	Status = XGpio_Initialize(&GpioLeds, XPAR_GPIO_1_DEVICE_ID);
	if (Status != XST_SUCCESS) {
		printf("ERROR: Initialization failed for LEDs GPIO \n\r");
		return XST_FAILURE;
	}

	Status = XGpio_Initialize(&GpioBtn, XPAR_GPIO_0_DEVICE_ID);
	if (Status != XST_SUCCESS) {
		printf("ERROR: Initialization failed for BTN GPIO \n\r");
		return XST_FAILURE;
	}

	// Initialize Timer
	Status = XTmrCtr_Initialize(&Timer, XPAR_TMRCTR_0_DEVICE_ID);
	if (Status != XST_SUCCESS) {
		printf("ERROR: Initialization failed for LEDs GPIO \n\r");
		return XST_FAILURE;
	}

	// Configure timer
	XTmrCtr_SetResetValue(&Timer, TIMER_COUNTER_0, 500000);
	XTmrCtr_SetOptions(&Timer, TIMER_COUNTER_0, XTC_DOWN_COUNT_OPTION);
	// Start timer
	XTmrCtr_Start(&Timer, TIMER_COUNTER_0);

	while(Btn_val != 0x3) {
		if (XTmrCtr_IsExpired(&Timer, TIMER_COUNTER_0)) {
			// Restart timer
			XTmrCtr_Start(&Timer, TIMER_COUNTER_0);
			// Update LEDs
			XGpio_DiscreteWrite(&GpioLeds, 1, i++);
			if (i>63) {
				i=0;
				xil_printf(". ");
			}
		}
        Btn_val = XGpio_DiscreteRead(&GpioBtn, 1);
        if (Btn_val != Btn_prev){
                printf("\n\rBTN prev: %i - Now: %i", Btn_prev, Btn_val);
                Btn_prev = Btn_val;
            }

	}

	printf("\nEnding SW Design with Zynq-7000 and Vitis classic\n\r");
    return 0;
}
