clock.c

00001 #include <sys/clock.h>
00002 #include <sys/cc.h>
00003 #include <sys/etimer.h>
00004 #include <debug-uart.h>
00005 
00006 #include <AT91SAM7S64.h>
00007 #include <sys-interrupt.h>
00008 
00009 #define PIV  ((MCK/CLOCK_SECOND/16)-1)
00010 
00011 static volatile clock_time_t current_clock = 0;
00012 static volatile unsigned long current_seconds = 0;
00013 static unsigned int second_countdown = CLOCK_SECOND;
00014 
00015 
00016 static int pit_handler_func()
00017 {
00018   if (!(*AT91C_PITC_PISR & AT91C_PITC_PITS)) return 0;  /* Check PIT
00019                                                            Interrupt */
00020   current_clock++;
00021   if(etimer_pending() && etimer_next_expiration_time() <= current_clock) {
00022     etimer_request_poll();
00023     /* dbg_printf("%d,%d\n", clock_time(),etimer_next_expiration_time   ()); */
00024 
00025   }
00026   if (--second_countdown == 0) {
00027     current_seconds++;
00028     second_countdown = CLOCK_SECOND;
00029   }
00030   (void)*AT91C_PITC_PIVR;
00031   return 1;
00032 }
00033 
00034 static SystemInterruptHandler pit_handler = {NULL, pit_handler_func};
00035 
00036 void
00037 clock_init()
00038 {
00039   sys_interrupt_append_handler(&pit_handler);
00040   *AT91C_PITC_PIMR = (AT91C_PITC_PITIEN |    /* PIT Interrupt Enable */ 
00041                       AT91C_PITC_PITEN  |    /* PIT Enable */
00042                       PIV);
00043   sys_interrupt_enable();
00044 }
00045 
00046 clock_time_t
00047 clock_time(void)
00048 {
00049   return current_clock;
00050 }
00051 
00052 /* The inner loop takes 4 cycles. The outer 5+SPIN_COUNT*4. */
00053 
00054 #define SPIN_TIME 2 /* us */
00055 #define SPIN_COUNT (((MCK*SPIN_TIME/1000000)-5)/4)
00056 
00057 #ifndef __MAKING_DEPS__
00058 
00059 void
00060 clock_delay(unsigned int t)
00061 {
00062 #ifdef __THUMBEL__ 
00063   asm volatile("1: mov r1,%2\n2:\tsub r1,#1\n\tbne 2b\n\tsub %0,#1\n\tbne 1b\n":"=l"(t):"0"(t),"l"(SPIN_COUNT));
00064 #else
00065 #error Must be compiled in thumb mode
00066 #endif
00067 }
00068 
00069 unsigned long
00070 clock_seconds(void)
00071 {
00072   return current_seconds;
00073 }
00074 #endif /* __MAKING_DEPS__ */

Generated on Mon Apr 11 14:23:33 2011 for Contiki 2.5 by  doxygen 1.6.1