第6篇 对blink的进一步修改 (教程lesson 1)

本文探讨了如何通过将Blink功能转换为计数器,实现LED状态的周期性变化。详细介绍了如何在NESC环境下定义计数器、初始化、启动、停止任务,并通过计数器值的递增来控制LED的不同状态,如红灯、绿灯、黄灯的亮灭。还提供了两种实现方式的对比,一种使用了task进行周期性操作,另一种则直接在事件触发时进行判断。文章最后鼓励读者实践并实验不同功能的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有没有想过对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,看看绿灯是不是每秒亮一次。

评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值