有没有想过对blink进一步修改?
把blink改成一个计数器:
代码如下:
Myblink.nc
configuration MyBlink {
}
implementation {
components Main, MyBlinkM, TimerC, LedsC;
Main.StdControl -> TimerC.StdControl;
Main.StdControl -> MyBlinkM.StdControl;
MyBlinkM.Timer -> TimerC.Timer[unique("Timer")];
MyBlinkM.Leds -> LedsC.Leds;
}
MyblinkM.nc
module MyBlinkM {
provides {
interface StdControl;
}
uses {
interface Timer;
interface Leds;
}
}
implementation {
int i; //注意到nesc中,定义一个整形变量的方式和c一致
command result_t StdControl.init() {
call Leds.init();
i = 0 ;
return SUCCESS;
}
command result_t StdControl.start() {
// Start a repeating timer that fires every 1000ms
return call Timer.start(TIMER_REPEAT, 10000);
}
command result_t StdControl.stop() {
return call Timer.stop();
}
task void processing() //新知识!task !esson3中学习
{ //取mod运算,mod1,红灯亮,mod2,绿灯亮,mod4,黄灯亮。注意学习的使用
if (i & 1) call Leds.redOn();
else call Leds.redOff();
if (i & 2) call Leds.greenOn();
else call Leds.greenOff();
if (i & 4) call Leds.yellowOn();
else call Leds.yellowOff();
}
event result_t Timer.fired()
{
i++; //计数器值上升
post processing(); //调用一个task的方式是post!
return SUCCESS;
}
}
不愿意使用task的同学看这里:
module MyBlinkM {
provides {
interface StdControl;
}
uses {
interface Timer;
interface Leds;
}
}
implementation {
int i;
command result_t StdControl.init() {
call Leds.init();
i = 0 ;
return SUCCESS;
}
command result_t StdControl.start() {
// Start a repeating timer that fires every 1000ms
return call Timer.start(TIMER_REPEAT, 10000);
}
command result_t StdControl.stop() {
return call Timer.stop();
}
event result_t Timer.fired()
{
i++;
if (i & 1) call Leds.redOn();
else call Leds.redOff();
if (i & 2) call Leds.greenOn();
else call Leds.greenOff();
if (i & 4) call Leds.yellowOn();
else call Leds.yellowOff();
return SUCCESS;
}
}
这两个程序基本相同,但后者没使用task,在event当中直接判断。程序好坏,大家自己去编译一下跑跑看吧。
讲到这里,blink已经给挖掘的差不多了,大家刻意编译blink程序 并且尝试改名之后再次编译, 将blink中的red改为green,看看绿灯是不是每秒亮一次。
本文探讨了如何通过将Blink功能转换为计数器,实现LED状态的周期性变化。详细介绍了如何在NESC环境下定义计数器、初始化、启动、停止任务,并通过计数器值的递增来控制LED的不同状态,如红灯、绿灯、黄灯的亮灭。还提供了两种实现方式的对比,一种使用了task进行周期性操作,另一种则直接在事件触发时进行判断。文章最后鼓励读者实践并实验不同功能的实现。
5529





