45
Architectures and Architectures and Applications for Wireless Applications for Wireless Sensor Networks (204525) Sensor Networks (204525) Sensor Node Programming Sensor Node Programming Chaiporn Jaikaeo [email protected] Department of Computer Engineering Kasetsart University

Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

  • Upload
    celina

  • View
    31

  • Download
    1

Embed Size (px)

DESCRIPTION

Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming. Chaiporn Jaikaeo [email protected] Department of Computer Engineering Kasetsart University. Outline. Microcontroller programming Software development cycle IWING's MoteLib. IWING-MRF Mote. - PowerPoint PPT Presentation

Citation preview

Page 1: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

Architectures and Applications Architectures and Applications for Wireless Sensor Networks for Wireless Sensor Networks

(204525)(204525)

Sensor Node ProgrammingSensor Node Programming

Chaiporn [email protected]

Department of Computer EngineeringKasetsart University

Page 2: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

2

OutlineOutline Microcontroller programmingMicrocontroller programming

Software development cycleSoftware development cycle IWING's MoteLibIWING's MoteLib

Page 3: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

3

IWING-MRF MoteIWING-MRF Mote

Radio transceiver

8-bit AVR Microcontroller

USB Connector(for reprogramming

and power)

Analog/Digital sensor connectors

External battery connector

UART connectors

Morakot Saravanee, Chaiporn Jaikaeo, 2010. Intelligent Wireless Network Group Morakot Saravanee, Chaiporn Jaikaeo, 2010. Intelligent Wireless Network Group (IWING), KU(IWING), KU

Page 4: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

4

MicrocontrollerMicrocontrollerflash flash

memorymemory

BSLBSL

Typical Development Typical Development ProcessProcess For microcontrollers with bootstrap For microcontrollers with bootstrap

loader (BSL) installedloader (BSL) installed

Source code (C/Asm)Source code (C/Asm)

Cross Compiler/AssemblerCross Compiler/AssemblerCross Compiler/AssemblerCross Compiler/Assembler

Machine codeMachine codeSerial/USB

Page 5: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

5

Build Simple AppBuild Simple App Let's build a simple applicationLet's build a simple application How to know whether our program is How to know whether our program is

running?running? Make mote output somethingMake mote output something What can be used as output?What can be used as output?

Page 6: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

6

IWING-MRF SchematicIWING-MRF Schematic Available on course's homepageAvailable on course's homepage

Page 7: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

7

IWING-MRF – Blinking LEDIWING-MRF – Blinking LED Task: turn a LED on and off Task: turn a LED on and off

repeatedlyrepeatedly IdeaIdea

Configure Port D's Pin 5 (PD5) for Configure Port D's Pin 5 (PD5) for outputoutput

Repeatedly set the pin logic level to 0 Repeatedly set the pin logic level to 0 and 1and 1

Add some delay before toggling pin Add some delay before toggling pin levellevel

Page 8: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

8

IWING-MRF C Code – IWING-MRF C Code – blink.cblink.c

How to add delay?How to add delay? Can the code be made shorter?Can the code be made shorter?

#include <avr/io.h>

main(){ DDRD |= (1 << 5); // Make PD5 output while (1) { // Set pin logic to low PORTD &= ~(1 << 5);

// Add some delay

// Set pin logic to high PORTD |= (1 << 5); }}

Page 9: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

9

CompilingCompiling Make an Make an ELF binaryELF binary by running cross by running cross

compilercompiler

Note: blink.elf is not a Windows or Linux Note: blink.elf is not a Windows or Linux executable!executable!

Translate the object file into Translate the object file into ihexihex formatformat

$ avr-gcc -mmcu=atmega328p –o blink.elf blink.c$ avr-gcc -mmcu=atmega328p –o blink.elf blink.c

$ avr-objcopy -j .text -j .data $ avr-objcopy -j .text -j .data ––O ihex blink.elf blink.hexO ihex blink.elf blink.hex

Page 10: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

10

Flashing Code Into MoteFlashing Code Into Mote Plug mote into a USB portPlug mote into a USB port Activate boot-loaderActivate boot-loader

Press and release RESET while holding Press and release RESET while holding USER/B.L.USER/B.L.

Make sure it is recognized by your PCMake sure it is recognized by your PC

Invoke chip programmerInvoke chip programmer$ avrdude -p atmega328p -c usbasp -U flash:w:blink.hex$ avrdude -p atmega328p -c usbasp -U flash:w:blink.hex

$ $ lsusblsusbBus 003 Device 049: ID 16c0:05dc Bus 003 Device 049: ID 16c0:05dc Bus 001 Device 003: ID 046d:c03d Logitech, Inc. Bus 001 Device 003: ID 046d:c03d Logitech, Inc.

Page 11: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

11

IWING-MRF's Boot LoaderIWING-MRF's Boot Loader

Page 12: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

12

Creating Creating MakefileMakefile

To compileTo compile

To download program to flash (will compile if To download program to flash (will compile if needed)needed)

makemake

make flashmake flash

Tab character

Page 13: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

13

Programming ExerciseProgramming Exercise Modify Modify blink.cblink.c so that so that

Under normal condition, LEDs blink in Under normal condition, LEDs blink in the sequencethe sequence

RedRed YellowYellow GreenGreen

When the When the user button is pressed (and is pressed (and held), only held), only GreenGreen will blink will blink

Page 14: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

14

IWING's MoteLibIWING's MoteLib

Software

Hardware

Morakot Saravanee, Patra Poome, Chaiporn Jaikaeo, 2009. Intelligent Wireless Morakot Saravanee, Patra Poome, Chaiporn Jaikaeo, 2009. Intelligent Wireless Network Group (IWING), KUNetwork Group (IWING), KU

Page 15: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

15

Hardware AbstractionHardware Abstraction

IWING-MRF Hardware

IWING-MRF API Implementation

Page 16: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

16

Mote and Network Mote and Network EmulatorEmulator

Virtual Mote

Page 17: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

17

Programming ModelProgramming Model MoteLib provides event-based MoteLib provides event-based

programming environmentprogramming environment

Idle loop

Radio event handler

Sensor event handler

Timer event handler

Boot event handler

Handled by MoteLibHandled by MoteLib Handled by developerHandled by developer

Page 18: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

18

ExampleExample Turn red LED on and off repeatedly Turn red LED on and off repeatedly

every 500 msevery 500 ms#include <motelib/system.h>#include <motelib/led.h>#include <motelib/timer.h>

Timer t;

void fired() { ledToggle(0);}

void boot() { timerCreate(&t); timerStart(&t, TIMER_PERIODIC, 500, fired);}

Page 19: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

19

Example: Creating Example: Creating MakefileMakefile

# Platform to build the code forPLATFORM = iwing-mrf

# Required target without extensionTARGET = blink

# Include MoteLib's main make rulesinclude $(MOTELIB_DIR)/Makerules

Page 20: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

20

Example: Build and Flash Example: Build and Flash AppApp Build your applicationBuild your application

Program the mote withProgram the mote with

makemake

make flashmake flash

Page 21: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

21

MoteLib APIMoteLib API Residing in Residing in $(MOTELIB_DIR)/include$(MOTELIB_DIR)/include

motelib/system.hmotelib/system.h motelib/led.hmotelib/led.h motelib/timer.hmotelib/timer.h motelib/button.hmotelib/button.h motelib/sensor.hmotelib/sensor.h motelib/actor.hmotelib/actor.h motelib/radio.hmotelib/radio.h motelib/uart.hmotelib/uart.h

Complete API documentation can be found Complete API documentation can be found herehere http://www.cpe.ku.ac.th/~cpj/motelib/http://www.cpe.ku.ac.th/~cpj/motelib/

Page 22: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

22

System API System API ((motelib/system.hmotelib/system.h)) Provides Provides boot()boot() function signature function signature Provides various function Provides various function

declarations for node ID and network declarations for node ID and network ID inquiryID inquiry

Should be included in every MoteLib Should be included in every MoteLib applicationapplication

Page 23: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

23

LED API (LED API (motelib/led.hmotelib/led.h)) Turn LED#2 onTurn LED#2 on

Turn LED#1 offTurn LED#1 off

Toggle LED#0Toggle LED#0

Use LEDs to display binary valueUse LEDs to display binary value

ledSet(2,1);

ledSet(1,0);

ledToggle(0);

ledSetValue(5);

Page 24: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

24

Timer API Timer API ((motelib/timer.hmotelib/timer.h)) Define and initialize a timerDefine and initialize a timer

Start the timer with 1-second timeout; Start the timer with 1-second timeout; trigger only once; call function trigger only once; call function firedfired when triggeredwhen triggered

Start the timer with 1-second timeout; Start the timer with 1-second timeout; trigger periodicallytrigger periodically

Timer t;timerCreate(&t);

timerStart(&t, TIMER_ONESHOT, 1000, fired);

timerStart(&t, TIMER_PERIODIC, 1000, fired);

Page 25: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

25

Timer API (cont'd)Timer API (cont'd) Defining callbackDefining callback

void fired(Timer *t){ // do something}

Page 26: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

26

Button API (Button API (motelib/button.hmotelib/button.h))

Set handler to monitor button eventSet handler to monitor button event Usually called in boot()Usually called in boot()

Handler exampleHandler example

buttonSetHandler(handler);

void handler(ButtonStatus s){ if (s == BUTTON_PRESSED) // do something if (s == BUTTON_RELEASED) // do something}

Page 27: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

27

Programming PracticeProgramming Practice button-count.cbutton-count.c

Counts how many times the USER Counts how many times the USER button has been pressedbutton has been pressed

Then shows the number (only 3 LSBs) Then shows the number (only 3 LSBs) on the LEDson the LEDs

Count to 7 and wrap around to 0Count to 7 and wrap around to 0

Page 28: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

28

Sensor API Sensor API ((motelib/sensor.hmotelib/sensor.h)) Read digital input from input#0Read digital input from input#0

Request analog reading (asynchronous) Request analog reading (asynchronous) from input#3from input#3

uint16_t x = sensorReadDigital(SENSOR_0);

sensorRequestAnalog(SENSOR_3, dataReady);:

void dataReady(uint16_t value){ // value stores sensor reading}

Page 29: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

29

Actor API Actor API ((motelib/actor.hmotelib/actor.h)) Activate output #2 (set logic to High)Activate output #2 (set logic to High)

Deactivate output #3 (set logic to Deactivate output #3 (set logic to Low)Low)

actorSetState(ACTOR_2,1);

actorSetState(ACTOR_3,0);

Page 30: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

30

Measures light and Measures light and temperaturetemperature

Sensor BoardSensor BoardPC4 (SENSOR_4)PC4 (SENSOR_4)

PC2 (SENSOR_2)PC2 (SENSOR_2)

PC0 (SENSOR_0)PC0 (SENSOR_0)

Page 31: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

31

Sensor Board SchematicSensor Board Schematic

Page 32: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

32

Sensor Reading ProcedureSensor Reading Procedure Step 1: Turn on sensor power (PC0)Step 1: Turn on sensor power (PC0) Step 2: Request analog readingStep 2: Request analog reading Step 3: Wait until value is availableStep 3: Wait until value is available Step 4: Turn off sensor powerStep 4: Turn off sensor power

Page 33: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

33

Example: Example: sense-light.csense-light.c Every 100 ms, measure light and Every 100 ms, measure light and

display the value on LEDsdisplay the value on LEDs Light value is in range 0 – 1023Light value is in range 0 – 1023 Need to scale down to 0 – 7Need to scale down to 0 – 7

Page 34: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

34

ExampleExample#include <motelib/system.h>#include <motelib/led.h>#include <motelib/timer.h>#include <motelib/sensor.h>#include <motelib/actor.h>

Timer t;

void readDone(uint16_t value);void readLight(Timer *t);

void boot(){ timerCreate(&t); timerStart(&t, TIMER_PERIODIC, 100, readLight);}

void readLight(Timer *t){ actorSetState(ACTOR_0, 1); sensorRequestAnalog(SENSOR_1, readDone);}

void readDone(uint16_t value){ ledSetValue(value/128); actorSetState(ACTOR_0, 0);}

Page 35: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

35

Programming PracticeProgramming Practice Modify Modify sense-light.csense-light.c so that light so that light

is sampled 4 times in each is sampled 4 times in each measurementmeasurement Average value is displayed on LEDsAverage value is displayed on LEDs

Page 36: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

36

Creating a Reading TaskCreating a Reading Task Event-based code Event-based code

can be difficult to can be difficult to read and maintainread and maintain

IdeaIdea Make a reading Make a reading

task that runs task that runs foreverforever

Other tasks can Other tasks can also be added to also be added to run concurrentlyrun concurrently

Start timer

Wait until timer expired

Create timer

Turn on sensors

Request reading

Wait until data ready

Complete 4 samples?

Compute and display average

Turn off sensors

Page 37: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

37

Synchronous OperationsSynchronous Operations MoteLib provides various checks to MoteLib provides various checks to

support synchronous operationsupport synchronous operation E.g.,E.g.,

timerExpired(t)timerExpired(t) Determines whether timer Determines whether timer tt has already has already

expiredexpired Only works for one-shot timerOnly works for one-shot timer

sensorAnalogWaiting(s)sensorAnalogWaiting(s) Returns true if the system still waits for Returns true if the system still waits for

sensor sensor ss sensorAnalogResult(s)sensorAnalogResult(s)

Returns the most recent value of sensor Returns the most recent value of sensor ss

Page 38: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

38

First AttemptFirst Attempt#include <motelib/system.h>#include <motelib/led.h>#include <motelib/timer.h>#include <motelib/sensor.h>#include <motelib/actor.h>

Timer t;void readLightTask();

void boot(){ readLightTask();}

void readLightTask(){ uint8_t i; uint16_t sum = 0;

timerCreate(&t);

while (1) { timerStart(&t, TIMER_ONESHOT, 100, NULL); while (!timerExpired(&t)) ; actorSetState(ACTOR_0, 1); for (i = 0; i < 4; i++) { sensorRequestAnalog(SENSOR_1, NULL); while (sensorAnalogWaiting(SENSOR_1)) ; sum += sensorAnalogResult(SENSOR_1); } ledSetValue(sum/4/128); actorSetState(ACTOR_0, 0); }}

Will this work?Will this work?

Page 39: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

39

Emulating ConcurrencyEmulating Concurrency Previous example wouldn't work Previous example wouldn't work

because of the blocking while-loopbecause of the blocking while-loop Other parts of the system will be Other parts of the system will be

unresponsiveunresponsive Must return to MoteLib Must return to MoteLib insideinside of the of the

while-loopswhile-loops During MoteLib's idle loop, keep During MoteLib's idle loop, keep

jumping into the jumping into the while-loopswhile-loops

Page 40: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

40

Programming ModelProgramming Model

MoteLib'sIdle loop

Task 2

Event handler2

Task 1

Event handler1

Handled by MoteLibHandled by MoteLib Handled by developerHandled by developer

callcall

returnreturncallcall

returnreturn

continuecontinue

yieldyield

yieldyield

continuecontinue

Page 41: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

41

Implementation DetailsImplementation Details How to ask MoteLib to call our How to ask MoteLib to call our taskstasks??

MoteLib provides MoteLib provides setLoopRoutine()setLoopRoutine(), , allowing a function to be called every allowing a function to be called every idle loopidle loop

How to have a task yield and How to have a task yield and correctly come back to where it left?correctly come back to where it left?

void myroutine() { // something to be executed continuously}

void boot() { : setLoopRoutine(myroutine);}

Page 42: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

42

Duff's DeviceDuff's Device Invented to optimize data transfer by Invented to optimize data transfer by

means of loop unwindingmeans of loop unwinding Switch cases are used like GOTO Switch cases are used like GOTO

labelslabelsdo { *to = *from++;} while(--count > 0);

register n = (count + 7) / 8;switch(count % 8) {case 0: do { *to = *from++;case 7: *to = *from++;case 6: *to = *from++;case 5: *to = *from++;case 4: *to = *from++;case 3: *to = *from++;case 2: *to = *from++;case 1: *to = *from++; } while(--n > 0);}

Page 43: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

43

ProtothreadsProtothreads Invented by Adam Dunkels and Oliver Invented by Adam Dunkels and Oliver

SchmidtSchmidt Used in the Contiki OSUsed in the Contiki OS

Provides light-weight mechanism for Provides light-weight mechanism for concurrent programming using concurrent programming using standard C standard C macrosmacros and and switch-caseswitch-case statements statements

Heavily inspired by Duff's Device and Heavily inspired by Duff's Device and Simon Tatham's Simon Tatham's CoroutinesCoroutines in C in C

SeeSee http://dunkels.com/adam/pt/expansion.http://dunkels.com/adam/pt/expansion.

htmlhtml

Page 44: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

44

Revised Revised sense-light.csense-light.c//////////////////////////////PT_THREAD(readLightTask(struct pt *pt)){ static uint8_t i; static uint16_t sum = 0;

PT_BEGIN(pt);

timerCreate(&t);

while (1) { timerStart(&t, TIMER_ONESHOT, 100, NULL); PT_WAIT_UNTIL(pt, timerExpired(&t)); actorSetState(ACTOR_0, 1); for (i = 0; i < 4; i++) { sensorRequestAnalog(SENSOR_1, NULL); PT_WAIT_WHILE(pt, sensorAnalogWaiting(SENSOR_1)); sum += sensorAnalogResult(SENSOR_1); } ledSetValue(sum/4/128); actorSetState(ACTOR_0, 0); }

PT_END(pt);}

#include <motelib/system.h>#include <motelib/led.h>#include <motelib/timer.h>#include <motelib/sensor.h>#include <motelib/actor.h>#include <pt/pt.h>

struct pt readLight_pt;PT_THREAD(readLightTask(struct pt *pt));Timer t;

//////////////////////////////void scheduleTasks(){ readLightTask(&readLight_pt);}

//////////////////////////////void boot(){ setLoopRoutine(scheduleTasks);}

Page 45: Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming

45

Protothreads LimitationsProtothreads Limitations Local variables must be manually Local variables must be manually

preservedpreserved Local variables are created on stackLocal variables are created on stack They are destroyed when function returnsThey are destroyed when function returns So they should be stored in an explicit So they should be stored in an explicit

state objectstate object Or declared Or declared staticstatic, if reentrancy is not , if reentrancy is not

requiredrequired switch-caseswitch-case statements are not allowed statements are not allowed Cannot take advantage of multi-Cannot take advantage of multi-

processingprocessing