/*
 * delay.c
 *
 *  Created on: Feb 16, 2012
 *      Author: tkl
 */

#include <stdint.h>
#include <stddef.h>

#ifdef BOARD_STM32_H103
#include "system_stm32f10x.h"
#endif
#ifdef BOARD_STM32F4_DISCOVERY
#include "system_stm32f4xx.h"
#endif

#include "delay.h"

#define CORRECT 30  // Korrekturfaktor (stm32-h103 - oszi ermittelt (startup code ???)

//-----------------------------------------------------------------------------
static uint32_t get_div_us(void) {
    uint32_t us = 1e6;
    uint32_t ret = SystemCoreClock;
    ret /= us;
    if(ret == 0) {
        ret += 1;
    }
    return ret;
}

//-----------------------------------------------------------------------------
static uint32_t get_div_ms(void) {
    uint32_t ms = 1e3;
    uint32_t ret = SystemCoreClock;
    ret /= ms;
    if(ret == 0) {
        ret += 1;
    }
    return ret;
}

//-----------------------------------------------------------------------------
void delay_us(uint32_t delay_us) {
    uint32_t div = get_div_us();
    volatile uint64_t count = delay_us * div / CORRECT;

    while(count > 0) {
        count--;
    }
}

//-----------------------------------------------------------------------------
void delay_ms(uint32_t delay_ms) {
    uint32_t div = get_div_ms();
    volatile uint64_t count = delay_ms * div / CORRECT;

    while(count > 0) {
        count--;
    }
}
