// ==========================================================================
// buzzer.c
// (c) 2022, Aurel Dumitru
//
// Description:
// Buzzer control
// =========================================================================

#include "buzzer.h"
#include "main.h"
#include "utils.h"

/* Defines */
/* Data */
/* Private operations */

/* Public operations */
void Buzzer_MakeBeep(uint32_t Frequency, uint32_t Duration)
{
	// Enable the power supply
	GPIO_PinState PowerState = HAL_GPIO_ReadPin(EN_3V3S_GPIO_Port, EN_3V3S_Pin);
	HAL_GPIO_WritePin(EN_3V3S_GPIO_Port, EN_3V3S_Pin, GPIO_PIN_SET);

	uint32_t BuzActTime	= (1000000/Frequency);
	uint32_t Loops		= (Duration*1000)/BuzActTime;
	for (; Loops > 0; Loops--)
	{
		Utils_DelayMicroseconds(BuzActTime/2);
		HAL_GPIO_WritePin(EN_BUZ_GPIO_Port, EN_BUZ_Pin, GPIO_PIN_SET);
		Utils_DelayMicroseconds(BuzActTime/2);
		HAL_GPIO_WritePin(EN_BUZ_GPIO_Port, EN_BUZ_Pin, GPIO_PIN_RESET);
	}

	// Disable the power supply if required
	if (PowerState == GPIO_PIN_RESET)
		HAL_GPIO_WritePin(EN_3V3S_GPIO_Port, EN_3V3S_Pin, GPIO_PIN_RESET);
}
