本實驗定期的打印“hello world”,并且計數打印的個數。第二線程被稱作“blink”,實現LEDs的高速閃爍(如果在Hello world線程里,可能實現不了這么快的速度)。
C++ Code
#include "contiki.h"
#include "dev/leds.h"
#include <stdio.h> /* For printf() */
/*---------------------------------------------------------------------------*/
/* We declare the two processes */
PROCESS(hello_world_process, "Hello world process");
PROCESS(blink_process, "LED blink process");
/* We require the processes to be started automatically */
AUTOSTART_PROCESSES(&hello_world_process, &blink_process);
/*---------------------------------------------------------------------------*/
/* Implementation of the first process */
PROCESS_THREAD(hello_world_process, ev, data)
{
// variables are declared static to ensure their values are kept
// between kernel calls.
static struct etimer timer;
static int count = 0;
// any process mustt start with this.
PROCESS_BEGIN();
// set the etimer module to generate an event in one second.
etimer_set(&timer, CLOCK_CONF_SECOND);
while (1)
{
// wait here for an event to happen
PROCESS_WAIT_EVENT();
// if the event is the timer event as expected...
if(ev == PROCESS_EVENT_TIMER)
{
// do the process work
printf("Hello, world #%i\n", count);
count ++;
// reset the timer so it will generate an other event
// the exact same time after it expired (periodicity guaranteed)
etimer_reset(&timer);
}
// and loop
}
// any process must end with this, even if it is never reached.
PROCESS_END();
}
/*---------------------------------------------------------------------------*/
/* Implementation of the second process */
PROCESS_THREAD(blink_process, ev, data)
{
static struct etimer timer;
static uint8_t leds_state = 0;
PROCESS_BEGIN();
while (1)
{
// we set the timer from here every time
etimer_set(&timer, CLOCK_CONF_SECOND / 4);
// and wait until the vent we receive is the one we're waiting for
PROCESS_WAIT_EVENT_UNTIL(ev == PROCESS_EVENT_TIMER);
// update the LEDs
leds_off(0xFF);
leds_on(leds_state);
leds_state += 1;
}
PROCESS_END();
}
/*---------------------------------------------------------------------------*/
1、線程啟動流程
a) 聲明線程PROCESS(name, strname),name線程名字,strname對線程名字的描述。
b) AUTOSTART_PROCESSES(&hello_world_process, &blink_process)開啟線程。
c) PROCESS_THREAD(hello_world_process, ev, data)線程宏定義。
第一個參數lc是英文全稱是local continuation(本地延續?,這個不好翻譯),它可以說就是protothread的控制參數,因為protothread的精華在C的switch控制語句,這個lc就是switch里面的參數;
第二個參數就是timer給這個進程傳遞的事件了,其實就是一個unsigned char類型的參數,具體的參數值在process .h中定義;
第三個參數也是給進程傳遞的一個參數(舉個例子,假如要退出一個進程的話,那么必須把這個進程所對應的timer也要從timer隊列timerlist清除掉,那么進程在死掉之前就要給etimer_process傳遞這個參數,參數的值就是進程本身,這樣才能是etimer_process在timer隊列里找到相應的etimer進而清除)。