|
TinyOS點亮一個LED燈的程序 |
一派掌門 二十級 |
【MyC.nc】 module MyC { uses interface Leds; uses interface Boot; } implementation { event void Boot.booted() { call Leds.led2Toggle(); } } 【MyAppC.nc】 configuration MyAppC { } implementation { components MyC, MainC, LedsC;
MyC -> MainC.Boot; MyC.Leds -> LedsC; } 【Makefile】 COMPONENT = MyAppC include $(MAKERULES)
命令行執行:make telosb install bsl,/dev/ttyUSB0 即可編譯和燒寫 注意逗號左右沒有空格,加了空格燒寫會失敗! 注意用chown命令保證ttyUSB0的權限
|
一派掌門 二十級 |
【代碼解釋】 module MyC { uses interface Boot; // 使用Boot接口 uses interface Leds; // 使用Leds接口 // 至於接口是哪個組件提供的, 只能在configuration中指明 } implementation { event void Boot.booted() { call Leds.led2Toggle(); } }
configuration MyAppC { } implementation { components MyC, MainC, LedsC; // 該模塊使用的組件。注意配置MyAppC不是組件,所以要引用對應的MyC組件
MyC.Boot -> MainC.Boot; // Boot接口是MainC組件提供的 MyC.Leds -> LedsC.Leds; // Leds接口是LedsC組件提供的 }
|
|
一派掌門 二十級 |
無論接口是哪個組件提供的,uses interface後面都只能跟上組件的名字,並且不能隨便亂改名稱,例如uses interface A就是錯誤的,因為A接口根本不存在。即使寫上MyC.A-> MainC.Boot也是錯誤的。也就是說,MyC.Boot -> MainC.Boot這兩邊的Boot必須相同。
|
|
一派掌門 二十級 |
在nesC中,不允許有「MyC組件的A接口使用的是MainC組件提供的Boot接口」這樣的說法出現,只能說「MyC組件使用的Boot接口是MainC組件提供的」。 另外,MyAppC是一個configuration,不是組件(component),所以在components關鍵字中要寫上MyC,因為MyC才是組件。
|
|
一派掌門 二十級 |
event是接口使用者必須實現的函數。例如MyC組件(接口使用者)使用了MainC組件提供的Boot接口,因此MyC組件就必須自己實現Boot接口的booted函數。 Boot.booted函數是程序的入口點,相當於C語言的main函數。
|
|
一派掌門 二十級 |
|
|
一派掌門 二十級 |
【延時函數】 module MyC { uses interface Boot; // 使用Boot接口 uses interface Leds; // 使用Leds接口 // 至於接口是哪個組件提供的, 只能在configuration中指明 } implementation { // 延時約0.5秒 void delay(void) { unsigned char i; unsigned int j; for (i = 0; i < 16; i++) for (j = 0; j < 30000; j++); } event void Boot.booted() { while (1) { call Leds.led2Toggle(); delay(); call Leds.led2Toggle(); delay(); } } }
|
|
一派掌門 二十級 |
【點亮自己焊的LED燈(P2.1)的程序】 #include <io.h> void wait(void) { volatile unsigned int i; for (i = 0; i < 32000; i++); } int main(void) { P2DIR = 0xff; P2OUT = 0x00; while (1) { P2OUT ^= 0x02; wait(); } } 【運行結果】
|
|
一派掌門 二十級 |
【上述程序的TinyOS版本】 configuration MyAppC { } implementation { components MyC, MainC; MyC.Boot -> MainC.Boot; }
module MyC { uses interface Boot; } implementation { // 延時約0.5秒 // tinyos中delay函數運行地更快 void delay(void) { unsigned char i; unsigned int j; for (i = 0; i < 16; i++) for (j = 0; j < 32000; j++); } // 主函數 event void Boot.booted() { // 在tinyos程序中不需要<io.h> P2DIR = 0xff; P2OUT = 0xff; while (1) { P2OUT ^= 0x02; delay(); } } }
|
|