void clock_init(void) { /* Make sure we know where we stand */ CLKCONCMD = CLKCONCMD_OSC32K | CLKCONCMD_OSC; /* Stay with 32 KHz RC OSC, Chance System Clock to 32 MHz */ CLKCONCMD &= ~CLKCONCMD_OSC; while(CLKCONSTA & CLKCONCMD_OSC); /* Tickspeed 500 kHz for timers[1-4] */ CLKCONCMD |= CLKCONCMD_TICKSPD2 | CLKCONCMD_TICKSPD1; while(CLKCONSTA != CLKCONCMD); /*Initialize tick value*/ timer_value = ST0; timer_value += ((unsigned long int) ST1) << 8; timer_value += ((unsigned long int) ST2) << 16; timer_value += TICK_VAL; ST2 = (unsigned char) (timer_value >> 16); ST1 = (unsigned char) (timer_value >> 8); ST0 = (unsigned char) timer_value; STIE = 1; /* IEN0.STIE interrupt enable */ }
CCIF clock_time_t clock_time(void) { return count; }
#pragma vector=ST_VECTOR __near_func __interrupt void clock_isr(void) { DISABLE_INTERRUPTS(); ENERGEST_ON(ENERGEST_TYPE_IRQ); timer_value = ST0; timer_value += ((unsigned long int) ST1) << 8; timer_value += ((unsigned long int) ST2) << 16; timer_value += TICK_VAL; ST2 = (unsigned char) (timer_value >> 16); ST1 = (unsigned char) (timer_value >> 8); ST0 = (unsigned char) timer_value; ++count; if(count % CLOCK_CONF_SECOND == 0) { ++seconds; } if(etimer_pending() && (etimer_next_expiration_time() - count - 1) > MAX_TICKS) { etimer_request_poll(); } STIF = 0; /* IRCON.STIF */ ENERGEST_OFF(ENERGEST_TYPE_IRQ); ENABLE_INTERRUPTS(); }
CCIF unsigned long clock_seconds(void) { return seconds; } void clock_delay(unsigned int len) { unsigned int i; for(i = 0; i< len; i++) { ASM(nop); } }
4.范例
PROCESS_THREAD(clock_test_process, ev, data) { PROCESS_BEGIN(); printf("Clock delay test, (10,000 x i) cycles:\n"); i = 1; while(i < 6) { start_count = clock_time(); // 记录开始timer clock_delay(10000 * i); // 软件延时 end_count = clock_time(); // 记录结束timer diff = end_count - start_count; // 计算差值,单位为tick printf("Delayed %u \n%u ticks =~ %u ms\n", 10000 * i, diff, diff * 8); i++; } printf("Done!\n"); PROCESS_END(); }
PROCESS_THREAD(clock_test_process, ev, data) { PROCESS_BEGIN(); printf("Clock Seconds Test (5s):\n"); // 间隔为5S i = 0; while(i < 10) { etimer_set(&et, 5 * CLOCK_SECOND); // etimer溢出时间为5s PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et)); // 等待定时器溢出 sec = clock_seconds(); // 系统运行时间 单位s printf("%lu Seconds\n", sec); // 打印 i++; } printf("Done!\n"); PROCESS_END(); }【实验结果】