當(dāng)前位置:首頁 > 嵌入式培訓(xùn) > 嵌入式學(xué)習(xí) > 講師博文 > 第1章 Contiki Hello World實(shí)驗(yàn)
本實(shí)驗(yàn)定期的打印“hello world”,并且計(jì)數(shù)打印的個(gè)數(shù)。第二線程被稱作“blink”,實(shí)現(xiàn)LEDs的高速閃爍(如果在Hello world線程里,可能實(shí)現(xiàn)不了這么快的速度)。
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、線程啟動(dòng)流程
a) 聲明線程PROCESS(name, strname),name線程名字,strname對線程名字的描述。
b) AUTOSTART_PROCESSES(&hello_world_process, &blink_process)開啟線程。
c) PROCESS_THREAD(hello_world_process, ev, data)線程宏定義。
第一個(gè)參數(shù)lc是英文全稱是local continuation(本地延續(xù)?,這個(gè)不好翻譯),它可以說就是protothread的控制參數(shù),因?yàn)閜rotothread的精華在C的switch控制語句,這個(gè)lc就是switch里面的參數(shù);
第二個(gè)參數(shù)就是timer給這個(gè)進(jìn)程傳遞的事件了,其實(shí)就是一個(gè)unsigned char類型的參數(shù),具體的參數(shù)值在process .h中定義;
第三個(gè)參數(shù)也是給進(jìn)程傳遞的一個(gè)參數(shù)(舉個(gè)例子,假如要退出一個(gè)進(jìn)程的話,那么必須把這個(gè)進(jìn)程所對應(yīng)的timer也要從timer隊(duì)列timerlist清除掉,那么進(jìn)程在死掉之前就要給etimer_process傳遞這個(gè)參數(shù),參數(shù)的值就是進(jìn)程本身,這樣才能是etimer_process在timer隊(duì)列里找到相應(yīng)的etimer進(jìn)而清除)。