Contiki 3.x
clock.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2012, Swedish Institute of Computer Science.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  * notice, this list of conditions and the following disclaimer in the
12  * documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the Institute nor the names of its contributors
14  * may be used to endorse or promote products derived from this software
15  * without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * This file is part of the Contiki operating system.
30  *
31  */
32  /**
33  * \brief This module contains AVR-specific code to implement
34  * the Contiki core clock functions.
35  *
36  * \author David Kopf <dak664@embarqmail.com> and others.
37  *
38 */
39 /** \addtogroup avr
40  * @{
41  */
42  /**
43  * \defgroup avrclock AVR clock implementation
44  * @{
45  */
46 /**
47  * \file
48  * This file contains AVR-specific code to implement the Contiki core clock functions.
49  *
50  */
51 /**
52  * These routines define the AVR-specific calls declared in /core/sys/clock.h
53  * CLOCK_SECOND is the number of ticks per second.
54  * It is defined through CONF_CLOCK_SECOND in the contiki-conf.h for each platform.
55  * The usual AVR defaults are 128 or 125 ticks per second, counting a prescaled CPU clock
56  * using the 8 bit timer0.
57  *
58  * clock_time_t is usually declared by the platform as an unsigned 16 bit data type,
59  * thus intervals up to 512 or 524 seconds can be measured with ~8 millisecond precision.
60  * For longer intervals the 32 bit clock_seconds() is available.
61  *
62  * Since a carry to a higer byte can occur during an interrupt, declaring them non-static
63  * for direct examination can cause occasional time reversals!
64  *
65  * clock-avr.h contains the specific setup code for each mcu.
66  */
67 #include "sys/clock.h"
68 #include "dev/clock-avr.h"
69 #include "sys/etimer.h"
70 
71 #include <avr/io.h>
72 #include <avr/interrupt.h>
73 
74 /* Two tick counters avoid a software divide when CLOCK_SECOND is not a power of two. */
75 #if CLOCK_SECOND && (CLOCK_SECOND - 1)
76 #define TWO_COUNTERS 1
77 #endif
78 
79 /* count is usually a 16 bit variable, although the platform can declare it otherwise */
80 static volatile clock_time_t count;
81 #if TWO_COUNTERS
82 /* scount is the 8 bit counter that counts ticks modulo CLOCK_SECONDS */
83 static volatile uint8_t scount;
84 #endif
85 /* seconds is available globally but non-atomic update during interrupt can cause time reversals */
86 volatile unsigned long seconds;
87 /* sleepseconds is the number of seconds sleeping since startup, available globally */
88 long sleepseconds;
89 
90 /* Set RADIOSTATS to monitor radio on time (must also be set in the radio driver) */
91 #if RF230BB && AVR_WEBSERVER
92 #define RADIOSTATS 1
93 #endif
94 
95 #if RADIOSTATS
96 static volatile uint8_t rcount;
97 volatile unsigned long radioontime;
98 extern uint8_t RF230_receive_on;
99 #endif
100 
101 /* Set RADIO_CONF_CALIBRATE_INTERVAL for periodic calibration of the PLL during extended radio on time.
102  * The RF230 data sheet suggests every 5 minutes if the temperature is fluctuating.
103  * At present the specified interval is ignored, and an 8 bit counter gives 256 second intervals.
104  * Actual calibration is done by the driver on the next transmit request.
105  */
106 #if RADIO_CONF_CALIBRATE_INTERVAL
107 extern volatile uint8_t rf230_calibrate;
108 static uint8_t calibrate_interval;
109 #endif
110 
111 /*---------------------------------------------------------------------------*/
112 /**
113  * Start the clock by enabling the timer comparison interrupts.
114  */
115 void
117 {
118  cli ();
119  OCRSetup();
120  sei ();
121 }
122 /*---------------------------------------------------------------------------*/
123 /**
124  * Return the tick counter. When 16 bit it typically wraps every 10 minutes.
125  * The comparison avoids the need to disable clock interrupts for an atomic
126  * read of the multi-byte variable.
127  */
128 clock_time_t
130 {
131  clock_time_t tmp;
132  do {
133  tmp = count;
134  } while(tmp != count);
135  return tmp;
136 }
137 /*---------------------------------------------------------------------------*/
138 /**
139  * Return seconds, default is time since startup.
140  * The comparison avoids the need to disable clock interrupts for an atomic
141  * read of the four-byte variable.
142  */
143 unsigned long
145 {
146  unsigned long tmp;
147  do {
148  tmp = seconds;
149  } while(tmp != seconds);
150  return tmp;
151 }
152 /*---------------------------------------------------------------------------*/
153 /**
154  * Set seconds, e.g. to a standard epoch for an absolute date/time.
155  */
156 void
157 clock_set_seconds(unsigned long sec)
158 {
159  seconds = sec;
160 }
161 /*---------------------------------------------------------------------------*/
162 /**
163  * Wait for a number of clock ticks.
164  */
165 void
166 clock_wait(clock_time_t t)
167 {
168  clock_time_t endticks = clock_time() + t;
169  if (sizeof(clock_time_t) == 1) {
170  while ((signed char )(clock_time() - endticks) < 0) {;}
171  } else if (sizeof(clock_time_t) == 2) {
172  while ((signed short)(clock_time() - endticks) < 0) {;}
173  } else {
174  while ((signed long )(clock_time() - endticks) < 0) {;}
175  }
176 }
177 /*---------------------------------------------------------------------------*/
178 /**
179  * Delay the CPU for up to 65535*(4000000/F_CPU) microseconds.
180  * Copied from _delay_loop_2 in AVR library delay_basic.h, 4 clocks per loop.
181  * For accurate short delays, inline _delay_loop_2 in the caller, use a constant
182  * value for the delay, and disable interrupts if necessary.
183  */
184 static inline void my_delay_loop_2(uint16_t __count) __attribute__((always_inline));
185 void
186 my_delay_loop_2(uint16_t __count)
187 {
188  __asm__ volatile (
189  "1: sbiw %0,1" "\n\t"
190  "brne 1b"
191  : "=w" (__count)
192  : "0" (__count)
193  );
194 }
195 void
196 clock_delay_usec(uint16_t howlong)
197 {
198 #if 0
199 /* Accurate delay at any frequency, but introduces a 64 bit intermediate
200  * and has a 279 clock overhead.
201  */
202  if(howlong<=(uint16_t)(279000000UL/F_CPU)) return;
203  howlong-=(uint16_t) (279000000UL/F_CPU);
204  my_delay_loop_2(((uint64_t)(howlong) * (uint64_t) F_CPU) / 4000000ULL);
205  /* Remaining numbers tweaked for the breakpoint CPU frequencies */
206  /* Add other frequencies as necessary */
207 #elif F_CPU>=16000000UL
208  if(howlong<1) return;
209  my_delay_loop_2((howlong*(uint16_t)(F_CPU/3250000)));
210 #elif F_CPU >= 12000000UL
211  if(howlong<2) return;
212  howlong-=(uint16_t) (3*12000000/F_CPU);
213  my_delay_loop_2((howlong*(uint16_t)(F_CPU/3250000)));
214 #elif F_CPU >= 8000000UL
215  if(howlong<4) return;
216  howlong-=(uint16_t) (3*8000000/F_CPU);
217  my_delay_loop_2((howlong*(uint16_t)(F_CPU/2000000))/2);
218 #elif F_CPU >= 4000000UL
219  if(howlong<5) return;
220  howlong-=(uint16_t) (4*4000000/F_CPU);
221  my_delay_loop_2((howlong*(uint16_t)(F_CPU/2000000))/2);
222 #elif F_CPU >= 2000000UL
223  if(howlong<11) return;
224  howlong-=(uint16_t) (10*2000000/F_CPU);
225  my_delay_loop_2((howlong*(uint16_t)(F_CPU/1000000))/4);
226 #elif F_CPU >= 1000000UL
227  if(howlong<=17) return;
228  howlong-=(uint16_t) (17*1000000/F_CPU);
229  my_delay_loop_2((howlong*(uint16_t)(F_CPU/1000000))/4);
230 #else
231  howlong >> 5;
232  if (howlong < 1) return;
233  my_delay_loop_2(howlong);
234 #endif
235 }
236 #if 0
237 /*---------------------------------------------------------------------------*/
238 /**
239  * Legacy delay. The original clock_delay for the msp430 used a granularity
240  * of 2.83 usec. This approximates that delay for values up to 1456 usec.
241  * (The largest core call in leds.c uses 400).
242  */
243 void
244 clock_delay(unsigned int howlong)
245 {
246  if(howlong<2) return;
247  clock_delay_usec((45*howlong)>>4);
248 }
249 #endif
250 /*---------------------------------------------------------------------------*/
251 /**
252  * Delay up to 65535 milliseconds.
253  * \param dt How many milliseconds to delay.
254  *
255  * Neither interrupts nor the watchdog timer is disabled over the delay.
256  * Platforms are not required to implement this call.
257  * \note This will break for CPUs clocked above 260 MHz.
258  */
259 void
260 clock_delay_msec(uint16_t howlong)
261 {
262 
263 #if F_CPU>=16000000
264  while(howlong--) clock_delay_usec(1000);
265 #elif F_CPU>=8000000
266  uint16_t i=996;
267  while(howlong--) {clock_delay_usec(i);i=999;}
268 #elif F_CPU>=4000000
269  uint16_t i=992;
270  while(howlong--) {clock_delay_usec(i);i=999;}
271 #elif F_CPU>=2000000
272  uint16_t i=989;
273  while(howlong--) {clock_delay_usec(i);i=999;}
274 #else
275  uint16_t i=983;
276  while(howlong--) {clock_delay_usec(i);i=999;}
277 #endif
278 }
279 /*---------------------------------------------------------------------------*/
280 /**
281  * Adjust the system current clock time.
282  * \param dt How many ticks to add
283  *
284  * Typically used to add ticks after an MCU sleep
285  * clock_seconds will increment if necessary to reflect the tick addition.
286  * Leap ticks or seconds can (rarely) be introduced if the ISR is not blocked.
287  */
288 void
289 clock_adjust_ticks(clock_time_t howmany)
290 {
291  uint8_t sreg = SREG;cli();
292  count += howmany;
293 #if TWO_COUNTERS
294  howmany+= scount;
295 #endif
296  while(howmany >= CLOCK_SECOND) {
297  howmany -= CLOCK_SECOND;
298  seconds++;
299  sleepseconds++;
300 #if RADIOSTATS
301  if (RF230_receive_on) radioontime += 1;
302 #endif
303  }
304 #if TWO_COUNTERS
305  scount = howmany;
306 #endif
307  SREG=sreg;
308 }
309 /*---------------------------------------------------------------------------*/
310 /* This it the timer comparison match interrupt.
311  * It maintains the tick counter, clock_seconds, and etimer updates.
312  *
313  * If the interrupts derive from an external crystal, the CPU instruction
314  * clock can optionally be phase locked to it. This allows accurate rtimer
315  * interrupts for strobe detection during radio duty cycling.
316  * Phase lock is accomplished by adjusting OSCCAL based on the phase error
317  * since the last interrupt.
318  */
319 /*---------------------------------------------------------------------------*/
320 #if defined(DOXYGEN)
321 /** \brief ISR for the TIMER0 or TIMER2 interrupt as defined in
322  * clock-avr.h for the particular MCU.
323  */
324 void AVR_OUTPUT_COMPARE_INT(void);
325 #else
327 {
328  count++;
329 #if TWO_COUNTERS
330  if(++scount >= CLOCK_SECOND) {
331  scount = 0;
332 #else
333  if(count%CLOCK_SECOND==0) {
334 #endif
335  seconds++;
336 
337 #if RADIO_CONF_CALIBRATE_INTERVAL
338  /* Force a radio PLL frequency calibration every 256 seconds */
339  if (++calibrate_interval==0) {
340  rf230_calibrate=1;
341  }
342 #endif
343 
344  }
345 
346 #if RADIOSTATS
347  /* Sample radio on time. Less accurate than ENERGEST but a smaller footprint */
348  if (RF230_receive_on) {
349  if (++rcount >= CLOCK_SECOND) {
350  rcount=0;
351  radioontime++;
352  }
353  }
354 #endif
355 
356 #if F_CPU == 0x800000 && USE_32K_CRYSTAL
357 /* Special routine to phase lock CPU to 32768 watch crystal.
358  * We are interrupting 128 times per second.
359  * If RTIMER_ARCH_SECOND is a multiple of 128 we can use the residual modulo
360  * 128 to determine whether the clock is too fast or too slow.
361  * E.g. for 8192 the phase should be constant modulo 0x40
362  * OSCCAL is started in the lower range at 90, allowed to stabilize, then
363  * rapidly raised or lowered based on the phase comparison.
364  * It gives less phase noise to do this every tick and doesn't seem to hurt anything.
365  */
366 #include "rtimer-arch.h"
367 {
368 volatile static uint8_t lockcount;
369 volatile static int16_t last_phase;
370 volatile static uint8_t osccalhigh,osccallow;
371  if (seconds < 60) { //give a minute to stabilize
372  if(++lockcount >= 8192UL*128/RTIMER_ARCH_SECOND) {
373  lockcount=0;
374  rtimer_phase = TCNT3 & 0x0fff;
375  if (seconds < 2) OSCCAL=100;
376  if (last_phase > rtimer_phase) osccalhigh=++OSCCAL; else osccallow=--OSCCAL;
377  last_phase = rtimer_phase;
378  }
379  } else {
380  uint8_t error = (TCNT3 - last_phase) & 0x3f;
381  if (error == 0) {
382  } else if (error<32) {
383  OSCCAL=osccallow-1;
384  } else {
385  OSCCAL=osccalhigh+1;
386  }
387  }
388 }
389 #endif
390 
391 #if 1
392 /* gcc will save all registers on the stack if an external routine is called */
393  if(etimer_pending()) {
395  }
396 #else
397 /* doing this locally saves 9 pushes and 9 pops, but these etimer.c and process.c variables have to lose the static qualifier */
398  extern struct etimer *timerlist;
399  extern volatile unsigned char poll_requested;
400 
401 #define PROCESS_STATE_NONE 0
402 #define PROCESS_STATE_RUNNING 1
403 #define PROCESS_STATE_CALLED 2
404 
405  if (timerlist) {
406  if(etimer_process.state == PROCESS_STATE_RUNNING || etimer_process.state == PROCESS_STATE_CALLED) {
407  etimer_process.needspoll = 1;
408  poll_requested = 1;
409  }
410  }
411 #endif
412 }
413 #endif /* defined(DOXYGEN) */
414 /*---------------------------------------------------------------------------*/
415 /* Debugging aids */
416 
417 #ifdef HANDLE_UNSUPPORTED_INTERRUPTS
418 /* Ignore unsupported interrupts, optionally hang for debugging */
419 /* BADISR is a gcc weak symbol that matches any undefined interrupt */
420 ISR(BADISR_vect) {
421 //static volatile uint8_t x;while (1) x++;
422 }
423 #endif
424 #ifdef HANG_ON_UNKNOWN_INTERRUPT
425 /* Hang on any unsupported interrupt */
426 /* Useful for diagnosing unknown interrupts that reset the mcu.
427  * Currently set up for 12mega128rfa1.
428  * For other mcus, enable all and then disable the conflicts.
429  */
430 static volatile uint8_t x;
431 ISR( _VECTOR(0)) {while (1) x++;}
432 ISR( _VECTOR(1)) {while (1) x++;}
433 ISR( _VECTOR(2)) {while (1) x++;}
434 ISR( _VECTOR(3)) {while (1) x++;}
435 ISR( _VECTOR(4)) {while (1) x++;}
436 ISR( _VECTOR(5)) {while (1) x++;}
437 ISR( _VECTOR(6)) {while (1) x++;}
438 ISR( _VECTOR(7)) {while (1) x++;}
439 ISR( _VECTOR(8)) {while (1) x++;}
440 ISR( _VECTOR(9)) {while (1) x++;}
441 ISR( _VECTOR(10)) {while (1) x++;}
442 ISR( _VECTOR(11)) {while (1) x++;}
443 ISR( _VECTOR(12)) {while (1) x++;}
444 ISR( _VECTOR(13)) {while (1) x++;}
445 ISR( _VECTOR(14)) {while (1) x++;}
446 ISR( _VECTOR(15)) {while (1) x++;}
447 ISR( _VECTOR(16)) {while (1) x++;}
448 ISR( _VECTOR(17)) {while (1) x++;}
449 ISR( _VECTOR(18)) {while (1) x++;}
450 ISR( _VECTOR(19)) {while (1) x++;}
451 //ISR( _VECTOR(20)) {while (1) x++;}
452 //ISR( _VECTOR(21)) {while (1) x++;}
453 ISR( _VECTOR(22)) {while (1) x++;}
454 ISR( _VECTOR(23)) {while (1) x++;}
455 ISR( _VECTOR(24)) {while (1) x++;}
456 //ISR( _VECTOR(25)) {while (1) x++;}
457 ISR( _VECTOR(26)) {while (1) x++;}
458 //ISR( _VECTOR(27)) {while (1) x++;}
459 ISR( _VECTOR(28)) {while (1) x++;}
460 ISR( _VECTOR(29)) {while (1) x++;}
461 ISR( _VECTOR(30)) {while (1) x++;}
462 ISR( _VECTOR(31)) {while (1) x++;}
463 //ISR( _VECTOR(32)) {while (1) x++;}
464 ISR( _VECTOR(33)) {while (1) x++;}
465 ISR( _VECTOR(34)) {while (1) x++;}
466 ISR( _VECTOR(35)) {while (1) x++;}
467 //ISR( _VECTOR(36)) {while (1) x++;}
468 ISR( _VECTOR(37)) {while (1) x++;}
469 //ISR( _VECTOR(38)) {while (1) x++;}
470 ISR( _VECTOR(39)) {while (1) x++;}
471 ISR( _VECTOR(40)) {while (1) x++;}
472 ISR( _VECTOR(41)) {while (1) x++;}
473 ISR( _VECTOR(42)) {while (1) x++;}
474 ISR( _VECTOR(43)) {while (1) x++;}
475 ISR( _VECTOR(44)) {while (1) x++;}
476 ISR( _VECTOR(45)) {while (1) x++;}
477 ISR( _VECTOR(46)) {while (1) x++;}
478 ISR( _VECTOR(47)) {while (1) x++;}
479 ISR( _VECTOR(48)) {while (1) x++;}
480 ISR( _VECTOR(49)) {while (1) x++;}
481 ISR( _VECTOR(50)) {while (1) x++;}
482 ISR( _VECTOR(51)) {while (1) x++;}
483 ISR( _VECTOR(52)) {while (1) x++;}
484 ISR( _VECTOR(53)) {while (1) x++;}
485 ISR( _VECTOR(54)) {while (1) x++;}
486 ISR( _VECTOR(55)) {while (1) x++;}
487 ISR( _VECTOR(56)) {while (1) x++;}
488 //ISR( _VECTOR(57)) {while (1) x++;}
489 //ISR( _VECTOR(58)) {while (1) x++;}
490 //ISR( _VECTOR(59)) {while (1) x++;}
491 //ISR( _VECTOR(60)) {while (1) x++;}
492 ISR( _VECTOR(61)) {while (1) x++;}
493 ISR( _VECTOR(62)) {while (1) x++;}
494 ISR( _VECTOR(63)) {while (1) x++;}
495 ISR( _VECTOR(64)) {while (1) x++;}
496 ISR( _VECTOR(65)) {while (1) x++;}
497 ISR( _VECTOR(66)) {while (1) x++;}
498 ISR( _VECTOR(67)) {while (1) x++;}
499 ISR( _VECTOR(68)) {while (1) x++;}
500 ISR( _VECTOR(69)) {while (1) x++;}
501 ISR( _VECTOR(70)) {while (1) x++;}
502 ISR( _VECTOR(71)) {while (1) x++;}
503 ISR( _VECTOR(72)) {while (1) x++;}
504 ISR( _VECTOR(73)) {while (1) x++;}
505 ISR( _VECTOR(74)) {while (1) x++;}
506 ISR( _VECTOR(75)) {while (1) x++;}
507 ISR( _VECTOR(76)) {while (1) x++;}
508 ISR( _VECTOR(77)) {while (1) x++;}
509 ISR( _VECTOR(78)) {while (1) x++;}
510 ISR( _VECTOR(79)) {while (1) x++;}
511 #endif
512 /** @} */
513 /** @} */
#define F_CPU
CPU core frequency resulting from the chosen divisors and multipliers.
Definition: config-clocks.h:87
void clock_delay_usec(uint16_t dt)
Delay a given number of microseconds.
Definition: clock.c:94
void __attribute__((interrupt))
This ISR handles most of the business interacting with the 1-wire bus.
Definition: onewire.c:174
void clock_delay_msec(uint16_t howlong)
Delay up to 65535 milliseconds.
Definition: clock.c:260
void clock_init(void)
Initialize the clock library.
Definition: clock.c:76
void AVR_OUTPUT_COMPARE_INT(void)
ISR for the TIMER0 or TIMER2 interrupt as defined in clock-avr.h for the particular MCU...
void clock_adjust_ticks(clock_time_t howmany)
Adjust the system current clock time.
Definition: clock.c:289
CCIF clock_time_t clock_time(void)
Get the current clock time.
Definition: clock.c:41
void etimer_request_poll(void)
Make the event timer aware that the clock has changed.
Definition: etimer.c:145
void clock_set_seconds(unsigned long sec)
Set the value of the platform seconds.
Definition: clock.c:49
CCIF unsigned long clock_seconds(void)
Get the current value of the platform seconds.
Definition: clock.c:57
int etimer_pending(void)
Check if there are any non-expired event timers.
Definition: etimer.c:223
void clock_delay(unsigned int delay)
Obsolete delay function but we implement it here since some code still uses it.
Definition: clock.c:60
void clock_wait(clock_time_t t)
Wait for a given number of ticks.
Definition: clock.c:166
Event timer header file.
A timer.
Definition: etimer.h:76
#define CLOCK_SECOND
A second, measured in system clock time.
Definition: clock.h:82