#include "delay.h"
#include	"key.h"
#include "stm32f0xx_it.h"
#include "stm32f0xx_tim.h"
#define  u8  unsigned char
#define  u16  unsigned int

u8 keycnter=0;
u8 KeyPressFlag[4]={0};

static int8_t  fac_us=0;//us
static int16_t fac_ms=0;//ms

u8 Delay_cnter=0;
u16 SendDelay_Counter=0;
void TIM3_Init(void)//周期50ms
{
  TIM_TimeBaseInitTypeDef          TIM_TimeBaseInitStructure;
	NVIC_InitTypeDef                NVIC_InitStructure;

	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);  //tim3时钟使能,APB时钟48M
				 
	TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1; //分频系数为1
	TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up; //向上计数
	TIM_TimeBaseInitStructure.TIM_Period = 999;
	TIM_TimeBaseInitStructure.TIM_Prescaler = 959;  //定时500ms
	TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStructure);


	TIM_ClearITPendingBit(TIM3,TIM_IT_Update);
	TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE); //允许定时器3更新中断
	TIM_Cmd(TIM3,ENABLE); //使能定时器3       


	NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn; //定时器3中断
	NVIC_InitStructure.NVIC_IRQChannelPriority = 2; //优先级0
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_Init(&NVIC_InitStructure);
 
}

void TIM3_IRQHandler(void)
{
       
	if(TIM_GetITStatus(TIM3,TIM_IT_Update) != RESET) //溢出中断
	{
			HAL_TIM_PeriodElapsedCallback();
	}
	TIM_ClearITPendingBit(TIM3,TIM_IT_Update);  //清除中断标志位
}
void delay_init()	 
{
	SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK_Div8);//选择外部时钟  HCLK/8
	
	fac_us=SystemCoreClock/8000000;	//为系统时钟的1/8  
	fac_ms=(int16_t)fac_us*1000;//每个ms需要的systick时钟数 
	
}	
//延时Nus

void delay_us(int32_t nus)
{		
	int32_t temp;	    	 
	SysTick->LOAD=nus*fac_us; //时间加载	  		 
	SysTick->VAL=0x00;        //清空计数器
	SysTick->CTRL|=SysTick_CTRL_ENABLE_Msk ;          //开始倒数	 
	do
	{
		temp=SysTick->CTRL;
	}
	while(temp&0x01&&!(temp&(1<<16)));//等待时间到达   
	SysTick->CTRL&=~SysTick_CTRL_ENABLE_Msk;       //关闭计数器
	SysTick->VAL =0X00;       //清空计数器	 
}
//void delay_us(int32_t nus)
//{
//	for( ;nus>0;nus--)
//	{
//			__NOP();
//		
//	}
//}
//延时Nms

void delay_ms(int16_t nms)
{	 		  	  
	int32_t temp;		   
	SysTick->LOAD=(int32_t)nms*fac_ms;//时间加载(SysTick->LOAD为24bit)
	SysTick->VAL =0x00;           //清空计数器
	SysTick->CTRL|=SysTick_CTRL_ENABLE_Msk ;          //开始倒数  
	do
	{
		temp=SysTick->CTRL;
	}
	while(temp&0x01&&!(temp&(1<<16)));//等待时间到达   
	SysTick->CTRL&=~SysTick_CTRL_ENABLE_Msk;       //关闭计数器
	SysTick->VAL =0X00;       //清空计数器	  	    
} 


void HAL_TIM_PeriodElapsedCallback()
{
	
		static u8 key_up=1;//按键按松开标志
		Delay_cnter++;
		SendDelay_Counter++;
		if(key_up&&(KEY1==0||KEY2==0||KEY3==0 ||KEY4==0))
		{
			key_up=0;
			delay_ms(10);
			if(KEY1==0)	
			{
				// KeyPressFlag[0]=1;
				KeyPressFlag[3]=1;  //Enter  
			}
			else if(KEY2==0)
			{
				 KeyPressFlag[1]=1; //menu
			}					
			else if(KEY3==0)
			{
				KeyPressFlag[0]=1;  //right
			}					
			else if(KEY4==0)	
			{
				KeyPressFlag[2]=1;  //left
			}	
		}
		else if(KEY1==1 && KEY2==1 && KEY3==1 && KEY4==1)
		{
			 key_up=1; 
		}

}
