1 /* mbed Microcontroller Library
2 * Copyright (c) 2006-2013 ARM Limited
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include "us_ticker_api.h"
18 #include "PeripheralNames.h"
19 #include "fsl_pit_hal.h"
20 #include "fsl_sim_hal.h"
21 #include "fsl_clock_manager.h"
23 static int us_ticker_inited = 0;
25 void us_ticker_init(void) {
26 if (us_ticker_inited) {
31 //Common for ticker/timer
33 CLOCK_SYS_EnablePitClock(0);
34 PIT_HAL_Enable(PIT_BASE);
35 CLOCK_SYS_GetFreq(kBusClock, &busClock);
38 PIT_HAL_SetTimerPeriodByCount(PIT_BASE, 0, busClock / 1000000 - 1);
39 PIT_HAL_SetTimerPeriodByCount(PIT_BASE, 1, 0xFFFFFFFF);
40 PIT_HAL_SetTimerChainCmd(PIT_BASE, 1, true);
41 PIT_HAL_StartTimer(PIT_BASE, 0);
42 PIT_HAL_StartTimer(PIT_BASE, 1);
45 PIT_HAL_SetTimerPeriodByCount(PIT_BASE, 2, busClock / 1000000 - 1);
46 PIT_HAL_SetTimerChainCmd(PIT_BASE, 3, true);
47 NVIC_SetVector(PIT3_IRQn, (uint32_t)us_ticker_irq_handler);
48 NVIC_EnableIRQ(PIT3_IRQn);
52 uint32_t us_ticker_read() {
53 if (!us_ticker_inited) {
57 return ~(PIT_HAL_ReadTimerCount(PIT_BASE, 1));
60 void us_ticker_disable_interrupt(void) {
61 PIT_HAL_SetIntCmd(PIT_BASE, 3, false);
64 void us_ticker_clear_interrupt(void) {
65 PIT_HAL_ClearIntFlag(PIT_BASE, 3);
68 void us_ticker_set_interrupt(timestamp_t timestamp) {
69 int delta = (int)(timestamp - us_ticker_read());
71 // This event was in the past:
72 us_ticker_irq_handler();
76 PIT_HAL_StopTimer(PIT_BASE, 3);
77 PIT_HAL_StopTimer(PIT_BASE, 2);
78 PIT_HAL_SetTimerPeriodByCount(PIT_BASE, 3, (uint32_t)delta);
79 PIT_HAL_SetIntCmd(PIT_BASE, 3, true);
80 PIT_HAL_StartTimer(PIT_BASE, 3);
81 PIT_HAL_StartTimer(PIT_BASE, 2);