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"
20 static ticker_event_handler event_handler;
21 static ticker_event_t *head = NULL;
23 void us_ticker_set_handler(ticker_event_handler handler) {
26 event_handler = handler;
29 void us_ticker_irq_handler(void) {
30 us_ticker_clear_interrupt();
32 /* Go through all the pending TimerEvents */
35 // There are no more TimerEvents left, so disable matches.
36 us_ticker_disable_interrupt();
40 if ((int)(head->timestamp - us_ticker_read()) <= 0) {
41 // This event was in the past:
42 // point to the following one and execute its handler
43 ticker_event_t *p = head;
45 if (event_handler != NULL) {
46 event_handler(p->id); // NOTE: the handler can set new events
48 /* Note: We continue back to examining the head because calling the
49 * event handler may have altered the chain of pending events. */
51 // This event and the following ones in the list are in the future:
52 // set it as next interrupt and return
53 us_ticker_set_interrupt(head->timestamp);
59 void us_ticker_insert_event(ticker_event_t *obj, timestamp_t timestamp, uint32_t id) {
60 /* disable interrupts for the duration of the function */
63 // initialise our data
64 obj->timestamp = timestamp;
67 /* Go through the list until we either reach the end, or find
68 an element this should come before (which is possibly the
70 ticker_event_t *prev = NULL, *p = head;
72 /* check if we come before p */
73 if ((int)(timestamp - p->timestamp) < 0) {
76 /* go to the next element */
81 /* if we're at the end p will be NULL, which is correct */
84 /* if prev is NULL we're at the head */
87 us_ticker_set_interrupt(timestamp);
95 void us_ticker_remove_event(ticker_event_t *obj) {
98 // remove this object from the list
100 // first in the list, so just drop me
103 us_ticker_disable_interrupt();
105 us_ticker_set_interrupt(head->timestamp);
108 // find the object before me, then drop me
109 ticker_event_t* p = head;
111 if (p->next == obj) {
122 int us_ticker_get_next_timestamp(timestamp_t *timestamp) {
125 /* if head is NULL, there are no pending events */
128 *timestamp = head->timestamp;