/*
 * Intro to SW Design with Zynq-7000 and Vitis
 * Check buttons
 *
 */

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

#define TIMER_COUNTER_0	 0
#define LED_CHANNEL 1

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 Unified\n\r");

    // Initialize LEDs GPIO
	Status = XGpio_Initialize(&GpioLeds, XPAR_PERIPHERALS_AXI_GPIO_LEDS_BASEADDR);
	if (Status != XST_SUCCESS) {
		printf("ERROR: Initialization failed for LEDs GPIO \n\r");
		return XST_FAILURE;
	}
    /* Set the direction for all signals as inputs except the LED output */
	//XGpio_SetDataDirection(&GpioLeds, LED_CHANNEL, 0x00);
    XGpio_DiscreteWrite(&GpioLeds, LED_CHANNEL, 5);

    // Initialize Buttons GPIO
	Status = XGpio_Initialize(&GpioBtn, XPAR_PERIPHERALS_AXI_GPIO_BUTTONS_BASEADDR);
	if (Status != XST_SUCCESS) {
		printf("ERROR: Initialization failed for Buttons GPIO \n\r");
		return XST_FAILURE;
	}
    /* Set the direction for all signals as inputs except the SW input */
	//XGpio_SetDataDirection(&GpioBtns, 1, 0XFF);

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

	// Configure timer
	XTmrCtr_SetResetValue(&Timer, TIMER_COUNTER_0, XPAR_PERIPHERALS_AXI_TIMER_0_CLOCK_FREQUENCY / 100);
    //XTmrCtr_SetResetValue(&Timer, TIMER_COUNTER_0, 50000);
	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, LED_CHANNEL, 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 Unified \n\r");
    return 0;
}
