/**
  * @brief  This function handles TIM3 global interrupt request.
  * @param  None
  * @retval None
  */
void TIM3_IRQHandler(void)
{
	if((TIM_GetFlagStatus(TIM3,TIM_FLAG_Update)) != RESET )
	{
		TIM_ClearITPendingBit(TIM3, TIM_FLAG_Update);
	}
}
Example #2
0
void TIM1_UP_TIM10_IRQHandler(void) {
	if (TIM_GetFlagStatus(TIM1, TIM_FLAG_Update) == SET) {
		inter_TIM1_UP_TIM10();
		TIM_ClearFlag(TIM1, TIM_FLAG_Update);
	}else if(TIM_GetFlagStatus(TIM1, TIM_FLAG_Trigger) == SET) {
		inter_TIM1_start();
		TIM_ClearFlag(TIM1, TIM_FLAG_Trigger);
	}
	return;
}
int main(void)
{   uint8_t brilho=0,sentido=0,flag=0; //brilho é o pwm , sentido define se é para aumentar o brilho ou para diminuir, a flag conta os 2 segundos
   
    RCC_Config_HSE_PLL_Max(); //Configura o clk a 72Mhz
    rccconfig(); //activa os perifericos necessários, tim, gpios...
    //timer2config();  //timer2, flag_update a cada 500ms 
    //timer4config_toggle(); //timer 4 no modo toggle ligado diretamente ao led no GPIOB9
    timer4config_pwm(); // timer 4 no modo pwm (modo de contagem crescente) de forma a regular o brilho do led GPIOB9
    timer2config_gated(); //timer 2 modo gated  
timer3config_toggle();  //buzzer  
gpioconfig(); //iniciar a configuração dos GPIO's
  
    //lcd_info();
    while (1)
    {
        //1
        if(sentido==0){
						brilho=brilho+24;
				}
				else {
						brilho=brilho-24;
				}
		
        GPIO_WriteBit(GPIOB, GPIO_Pin_8, Bit_SET); //liga led
        while(TIM_GetFlagStatus(TIM2,TIM_FLAG_Update)==RESET); //o prog só avança quando ocorrer a flag_update
        TIM_ClearFlag(TIM2, TIM_FLAG_Update);//logo após deverificar a flag do timer é necessário limpar a flag para o timer continuar

        if(sentido==0){
						brilho=brilho+24;
				}
				else {
						brilho=brilho-24;
				}
		TIM_SetCompare4(TIM4, brilho);
       
        GPIO_WriteBit(GPIOB, GPIO_Pin_8, Bit_RESET); //desliga led 
        while(TIM_GetFlagStatus(TIM2,TIM_FLAG_Update)==RESET); //o prog só avança quando ocorrer a flag_update
        TIM_ClearFlag(TIM2, TIM_FLAG_Update);//logo após deverificar a flag do timer é necessário limpar a flag para o timer continuar
        
       	flag++;
				if(sentido==0&&flag==2){
						sentido=1;
						flag=0;
				}
				else if (sentido==1&&flag==2) {
						sentido=0;
						flag=0;
				}
        
            
         
        
    }
    return (0);
}
Example #4
0
/**
  * @brief  This function handles TIM3 global interrupt request.
  * @param  None
  * @retval None
  */
void TIM3_IRQHandler(void)
{
	/***********?????¡ä???D??************/  
	if((TIM_GetFlagStatus(TIM3,TIM_FLAG_Trigger)) != RESET )
	{
		TIM_ClearITPendingBit(TIM3, TIM_FLAG_Trigger);
		HallPLLCtrl();	

	}

	if((TIM_GetFlagStatus(TIM3,TIM_FLAG_CC4)) != RESET )
	{
		TIM_ClearITPendingBit(TIM3, TIM_FLAG_CC4);	
 	}
}
Example #5
0
/*******************************************************************************
* Function Name  : TIM3_IRQHandler
* Description    : This function handles TIM3 global interrupt request.
* Input          : None
* Output         : None
* Return         : None
*******************************************************************************/
void TIM3_IRQHandler(void)
{
  if(TIM_GetFlagStatus(TIM3,TIM_FLAG_CC1) != RESET)
  {
    TIM_ClearFlag(TIM3,TIM_FLAG_CC1);
  }
}
Example #6
0
void __attribute__((used)) TIM8_TRG_COM_TIM14_IRQHandler()
{
  uint16_t capureVal;
  uint16_t capureValDiff;
  portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;

  if (TIM_GetITStatus(CPPM_TIMER, TIM_IT_CC1) != RESET)
  {
    if (TIM_GetFlagStatus(CPPM_TIMER, TIM_FLAG_CC1OF) != RESET)
    {
      //TODO: Handle overflow error
    }

    capureVal = TIM_GetCapture1(CPPM_TIMER);
    capureValDiff = capureVal - prevCapureVal;
    prevCapureVal = capureVal;

    xQueueSendFromISR(captureQueue, &capureValDiff, &xHigherPriorityTaskWoken);

    captureFlag = true;
    TIM_ClearITPendingBit(CPPM_TIMER, TIM_IT_CC1);
  }

  if (TIM_GetITStatus(CPPM_TIMER, TIM_IT_Update) != RESET)
  {
    // Update input status
    isAvailible = (captureFlag == true);
    captureFlag = false;
    TIM_ClearITPendingBit(CPPM_TIMER, TIM_IT_Update);
  }
}
Example #7
0
void TIM1_BRK_UP_TRG_COM_IRQHandler(void)
{
  /* Clear TIM1 COM pending bit */
	if((TIM_GetFlagStatus(TIM1,TIM_FLAG_Update)) != RESET )
	{
		TIM_ClearITPendingBit(TIM1, TIM_FLAG_Update);	
	}

	if((TIM_GetFlagStatus(TIM1,TIM_FLAG_Break)) != RESET )
	{
		TIM_ClearITPendingBit(TIM1, TIM_FLAG_Break);
		Close_PWM();		
		TIM_CtrlPWMOutputs(TIM1, DISABLE);
		ShortI_Flag=1;
		Motor_State=WAIT;		
	}
}
Example #8
0
int main()
{
	uint16_t dataSeq[13] = {'L','E','T','S',' ','S','T','A','R','T','!','\n','\n'};
	int count;

	Setup_USART_NVIC();
	SetupUSART();
	Setup_CAN_NVIC();
	SetupCAN();
	SetupLED();
	SetupTIM();
	

	while(!startFlag);

	TIM_Cmd(TIM2, ENABLE);
	TIM_ClearFlag(TIM2, TIM_FLAG_Update);
	while(!TIM_GetFlagStatus(TIM2, TIM_FLAG_Update));
	TIM_Cmd(TIM2, DISABLE);

	GPIO_WriteBit(GPIOB, GPIO_Pin_14, Bit_SET);

	/*for(count = 0; count < 13; count++)
	{
		while(!USART_GetFlagStatus(USART2, USART_FLAG_TC));
		USART_SendData(USART2, dataSeq[count]);
		USART_ClearFlag(USART2, USART_FLAG_TC);
	}*/
			
	count = 0;
			
	while(1)
	{
		autoSendFlag = 0;
		
		CAN_Transmit(CAN1, &CanTxMsgStructure);
		
		//while(autoSendFlag < 2);
		
		TIM_Cmd(TIM3, ENABLE);
		TIM_ClearFlag(TIM3, TIM_FLAG_Update);
		while(!TIM_GetFlagStatus(TIM3, TIM_FLAG_Update));
		TIM_Cmd(TIM3, DISABLE);
	}
				
}
Example #9
0
void TIM5_IRQHandler(void)
{
//	int16_t temp = 0;
	if(TIM_GetFlagStatus(TIM5, TIM_FLAG_Update) == SET)
	{
		TIM_ClearITPendingBit(TIM5, TIM_IT_Update);
		
	}
}
Example #10
0
//获得runtime时间
//返回值:执行时间,单位:0.1ms,最大延时时间为定时器CNT值的2倍*0.1ms
//需要根据所移植到的MCU的定时器参数进行修改
u32 usmart_get_runtime(void)
{
    if(TIM_GetFlagStatus(TIM4,TIM_FLAG_Update)==SET)//在运行期间,产生了定时器溢出
    {
        usmart_dev.runtime+=0XFFFF;
    }
    usmart_dev.runtime+=TIM_GetCounter(TIM4);
    return usmart_dev.runtime;		//返回计数值
}
Example #11
0
static int int_tmr_match_get_flag( elua_int_resnum resnum, int clear )
{
  TIM_TypeDef *base = ( TIM_TypeDef* )timer[ resnum ];
  int status = TIM_GetFlagStatus( base, TIM_FLAG_CC1 );

  if( clear )
    TIM_ClearFlag( base, TIM_FLAG_CC1 );
  return status;
}
Example #12
0
//定时器3中断服务程序	 
void TIM3_IRQHandler(void)
{ 		    		  			    
//	if(TIM3->SR & 0X0001)		//溢出中断
	if(TIM_GetFlagStatus(TIM3, TIM_IT_Update) == SET)
	{
		//LED1 = !LED1;			    				   				     	    	
	}
//	TIM3->SR &= ~(1 << 0);		//清除中断标志位 
	TIM_ClearFlag(TIM3, TIM_IT_Update);	
}
Example #13
0
/*******************************************************************************
* Function Name  : TIM2_IRQHandler
* Description    : This function handles TIM2 global interrupt request.
* Input          : None
* Output         : None
* Return         : None
*******************************************************************************/
void TIM2_IRQHandler(void)
{
  debugpins_isr_set();
  if(TIM_GetFlagStatus(TIM2,TIM_FLAG_CC1) != RESET)
  {
    TIM_ClearFlag(TIM2,TIM_FLAG_CC1);
    //leds_error_toggle();
    bsp_timer_isr();
  }
  debugpins_isr_clr();
}
Example #14
0
void Delay_us(uint16_t us)
{
	TIM_SetCounter(TIM5, us);
	TIM_ClearFlag(TIM5, TIM_FLAG_Update);

	TIM_Cmd(TIM5, ENABLE);

	// 判断是否Underflow
	while (TIM_GetFlagStatus(TIM5, TIM_FLAG_Update) != SET)
	{
	}
}
Example #15
0
void ErrHandler(void)
{
	uint8_t steadyLight = 0;
	BitAction TmpBitVal = Bit_RESET;
	TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
	TIM_TimeBaseStructInit(&TIM_TimeBaseInitStructure);
	TIM_TimeBaseInitStructure.TIM_Prescaler = 65535;
	
	switch(errFlag)
	{
		case 0: /* Nothing happened */
			break;
		
		case 1: /* MODBUS error */
			TIM_TimeBaseInitStructure.TIM_Period = 600;
			break;
		
		case 2: /* Open in the sensor wire */
			TIM_TimeBaseInitStructure.TIM_Period = 300;
			break;
		
		default: /* Devilry... */
			steadyLight = 1;
	}
	
	//CanTxMsgStructure.Data[7] = errFlag;
	
	if(!steadyLight) /* Error light blinking */
	{
		TIM_DeInit(TIM2);
		TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStructure);
		
		while(errFlag)
		{
			if(TmpBitVal == Bit_RESET) TmpBitVal = Bit_SET;
			else TmpBitVal = Bit_RESET;
			GPIO_WriteBit(GPIOB, GPIO_Pin_15, TmpBitVal);
		
			TIM_Cmd(TIM2, ENABLE);
			TIM_ClearFlag(TIM2, TIM_FLAG_Update);
			while(!TIM_GetFlagStatus(TIM2, TIM_FLAG_Update));
			TIM_Cmd(TIM2, DISABLE);
		}
	}
	else /* Error light steady */
	{
		GPIO_WriteBit(GPIOB, GPIO_Pin_15, Bit_SET);
		while(errFlag);
	}
	
	GPIO_WriteBit(GPIOB, GPIO_Pin_15, Bit_RESET);
}
void f3d_delay_uS(uint16_t uS_count) {
  if (uS_count >= 1000) {
    uS_count = 1000;
  }
  uS_count *= 36; 
  TIM_Cmd(TIM3, DISABLE);
  TIM_SetCounter(TIM3,0);
  TIM_SetCompare1(TIM3,uS_count);
  TIM_Cmd(TIM3, ENABLE);  
  while (TIM_GetFlagStatus(TIM3,TIM_FLAG_CC1)==RESET);
  TIM_ClearFlag(TIM3,TIM_FLAG_CC1);
  TIM_Cmd(TIM3, DISABLE);  
} 
Example #17
0
void TIM4_IRQHandler(void) //ISR for timer 4
{
	if(TIM_GetFlagStatus(TIM4,TIM_FLAG_Update)==SET)
	//make sure that is an interrupt from timer 4
	{
		Count++; //increase count by 1
		count%=31; //0<=count<=30
		sprintf(LCD_buff,"%d",count);
		//put string “<count’s value>” to LCD_buff
		LCD_GLASS_Clear(); //clear LCD Screen
		LCD_GLASS_DisplayString((unsigned char*)LCD_buff);
// display LCD_buff string on LCD
		TIM_ClearFlag(TIM4,TIM_FLAG_Update);
		//clear timer 4 interrupt flag
	}
}
Example #18
0
void TIM6_IRQHandler(void)//1ms
{
	static uint16_t count_1s = 0;

	unsigned portBASE_TYPE uxSavedInterruptStatus;
	uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
//	
//	count++;
//	if(count >= 10) 
//	{
//		count = 0;
//		uip_timer++;		//uip计时器增加1
//	}
//	if(TIM6->SR & 0X0001)	//溢出中断
#if ARM_MINI
	scan_led();
#endif	
	if(TIM_GetFlagStatus(TIM6, TIM_IT_Update) == SET)
	{
		uip_timer++;		//uip计时器增加1
	}
	
	
	miliseclast = miliseclast + SWTIMER_INTERVAL;  // 1ms

	if(count_1s < 1000 / SWTIMER_INTERVAL)
	{
		count_1s++;
	}
	else	
	{
		run_time++;
#if 0
	  timestart++;
#endif
		count_1s = 0;
	}
	SilenceTime = SilenceTime + SWTIMER_INTERVAL;
	if(SilenceTime > 10000)	
	{
		SilenceTime = 0;
	}	
//	TIM6->SR &= ~(1 << 0);	//清除中断标志位 
	TIM_ClearFlag(TIM6, TIM_IT_Update);		
	
	portCLEAR_INTERRUPT_MASK_FROM_ISR(uxSavedInterruptStatus);
}
/****************************************************
濞肩偟鍊濋懘銏犵崯妤e灝鈻岄懘娑滃姶閹枫垺缍朤IM6閼存媽鍔忛棁鑼跺妿
閼淬垻娲搁懘鐘崇樅閾忓繗鍔嶉懘銏犵崯閹枫垺缍栭懘锕佸姸
閼淬垻娲告ご浣圭亣閾忓繗鍔嶉懘銏犵崯閹枫垺缍栭懘锕佸姸
閸椼倛绁    閼村啿鐎: 5ms閼搭亞顩╂ス鎾瑰妽閼存媽鍔忛棁鑼跺妿閹枫垹宕茬喊宀冨壔绾板矂妾伴懘锝堝姦闂囪尪鍔嗛懘鎵暠閹枫垹宕查懘铏亣閼搭亞顩╂ス鎾瑰妽PID瑜版洝鍔冮懘锝堝皸閹枫垹宕茬挧鍌濆壘閸椼倗娲哥喊宀冨箺缁傚嫮鍙呯喊宀冨壘PWM
*****************************************************/
void TIM6_DAC_IRQHandler(void)
{
	if (TIM_GetFlagStatus(TIM6,TIM_FLAG_Update)!= RESET)
	{
		//printf("asasdd\r\n");
		calcSpeed();
		MOT_SpeedPID(MOT1);
		MOT_SpeedPID(MOT2);
		MOT_SpeedPID(MOT3);
		printf("realspeed[0]=%d,PWM=%d\r\n",RealSpeed[0],MOT1_PID.PWM);
		printf("realspeed[1]=%d,PWM=%d\r\n",RealSpeed[1],MOT2_PID.PWM);
		printf("realspeed[2]=%d,PWM=%d\r\n",RealSpeed[2],MOT3_PID.PWM);
		printf("count=%d\r\n",TIM_GetCounter(TIM3));
	}
	TIM_ClearFlag(TIM6, TIM_FLAG_Update);
	TIM_ClearITPendingBit(TIM6,TIM_FLAG_Update);
}
Example #20
0
//----------------------------------------------------------------------------------------------------
void TIM1_IRQHandler(void)
{
	IENABLE;

	if(TIM_GetFlagStatus(TIM1, TIM_FLAG_OC1) == SET)
	{
		TIM_ClearFlag(TIM1, TIM_FLAG_OC1); // clear irq pending bit
		TIM1->OC1R += 200;    // Timerfreq is 200kHz, generate an interrupt every 1ms
		CountMilliseconds++;
		
		// generate SW Interrupt to make a regular timing 
		// independent from the mainloop at the lowest IRQ priority
		VIC_SWITCmd(EXTIT3_ITLine, ENABLE);	
	}

	IDISABLE;
}
Example #21
0
static uint16_t tempSpiCycle(uint16_t data) {
	volatile uint16_t value;
	// Put SPI port into receive mode, this starts SCK running continuously
	SPI_BiDirectionalLineConfig(SPI1,SPI_Direction_Rx);
	SPI_I2S_SendData(SPI1,data);
	// Wait for Rx flag to be set
	while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE) == RESET);
	// Stop the clock! Put SPI port into transmit mode
	SPI_BiDirectionalLineConfig(SPI1,SPI_Direction_Tx);
	// Read data
	value=SPI_I2S_ReceiveData(SPI1);
	// Arbitrary delay because there's no way of telling when the SPI has
	// finished
	TIM_Cmd(TIM2,DISABLE);
	TIM_SetCounter(TIM2,CYCLE_WAIT_TIME);
	TIM_ClearFlag(TIM2,TIM_FLAG_Update);
	TIM_Cmd(TIM2,ENABLE);
	while(!TIM_GetFlagStatus(TIM2,TIM_FLAG_Update));
	return value;
}
Example #22
0
void TIM3_IRQHandler()
{
	
//	int i;
//	i++;
//	TIM_ClearITPendingBit(TIM3, TIM3_IRQn);
//	TIM_ClearITPendingBit(TIM3, TIM_IT_CC1);
//	TIM_ClearITPendingBit(TIM3, TIM_IT_CC2);
//	TIM_ClearITPendingBit(TIM3, TIM_IT_CC3);
//	TIM_ClearITPendingBit(TIM3, TIM_IT_CC4);
//	if ( TIM_GetFlagStatus(TIM3, TIM_FLAG_CC1))
//	{i++;}
//	if ( TIM_GetFlagStatus(TIM3, TIM_FLAG_CC2))
//	{i++;}
//	if ( TIM_GetFlagStatus(TIM3, TIM_FLAG_CC3))
//	{i++;}
//	if ( TIM_GetFlagStatus(TIM3, TIM_FLAG_CC4))
//	{i++;}
	
	if (TIM_GetFlagStatus(TIM3, TIM_FLAG_CC1))//проверяем что прерывание вызвал канал 1
	{
		if ( TIM3->CCER & TIM_CCER_CC1P)
		{
			/*проверка что бы проходили циклически по записям массива фронтов*/
			if (modCounter_FallCounter[CH_1]== MEASURE_BUFFER - 1)
				modCounter_FallCounter[CH_1]=0;
			else
				modCounter_FallCounter[CH_1]++;

			modCounter_Falls[CH_1][modCounter_FallCounter[CH_1]] = TIM_GetCapture1(TIM3);//записываем значение захвата
			
			modCounter_WritePending |= CH_1_DOWN;//указываем что произошел новый спад
			TIM3->CCER &= ~(TIM_CCER_CC1P);// перенастройка канала на захват по нарастающему фронту
		}
		else
		{
			/*проверка что бы проходили циклически по записям массива фронтов*/
			if (modCounter_RiseCounter[CH_1]== MEASURE_BUFFER -1)
				modCounter_RiseCounter[CH_1]=0;
			else
				modCounter_RiseCounter[CH_1]++;
			
			modCounter_Rises[CH_1][modCounter_RiseCounter[CH_1]] = TIM_GetCapture1(TIM3);//записываем значение захвата

			modCounter_WritePending |= CH_1_UP;//указываем что произошел подьем
			TIM3->CCER |= TIM_CCER_CC1P;//перенастройка канала на захват по спадающему фронту
		}
		TIM_ClearITPendingBit(TIM3, TIM_Channel_1);
	}
	
	if ( TIM_GetFlagStatus(TIM3, TIM_FLAG_CC2))//проверяем что прерывание вызвал канал 2
	{
		if ( TIM3->CCER & TIM_CCER_CC2P)
		{
			/*проверка что бы проходили циклически по записям массива фронтов*/
			if (modCounter_FallCounter[CH_2]== MEASURE_BUFFER - 1)
				modCounter_FallCounter[CH_2]=0;
			else
				modCounter_FallCounter[CH_2]++;

			modCounter_Falls[CH_2][modCounter_FallCounter[CH_2]] = TIM_GetCapture2(TIM3);//записываем значение захвата
			
			modCounter_WritePending |= CH_2_DOWN;//указываем что произошел новый спад
			TIM3->CCER &= ~(TIM_CCER_CC2P);// перенастройка канала на захват по нарастающему фронту
		}
		else
		{
			/*проверка что бы проходили циклически по записям массива фронтов*/
			if (modCounter_RiseCounter[CH_2] == MEASURE_BUFFER -1)
				modCounter_RiseCounter[CH_2]=0;
			else
				modCounter_RiseCounter[CH_2]++;
			
			modCounter_Rises[CH_2][modCounter_RiseCounter[CH_2]] = TIM_GetCapture2(TIM3);//записываем значение захвата

			modCounter_WritePending |= CH_2_UP;//указываем что произошел подьем
			TIM3->CCER |= TIM_CCER_CC2P;//перенастройка канала на захват по спадающему фронту
		}
		TIM_ClearITPendingBit(TIM3, TIM_Channel_2);
	}
	
	if ( TIM_GetFlagStatus(TIM3, TIM_FLAG_CC3))//проверяем что прерывание вызвал канал 3
	{
		if ( TIM3->CCER & TIM_CCER_CC3P) //если канал 3 настроен на захват спадающего фронта 
		{
			/*проверка что бы проходили циклически по записям массива фронтов*/
			if (modCounter_FallCounter[CH_3]== MEASURE_BUFFER - 1)
				modCounter_FallCounter[CH_3]=0;
			else
				modCounter_FallCounter[CH_3]++;

			modCounter_Falls[CH_3][modCounter_FallCounter[CH_3]] = TIM_GetCapture3(TIM3);//записываем значение захвата
			
			modCounter_WritePending |= CH_3_DOWN;//указываем что произошел новый спад
			TIM3->CCER &= ~(TIM_CCER_CC3P);// перенастройка канала на захват по нарастающему фронту
		}
		else
		{
			/*проверка что бы проходили циклически по записям массива фронтов*/
			if (modCounter_RiseCounter[CH_3]== MEASURE_BUFFER -1)
				modCounter_RiseCounter[CH_3]=0;
			else
				modCounter_RiseCounter[CH_3]++;
			
			modCounter_Rises[CH_3][modCounter_RiseCounter[CH_3]] = TIM_GetCapture3(TIM3);//записываем значение захвата

			modCounter_WritePending |= CH_3_UP;//указываем что произошел подьем
			TIM3->CCER |= TIM_CCER_CC3P;//перенастройка канала на захват по спадающему фронту
		}
		TIM_ClearITPendingBit(TIM3, TIM_Channel_3);//сброс бита прерывания
		
	}
	if ( TIM_GetFlagStatus(TIM3, TIM_FLAG_CC4))//проверяем что прерывание вызвал канал 3
	{
		if ( TIM3->CCER & TIM_CCER_CC4P) //если канал 3 настроен на захват спадающего фронта 
		{
			/*проверка что бы проходили циклически по записям массива фронтов*/
			if (modCounter_FallCounter[CH_4]== MEASURE_BUFFER - 1)
				modCounter_FallCounter[CH_4]=0;
			else
				modCounter_FallCounter[CH_4]++;

			modCounter_Falls[CH_4][modCounter_FallCounter[CH_4]] = TIM_GetCapture4(TIM3);//записываем значение захвата
			
			modCounter_WritePending |= CH_4_DOWN;//указываем что произошел новый спад
			TIM3->CCER &= ~(TIM_CCER_CC4P);// перенастройка канала на захват по нарастающему фронту
		}
		else
		{
			/*проверка что бы проходили циклически по записям массива фронтов*/
			if (modCounter_RiseCounter[CH_4]== MEASURE_BUFFER -1)
				modCounter_RiseCounter[CH_4]=0;
			else
				modCounter_RiseCounter[CH_4]++;
			
			modCounter_Rises[CH_4][modCounter_RiseCounter[CH_4]] = TIM_GetCapture4(TIM3);//записываем значение захвата

			modCounter_WritePending |= CH_4_UP;//указываем что произошел подьемs
			TIM3->CCER |= TIM_CCER_CC4P;//перенастройка канала на захват по спадающему фронту
		}
		TIM_ClearITPendingBit(TIM3, TIM_Channel_4);//сброс бита прерывания
		
	}
	
	
}
Example #23
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
    uint32_t currentTime;

    /*!< At this stage the microcontroller clock setting is already configured,
         this is done through SystemInit() function which is called from startup
         file (startup_stm32f3xx.s) before to branch to application main.
         To reconfigure the default setting of SystemInit() function, refer to
          system_stm32f4xx.c file
    */

    systemReady = false;

    systemInit();

    systemReady = true;

    //evrPush(EVR_StartingMain, 0);

    /* Setup SysTick Timer for 1 msec interrupts.
       ------------------------------------------
      1. The SysTick_Config() function is a CMSIS function which configure:
         - The SysTick Reload register with value passed as function parameter.
         - Configure the SysTick IRQ priority to the lowest value (0x0F).
         - Reset the SysTick Counter register.
         - Configure the SysTick Counter clock source to be Core Clock Source (HCLK).
         - Enable the SysTick Interrupt.
         - Start the SysTick Counter.

      2. You can change the SysTick Clock source to be HCLK_Div8 by calling the
         SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK_Div8) just after the
         SysTick_Config() function call. The SysTick_CLKSourceConfig() is defined
         inside the misc.c file.

      3. You can change the SysTick IRQ priority by calling the
         NVIC_SetPriority(SysTick_IRQn,...) just after the SysTick_Config() function
         call. The NVIC_SetPriority() is defined inside the core_cm4.h file.

      4. To adjust the SysTick time base, use the following formula:

           Reload Value = SysTick Counter Clock (Hz) x  Desired Time base (s)

         - Reload Value is the parameter to be passed for SysTick_Config() function
         - Reload Value should not exceed 0xFFFFFF
     */

#if 1
    if (APRS_SLOT >= 0)
    {
        do
        {
/*
            while (!uartAvailable())
                sleep();
*/
        } while (!gpsDecode((char)uartRead()));

        next_aprs = millis() + 1000 * (APRS_PERIOD - (gps_seconds + APRS_PERIOD - APRS_SLOT) % APRS_PERIOD);
    }
    else
    {
        next_aprs = millis();
    }
#endif

    while (1)
    {
        //evrCheck();

        // Wait for sampling clock to overflow
        if (TIM_GetFlagStatus(TIM2, TIM_FLAG_Update) != RESET)
        {
            ;
        }

#if 1
        if ((int32_t)(millis() - next_aprs) >= 0)
        {
            getPos();
            aprsSend();
            next_aprs += APRS_PERIOD * 1000L;

            while(afskBusy())
                ;

            //sleep();
#if DEBUG_MODEM
            afskDebug();
#endif
        }

        //sleep();
#else

        ///////////////////////////////

        if (frame_500Hz)
        {
            frame_500Hz = false;

            currentTime       = micros();
            deltaTime500Hz    = currentTime - previous500HzTime;
            previous500HzTime = currentTime;

            executionTime500Hz = micros() - currentTime;
        }

        ///////////////////////////////

        if (frame_100Hz)
        {
            frame_100Hz = false;

            currentTime       = micros();
            deltaTime100Hz    = currentTime - previous100HzTime;
            previous100HzTime = currentTime;

            executionTime100Hz = micros() - currentTime;
        }

        ///////////////////////////////

        if (frame_50Hz)
        {
            frame_50Hz = false;

            currentTime      = micros();
            deltaTime50Hz    = currentTime - previous50HzTime;
            previous50HzTime = currentTime;

#if 1
            while (uartAvailable())
            {
                gpsDecode((char)uartRead());
            }
#endif

            executionTime50Hz = micros() - currentTime;
        }

        ///////////////////////////////

        if (frame_10Hz)
        {
            frame_10Hz = false;

            currentTime      = micros();
            deltaTime10Hz    = currentTime - previous10HzTime;
            previous10HzTime = currentTime;

            cliCom();

            executionTime10Hz = micros() - currentTime;
        }

        ///////////////////////////////

        if (frame_5Hz)
        {
            frame_5Hz = false;

            currentTime     = micros();
            deltaTime5Hz    = currentTime - previous5HzTime;
            previous5HzTime = currentTime;

            executionTime5Hz = micros() - currentTime;
        }

        ///////////////////////////////

        if (frame_1Hz)
        {
            frame_1Hz = false;

            currentTime     = micros();
            deltaTime1Hz    = currentTime - previous1HzTime;
            previous1HzTime = currentTime;

            if (execUp == true) {
                ledToggle(LED0);
#ifdef DEBUG_MODEM
                afskDebug();
#endif
            }

            if (execUp == false)
                execUpCount++;

            if ((execUpCount == 5) && (execUp == false))
            {
                execUp = true;
                ledOFF(LED0);
            }

            executionTime1Hz = micros() - currentTime;
        }
#endif
    }
}
/**
  * @brief  Calibration of External crystal oscillator auto(through Timer
  *   
  * @param  None
  * @retval : None
  */
void AutoClockCalibration(void)
{
  RCC_ClocksTypeDef ClockValue;
  uint16_t TimerPrescalerValue=0x0003;
  uint16_t CountWait;
  uint16_t DeviationInteger;
  uint32_t CalibrationTimer;
  float f32_Deviation;
  TIM_ICInitTypeDef  TIM_ICInitStructure;
  
  TIM_DeInit(TIM2);
  BKP_TamperPinCmd(DISABLE);
  BKP_RTCOutputConfig(BKP_RTCOutputSource_CalibClock);
  
  /* TIM2 configuration: PWM Input mode ------------------------
     The external signal is connected to TIM2 CH2 pin (PA.01),
     The Rising edge is used as active edge,
     The TIM2 CCR2 is used to compute the frequency value
     The TIM2 CCR1 is used to compute the duty cycle value
  ------------------------------------------------------------ */
  TIM_PrescalerConfig(TIM2,TimerPrescalerValue,TIM_PSCReloadMode_Immediate);
  TIM_ICInitStructure.TIM_Channel = TIM_Channel_2;
  TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;
  TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
  TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;
  TIM_ICInitStructure.TIM_ICFilter = 0x00;
  TIM_PWMIConfig(TIM2, &TIM_ICInitStructure);
  TIM_ICInit(TIM2, &TIM_ICInitStructure);
  /* Select the TIM2 Input Trigger: TI2FP2 */
  TIM_SelectInputTrigger(TIM2, TIM_TS_TI2FP2);
  /* Select the slave Mode: Reset Mode */
  TIM_SelectSlaveMode(TIM2, TIM_SlaveMode_Reset);
  /* Enable the Master/Slave Mode */
  TIM_SelectMasterSlaveMode(TIM2, TIM_MasterSlaveMode_Enable);
  /* TIM enable Counter */
  TIM_Cmd(TIM2, ENABLE);
  LCD_Clear(Blue2);
  LCD_DisplayString(Line4,Column1,"Please Wait.....");
  /* Wait for 2 seconds */
  CalibrationTimer = RTC_GetCounter();
 
  while((RTC_GetCounter() - CalibrationTimer) < 2)
  {
  }
  
  RCC_GetClocksFreq(&ClockValue);
  TimerFrequency=(ClockValue.PCLK1_Frequency * 2)/(TimerPrescalerValue+1);
   /* Enable the CC2 Interrupt Request */
  TIM_ITConfig(TIM2, TIM_IT_CC2, ENABLE);
   /* Wait for 2 seconds */
  CalibrationTimer = RTC_GetCounter();
  
  while((RTC_GetCounter() - CalibrationTimer) < 2)
  {
  }

  if(!(TIM_GetFlagStatus(TIM2, TIM_FLAG_CC1)))
   /* There is no signal at the timer TIM2 peripheral input */
  {
    LCD_Clear(Blue2);
    LCD_DisplayString(Line3,Column0,"Please connect wire");
    LCD_DisplayString(Line4,Column0,"link between PC13");
    LCD_DisplayString(Line5,Column0,"and PA1");
    LCD_DisplayString(Line7,Column0,"No calibration done");
  }
  else
  {
    /* Calulate Deviation in ppm  using the formula :
    Deviation in ppm = (Deviation from 511.968/511.968)*1 million*/
    if(f32_Frequency > 511.968)
    {
      f32_Deviation=((f32_Frequency-511.968)/511.968)*1000000;
    }
    else
    {
      f32_Deviation=((511.968-f32_Frequency)/511.968)*1000000;
    }
     DeviationInteger = (uint16_t)f32_Deviation;
    
    if(f32_Deviation >= (DeviationInteger + 0.5))
    {
      DeviationInteger = ((uint16_t)f32_Deviation)+1;
    }
    
   CountWait=0;

   /* Frequency deviation in ppm should be les than equal to 121 ppm*/
   if(DeviationInteger <= 121)
   {
     while(CountWait<128)
     {
       if(CalibrationPpm[CountWait] == DeviationInteger)
       break;
       CountWait++;
     }

     BKP_SetRTCCalibrationValue(CountWait);
     LCD_Clear(Blue2);
     LCD_DisplayString(Line4,Column1,"Calibration Value");
     LCD_DisplayChar(Line5,Column10,(CountWait%10)+0x30);
     CountWait=CountWait/10;
     LCD_DisplayChar(Line5,Column9,(CountWait%10)+0x30);
     CountWait=CountWait/10;
   
     if(CountWait>0)
     {
       LCD_DisplayChar(Line5,Column8,(CountWait%10)+0x30);
     }
   }
   else /* Frequency deviation in ppm is more than 121 ppm, hence calibration
           can not be done */
   {
     LCD_Clear(Blue2);
     LCD_DisplayString(Line3,Column1,"Out Of Calibration");
     LCD_DisplayString(Line4,Column4,"Range");
   }
  }
  
  BKP_RTCOutputConfig(BKP_RTCOutputSource_None);
  TIM_ITConfig(TIM2, TIM_IT_CC2, DISABLE);
  TIM_Cmd(TIM2, DISABLE);
  TIM_DeInit(TIM2);
  CalibrationTimer=RTC_GetCounter();
  
  /*  Wait for 2 seconds  */
  while((RTC_GetCounter() - CalibrationTimer) < 5)
  {
  }
  
  MenuInit();
}
Example #25
0
//Main function (execution starts here after startup file)
int main(void)
{
	int i;
	int e;
	uint16_t temperature;

	init_GPIO_pins();
	
	//Short delay during which we can communicate with MCU via debugger even if later user code causes error such as sleep state with no wakeup event that prevents debugger interface working
	//THIS MUST COME BEFORE ALL USER CODE TO ENSURE CHIPS CAN BE REPROGRAMMED EVEN IF THEY GET STUCK IN A SLEEP STATE LATER
	for (i = 0; i < 1000000; i++)
	{
		LED_on();
	}
	
	GPIO_Init_Mode(GPIOA,GPIO_Pin_0,GPIO_Mode_IN_FLOATING); //User button.
	GPIO_Init_Mode(GPIOC,GPIO_Pin_11,GPIO_Mode_IN_FLOATING); //Accelerometer interrupt.
	delay_init();
	LED_off();
	LCDINIT();
	home();
	clear();
	display(); //Surely some of these can be commented out.
	noCursor();
	noBlink();

	standby();

	UART_init();
	humidity_init();
	ADC_init();
	I2C_EEPROM();
	I2C_ACCEL_INIT();
	I2C_EE_LoadConfig();
	logging_timer_init();
	
//	I2C_EE_BufferWrite(Test_Buffer, EEPROM_WriteAddress1, 100);
//I2C_EE_BufferRead(buffer, 0, 100);

	/*while(1){
		if(LEDbyte==512){LEDbyte=1;}
		else {LEDbyte=LEDbyte<<1;}
		setLEDS();
		
	setCursor(0,1);
	temperature=getTemperature();
	writenumber( temperature/100);
	write('.');
	writenumber((temperature/10)%10);
		write(' ');

		write(0xDF);
	write('C');
	setCursor(0,0);
	writenumber(readhumidity(24)); //Needs real temperature
	write(' ');
	write('%');
	write('R');
	write('H');
		delay_ms(50);
		
		check_and_process_received_command();
		
	}*/
	//currentstate=UPLOADING;

	while(1)
	{
		switch (currentstate){
			
		case WAITING:
			if (GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_0)) //Polling is probably ok here, since the loop will be very very fast.
			{
				currentstate=LOGGING;
				clear();
				write('S');
				write('t');
				write('a');
				write('r');
				write('t');
				write('i');
				write('n');
				write('g');
				delay_ms(2000);
				clear();
				I2C_EE_StartLog();
				TIM4->CNT=0;
			}
			break;

		case LOGGING:
			if (GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_0)){currentstate=WAITING;I2C_EE_FinishLog();break;} //Polling is probably ok here, since the loop will be very very fast.
			LEDbyte|= 1<<8;
			setLEDS();
			if (TIM_GetFlagStatus(TIM3, TIM_FLAG_Update) != RESET)
			{
				TIM_ClearFlag(TIM3, TIM_IT_Update);
				temperature = getTemperature();
				LogBuffer[0]=(temperature>>8)&0xFF;
				LogBuffer[1]=temperature&0xFF;
				LogBuffer[2]=readhumidity(LogBuffer[0]);
				I2C_ACCEL_READ();
				I2C_EE_Log(LogBuffer);
				setCursor(0,1);
				writenumber(temperature/100);
				write('.');
				writenumber(temperature%100);
				write(' ');
				write(0xDF);
				write('C');
				write(' ');
				setCursor(0,0);
				writenumber(25); //Needs real temperature
				write(' ');
				write('%');
				write('R');
				write('H');
				write(' ');
				LEDbyte&= ~(1<<8);
				setLEDS();
			}
			break;
		
		case UPLOADING:
			currentstate=WAITING;
			I2C_EE_Upload();
			break;
		
		case ERASING:
			currentstate=WAITING;
			I2C_EE_Erase();
			break;
		
		case STREAMING:
			if (TIM_GetFlagStatus(TIM3, TIM_FLAG_Update) != RESET)
			{
				TIM_ClearFlag(TIM3, TIM_IT_Update);
				temperature = getTemperature();
				LogBuffer[0]=(temperature>>8)&0xFF;
				LogBuffer[1]=temperature&0xFF;
				LogBuffer[2]=readhumidity(LogBuffer[0]);
				I2C_ACCEL_READ();
//				I2C_EE_Log(LogBuffer);
				for (e=0;i<ENTRYBYTES;i++)
				{
					UART_send_byte(LogBuffer[e]);
				}
				setCursor(0,1);
				writenumber(temperature/100);
				write('.');
				writenumber(temperature%100);
				write(' ');
				write(0xDF);
				write('C');
				write(' ');
				setCursor(0,0);
				writenumber(25); //Needs real temperature
				write(' ');
				write('%');
				write('R');
				write('H');
				write(' ');
				LEDbyte&= ~(1<<8);
				setLEDS();
			}
		break;
		}
Example #26
0
/*******************************************************************************
* Function Name  : AutoClockCalibration
* Description    : Calibration of External crystal oscillator auto(through Timer
                   peripheral)
* Input          : None
* Output         : None
* Return         : None
*******************************************************************************/
void AutoClockCalibration(void)
{
  RCC_ClocksTypeDef ClockValue;
  u16 u16_TimerPrescalerValue=0x0003;
  u16 u16_CountWait;
  u16 u16_DeviationInteger;
  u32 u32_CalibrationTimer;
  float f32_Deviation;
  TIM_ICInitTypeDef  TIM_ICInitStructure;
  
  TIM_DeInit(TIM2);
  BKP_TamperPinCmd(DISABLE);
  BKP_RTCOutputConfig(BKP_RTCOutputSource_CalibClock);
  
  /* TIM2 configuration: PWM Input mode ------------------------
     The external signal is connected to TIM2 CH2 pin (PA.01),
     The Rising edge is used as active edge,
     The TIM2 CCR2 is used to compute the frequency value
     The TIM2 CCR1 is used to compute the duty cycle value
  ------------------------------------------------------------ */
  TIM_PrescalerConfig(TIM2,u16_TimerPrescalerValue,TIM_PSCReloadMode_Immediate);
  TIM_ICInitStructure.TIM_Channel = TIM_Channel_2;
  TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;
  TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
  TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;
  TIM_ICInitStructure.TIM_ICFilter = 0x00;
  TIM_PWMIConfig(TIM2, &TIM_ICInitStructure);
  TIM_ICInit(TIM2, &TIM_ICInitStructure);
  /* Select the TIM2 Input Trigger: TI2FP2 */
  TIM_SelectInputTrigger(TIM2, TIM_TS_TI2FP2);
  /* Select the slave Mode: Reset Mode */
  TIM_SelectSlaveMode(TIM2, TIM_SlaveMode_Reset);
  /* Enable the Master/Slave Mode */
  TIM_SelectMasterSlaveMode(TIM2, TIM_MasterSlaveMode_Enable);
  /* TIM enable u16_Counter */
  TIM_Cmd(TIM2, ENABLE);

  /* Wait for 2 seconds */
  u32_CalibrationTimer = RTC_GetCounter();
 
  while((RTC_GetCounter() - u32_CalibrationTimer) < 2)
  {
  }
  
  RCC_GetClocksFreq(&ClockValue);
  u32_TimerFrequency=(ClockValue.PCLK1_Frequency * 2)/(u16_TimerPrescalerValue+1);
   /* Enable the CC2 Interrupt Request */
  TIM_ITConfig(TIM2, TIM_IT_CC2, ENABLE);
   /* Wait for 2 seconds */
  u32_CalibrationTimer = RTC_GetCounter();
  
  while((RTC_GetCounter() - u32_CalibrationTimer) < 2)
  {
  }

  if(!(TIM_GetFlagStatus(TIM2, TIM_FLAG_CC1)))
   /* There is no signal at the timer TIM2 peripheral input */
  {

  }
  else
  {
    /* Calulate Deviation in ppm  using the formula :
    Deviation in ppm = (Deviation from 511.968/511.968)*1 million*/
    if(f32_Frequency > 511.968)
    {
      f32_Deviation=((f32_Frequency-511.968)/511.968)*1000000;
    }
    else
    {
      f32_Deviation=((511.968-f32_Frequency)/511.968)*1000000;
    }
     u16_DeviationInteger = (u16)f32_Deviation;
    
    if(f32_Deviation >= (u16_DeviationInteger + 0.5))
    {
      u16_DeviationInteger = ((u16)f32_Deviation)+1;
    }
    
   u16_CountWait=0;

   /* Frequency deviation in ppm should be les than equal to 121 ppm*/
   if(u16_DeviationInteger <= 121)
   {
     while(u16_CountWait<128)
     {
       if(u8_CalibrationPpm[u16_CountWait] == u16_DeviationInteger)
       break;
       u16_CountWait++;
     }

     BKP_SetRTCCalibrationValue(u16_CountWait);

     u16_CountWait=u16_CountWait/10;

     u16_CountWait=u16_CountWait/10;
   
     if(u16_CountWait>0)
     {

     }
   }
   else /* Frequency deviation in ppm is more than 121 ppm, hence calibration
           can not be done */
   {

   }
  }
  
  BKP_RTCOutputConfig(BKP_RTCOutputSource_None);
  TIM_ITConfig(TIM2, TIM_IT_CC2, DISABLE);
  TIM_Cmd(TIM2, DISABLE);
  TIM_DeInit(TIM2);
  u32_CalibrationTimer=RTC_GetCounter();
  
  /*  Wait for 2 seconds  */
  while((RTC_GetCounter() - u32_CalibrationTimer) < 5)
  {
  }
  
  //MenuInit();
}