/*
 * sound.c
 *
 *  Created on: Apr 4, 2012
 *      Author: qwer1
 */

#include "sound.h"

//alarm sound at timer end
const U16 snd_program_stop[] = {
	SND_100MS(2400, 1), SND_100MS(0, 1), SND_100MS(2400, 1), SND_100MS(0, 1), SND_100MS(2400, 1), SND_100MS(0, 1), SND_100MS(2400, 1), SND_100MS(0, 1),
	SND_100MS(0, 2),
	SND_100MS(2400, 1), SND_100MS(0, 1), SND_100MS(2400, 1), SND_100MS(0, 1), SND_100MS(2400, 1), SND_100MS(0, 1), SND_100MS(2400, 1), SND_100MS(0, 1),
	SND_100MS(0, 2),
	SND_100MS(2400, 1), SND_100MS(0, 1), SND_100MS(2400, 1), SND_100MS(0, 1), SND_100MS(2400, 1), SND_100MS(0, 1), SND_100MS(2400, 1), SND_100MS(0, 1),
	SND_100MS(0, 10),
	0
};

TIM_TimeBaseInitTypeDef  sound_TIM_TimeBaseStructure;
TIM_OCInitTypeDef        sound_TIM_OCInitStructure;

void setup_sound(void) {
	// initialize GPIO
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_StructInit(&GPIO_InitStructure);
	GPIO_InitStructure.GPIO_Pin   = GPIO_Pin_0;
	GPIO_InitStructure.GPIO_Mode  = GPIO_Mode_AF_PP;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
	GPIO_Init(GPIOB, &GPIO_InitStructure);

	//enable TIM3 clock
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);

	setup_snd();
}

void snd_play( U16 freq ) {
	if (freq == 0) TIM_Cmd(TIM3, DISABLE);
	else {
		/* Time Base configuration */
		sound_TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
		sound_TIM_TimeBaseStructure.TIM_Prescaler = 0;
		sound_TIM_TimeBaseStructure.TIM_ClockDivision = 0;
		sound_TIM_TimeBaseStructure.TIM_Period = (F_CPU / (freq << 1)) - 1;// TimerPeriod;
		sound_TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;
		TIM_TimeBaseInit(TIM3, &sound_TIM_TimeBaseStructure);

		sound_TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Toggle;
		sound_TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
		sound_TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
		TIM_OC3Init(TIM3, &sound_TIM_OCInitStructure);

		TIM_Cmd(TIM3, ENABLE);
	}
}
