cancel
Showing results for 
Search instead for 
Did you mean: 

delay_ms not working

Wassini
Associate II

I have copied the delay_ms function from the standard Discovery code, but I can't get it to work. It seems that it is running precise 10x too slow, so "delay_ms(100)" gives me a 1 sec delay.

Can anyone explain what is wrong?

/* MAIN.C file
 * 
 * Copyright (c) 2002-2005 STMicroelectronics
 */
#include "stm8l15x.h"
 
 
/** DEFINES **/
#define GPIO_HIGH(a,b) 	 a->ODR|=b
#define GPIO_LOW(a,b)		 a->ODR&=~b
#define GPIO_TOGGLE(a,b) a->ODR^=b
 
/** STM8L Discovery board **/
#define LED_BLUE_PORT		GPIOC
#define LED_BLUE_PIN    GPIO_Pin_7
 
/** LOCAL PROTOTYPES **/
void delay_ms(u16);
 
 
/******************************
* MAIN
*/
main()
{
	GPIO_Init(LED_BLUE_PORT, LED_BLUE_PIN, GPIO_Mode_Out_PP_High_Fast);	
	GPIO_LOW(LED_BLUE_PORT, LED_BLUE_PIN);
 
	while (1)
	{
		GPIO_HIGH(LED_BLUE_PORT, LED_BLUE_PIN);
		delay_ms(100);
		GPIO_LOW(LED_BLUE_PORT, LED_BLUE_PIN);
		delay_ms(100);
	}
}
 
 
/******************************
* DELAY_MS
*/
void delay_ms(u16 n_ms)
{
/* Init TIMER 4 */
  CLK_PeripheralClockConfig(CLK_Peripheral_TIM4, ENABLE);
 
/* Init TIMER 4 prescaler: / (2^6) = /64 */
  TIM4->PSCR = 6;
 
/* HSI div by 1 --> Auto-Reload value: 16M / 64 = 1/4M, 1/4M / 1k = 250*/
  TIM4->ARR = 250;
  
/* Counter value: 2, to compensate the initialization of TIMER*/
  TIM4->CNTR = 2;
 
/* clear update flag */
  TIM4->SR1 &= ~TIM4_SR1_UIF;
 
/* Enable Counter */
  TIM4->CR1 |= TIM4_CR1_CEN;
 
  while(n_ms--)
  {
    while((TIM4->SR1 & TIM4_SR1_UIF) == 0) ;
    TIM4->SR1 &= ~TIM4_SR1_UIF;
  }
 
/* Disable Counter */
  TIM4->CR1 &= ~TIM4_CR1_CEN;
}

Thanks

Lars Bo Wassini

0 REPLIES 0