/*
 * hal_DoorLock.c
 *
 *  Created on: Nov 26, 2011
 *      Author: RomanM
 */

#include "stm32f10x.h"
#include "hal_DoorLock.h"

/*
 * PWM initialization on PB7 (TIM4_CH2) and control loop inputs
 */
void hal_DoorLock_Init(void) {
	GPIO_InitTypeDef GPIO_InitStructure;
	TIM_TimeBaseInitTypeDef	TIM_TimeBaseStructure;
	TIM_OCInitTypeDef TIM_OCInitStructure;

	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB | RCC_APB2Periph_AFIO, ENABLE);

	/* Port initialization */
	GPIO_InitStructure.GPIO_Pin	= GPIO_Pin_7;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOB, &GPIO_InitStructure);

	/* Input initialization */
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10 | GPIO_Pin_11;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
	GPIO_Init(GPIOB, &GPIO_InitStructure);

	/* Timer initialization */
	TIM_TimeBaseStructure.TIM_Period = 65535;
	TIM_TimeBaseStructure.TIM_Prescaler = 0;
	TIM_TimeBaseStructure.TIM_ClockDivision = 0;
	TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
	TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);

	/* Timer output initialization */
	TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
	TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
	TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
	TIM_OCInitStructure.TIM_Pulse = 0;
	TIM_OC2Init(TIM4, &TIM_OCInitStructure);

	TIM_Cmd(TIM4, ENABLE);				// Counter enable
}

/*
 * Set duty of PWM
 */
void hal_DoorLock_SetVoltage(uint16_t value) {
	TIM4->CCR2 = value;
}

/*
 * Get status of control loop on door lock
 */
uint8_t hal_DoorLock_GetLockLoop(void) {
	return GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_11);
}

/*
 * Get status of control loop on door
 */
uint8_t hal_DoorLock_GetDoorLoop(void) {
	return GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_10);
}
