/*
 * Switch.c
 *
 * Created: Sat Jan 28 2023 15:21:38
 *  Author Chris
 */
// ============================================================================================
// Includes
#include "Switch.h"

#include "pico/time.h"
#include "pico/types.h"
#include "pico/stdlib.h"
#include "hardware/gpio.h"


// ============================================================================================
// Defines
#define SWITCH_GPIO					23

#define GPIO_IRQ_LEVEL_LOW 			1
#define GPIO_IRQ_LEVEL_HIGH			2
#define GPIO_IRQ_EDGE_FALL			4
#define GPIO_IRQ_EDGE_RISE			8

#define SWITCH_IDLE					1
#define SWITCH_PRESSED				0

#define DEBOUNCE_TIME_SWITCH_MS		300	


// ============================================================================================
// Variables
volatile uint32_t	_Debounce_Time_Switch_ms;
volatile bool		_Switch_Press_Occurred;


// ============================================================================================
// Function Declarations


/*******************************************************************
	Interrupt Service Routines
*******************************************************************/

// Interrupt Service Routine from Rotary Encoder also used for this one

// void ISR_Switch(uint gpio, uint32_t events)
// {
// 	if(gpio == SWITCH_GPIO)
// 	{
// 		uint32_t Current_Time_ms = to_ms_since_boot(get_absolute_time());

// 		if(Current_Time_ms < _Debounce_Time_Switch_ms)
// 		{
// 			return;
// 		}

// 		_Switch_Press_Occurred = true;

// 		_Debounce_Time_Switch_ms = Current_Time_ms + DEBOUNCE_TIME_SWITCH_MS;
// 	}
// }

/*******************************************************************
	Functions
*******************************************************************/
void Switch_Init(bool use_pullup)
{
	_Debounce_Time_Switch_ms 	= 0;
	_Switch_Press_Occurred 		= false;
	
	gpio_init(SWITCH_GPIO);	gpio_set_dir(SWITCH_GPIO, false);

	if(use_pullup == SWITCH_USE_INTERNAL_PULLUP) {
		gpio_pull_up(SWITCH_GPIO);
	}

	// ISR from Rotery Encoder used for Switch as well. See file Rotary_Encoder.c
	gpio_set_irq_enabled(SWITCH_GPIO, GPIO_IRQ_EDGE_FALL, true);
}

bool Switch_Press_Occurred(void)
{
	bool Return_Value = _Switch_Press_Occurred;

	_Switch_Press_Occurred = false;

	return Return_Value;
}


/*******************************************************************
	Internal Functions
*******************************************************************/