wireless embedded systems 0120442x node programming n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Wireless Embedded Systems (0120442x) Node Programming PowerPoint Presentation
Download Presentation
Wireless Embedded Systems (0120442x) Node Programming

Loading in 2 Seconds...

play fullscreen
1 / 56

Wireless Embedded Systems (0120442x) Node Programming - PowerPoint PPT Presentation


  • 121 Views
  • Uploaded on

Wireless Embedded Systems (0120442x) Node Programming. Chaiporn Jaikaeo chaiporn.j@ku.ac.th Department of Computer Engineering Kasetsart University. Outline. Microcontroller programming Software development cycle Hardware platforms IWING-MRF IWING-JN IWING's MoteLib. IWING-MRF Mote.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Wireless Embedded Systems (0120442x) Node Programming' - twila


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
wireless embedded systems 0120442x node programming

Wireless Embedded Systems(0120442x)Node Programming

Chaiporn Jaikaeo

chaiporn.j@ku.ac.th

Department of Computer EngineeringKasetsart University

outline
Outline
  • Microcontroller programming
    • Software development cycle
  • Hardware platforms
    • IWING-MRF
    • IWING-JN
  • IWING's MoteLib
iwing mrf mote
IWING-MRF Mote

Analog/Digital sensor connectors

Radio transceiver

UART connectors

USB Connector(for reprogramming and power)

8-bit AVR Microcontroller

External battery connector

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

iwing jn mote
IWING-JN Mote

Wireless microcontrollermodule with PCB antenna

Analog/Digital sensor connectors

UART connectors

typical development process

Microcontroller

flash memory

BSL

Typical Development Process
  • For microcontrollers with bootstrap loader (BSL) installed

Source code (C/Asm)

Cross Compiler/Assembler

Serial/USB

Machine code

build simple app
Build Simple App
  • Let's build a simple application
  • How to know whether our program is running?
    • Make mote output something
    • What can be used as output?
iwing mrf schematic
IWING-MRF Schematic
  • Available on course's homepage
iwing mrf blinking led
IWING-MRF – Blinking LED
  • Task: turn a LED on and off repeatedly
  • Idea
    • Configure Port D's Pin 5 (PD5) for output
    • Repeatedly set the pin logic level to 0 and 1
    • Add some delay before toggling pin level
iwing mrf c code blink c
IWING-MRF C Code – blink.c

#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);

}

}

  • How to add delay?
  • Can the code be made shorter?
compiling
Compiling
  • Make an ELF binary by running cross compiler

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

  • Translate the object file into ihex format

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

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

flashing code into mote
Flashing Code Into Mote
  • Plug mote into a USB port
  • Activate boot-loader
    • Press and release RESET while holding USER/B.L.
  • Make sure it is recognized by your PC
  • Invoke chip programmer

$ lsusb

Bus 003 Device 049: ID 16c0:05dc

Bus 001 Device 003: ID 046d:c03d Logitech, Inc.

$ avrdude -p atmega328p -c usbasp -U flash:w:blink.hex

creating makefile

Tab character

Creating Makefile
  • To compile
  • To download program to flash (will compile if needed)

make

make flash

iwing s motelib

Software

Hardware

IWING's MoteLib

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

hardware abstraction
Hardware Abstraction

IWING-MRF API Implementation

IWING-MRF Hardware

hardware abstraction1
Hardware Abstraction

IWING-JN API Implementation

IWING-JN Hardware

programming model

Radio event handler

Sensor event handler

Timer event handler

Boot event handler

Programming Model
  • MoteLib provides event-based programming environment

Idle loop

Handled by MoteLib

Handled by developer

example
Example
  • Turn red LED on and off repeatedly every 500 ms

#include <motelib/system.h>

#include <motelib/led.h>

#include <motelib/timer.h>

Timer t;

voidfired(Timer *t) {

ledToggle(0);

}

void boot() {

timerCreate(&t);

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

}

example creating makefile
Example: Creating Makefile

# Platform to build the code for

PLATFORM = iwing-mrf

# Required target without extension

TARGET = blink

# Include MoteLib's main make rules

include $(MOTELIB_DIR)/Makerules

example build and flash app
Example: Build and Flash App
  • Build your application
  • Program the mote with

make

make flash

motelib api
MoteLib API
  • Residing in $(MOTELIB_DIR)/include
    • motelib/system.h
    • motelib/led.h
    • motelib/timer.h
    • motelib/button.h
    • motelib/sensor.h
    • motelib/actor.h
    • motelib/radio.h
    • motelib/uart.h
  • Complete API documentation can be found here
    • http://www.cpe.ku.ac.th/~cpj/motelib/
system api motelib system h
System API (motelib/system.h)
  • Provides boot() function signature
  • Provides various function declarations for node ID and network ID inquiry
  • Should be included in every MoteLib application
led api motelib led h
LED API (motelib/led.h)
  • Turn LED#2 on
  • Turn LED#1 off
  • Toggle LED#0
  • Use LEDs to display binary value

ledSet(2,1);

ledSet(1,0);

ledToggle(0);

ledSetValue(5);

timer api motelib timer h
Timer API (motelib/timer.h)
  • Define and initialize a timer
  • Start the timer with 1-second timeout; trigger only once; call function fired when triggered
  • Start the timer with 1-second timeout; trigger periodically

Timer t;

timerCreate(&t);

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

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

timer api cont d
Timer API (cont'd)
  • Defining callback

void fired(Timer *t)

{

// do something

}

button api motelib button h
Button API (motelib/button.h)
  • Set handler to monitor button event
    • Usually called in boot()
  • Handler example

buttonSetHandler(handler);

void handler(ButtonStatus s)

{

if (s == BUTTON_PRESSED)

// do something

if (s == BUTTON_RELEASED)

// do something

}

programming practice
Programming Practice
  • button-count.c
    • Counts how many times the USER button has been pressed
    • Then shows the number (only 3 LSBs) on the LEDs
    • Count to 7 and wrap around to 0
sensor api motelib sensor h
Sensor API (motelib/sensor.h)
  • Read digital input from input#0
  • Request analog reading (asynchronous) from input#3

uint16_t x = sensorReadDigital(SENSOR_0);

sensorRequestAnalog(SENSOR_3, dataReady);

:

void dataReady(uint16_t value)

{

// value stores sensor reading

}

actor api motelib actor h
Actor API (motelib/actor.h)
  • Activate output #2 (set logic to High)
  • Deactivate output #3 (set logic to Low)

actorSetState(ACTOR_2,1);

actorSetState(ACTOR_3,0);

sensor board
Sensor Board
  • Measures light and temperature

Sensor Power Supply

Light Sensor

Temperature Sensor

sensor reading procedure
Sensor Reading Procedure
  • Step 1: Turn on sensor power
  • Step 2: Request analog reading
  • Step 3: Wait until value is available
  • Step 4: Turn off sensor power
split phase operations

Controller

Sensor

Controller

Sensor

Request

Request

Ack

Blocking

Data

Ready

Read

Data

Synchronous Operation

Asynchronous Operation

Split-Phase Operations
example sense light c
Example: sense-light.c
  • Every 100 ms, measure light and display the value on LEDs
    • Light value is in range 0 – 1023
    • Need to scale down to 0 – 7
example1
Example

#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);

}

programming practice1
Programming Practice
  • Modify sense-light.c so that light is sampled 4 times in each measurement
    • Average value is displayed on LEDs
creating a reading task
Creating a Reading Task

Create timer

  • Event-based code can be difficult to read and maintain
  • Idea
    • Make a reading task that runs forever
    • Other tasks can also be added to run concurrently

Start timer

Wait until timer expired

Turn on sensors

Request reading

Wait until data ready

Complete 4 samples?

Compute and display average

Turn off sensors

synchronous operations
Synchronous Operations
  • MoteLib provides various checks to support synchronous operation
  • E.g.,
    • timerExpired(t)
      • Determines whether timer t has already expired
      • Only works for one-shot timer
    • sensorAnalogWaiting(s)
      • Returns true if the system still waits for sensor s
    • sensorAnalogResult(s)
      • Returns the most recent value of sensor s
first attempt
First 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?

problem with event based model
Problem with Event-based Model

Events: unstructured code flow

Threads: sequential code flow

Very much like programming with GOTOs

events require one stack
Events Require One Stack
  • Four event handlers, one stack

Stack is reused for every event handler

Eventhandler 1

Eventhandler 2

Eventhandler 3

Eventhandler 4

problem with multithreading
Problem with Multithreading
  • Four threads, each with its own stack

Thread 1

Thread 2

Thread 3

Thread 4

emulating concurrency
Emulating Concurrency
  • Previous example wouldn't work because of the blocking while-loop
    • Other parts of the system will be unresponsive
  • Must return to MoteLib inside of the while-loops
  • During MoteLib's idle loop, keep jumping into the while-loops
coroutines
Coroutines
  • Generalized subroutines
    • Allow multiple entry points for suspending and resuming execution at certain locations
  • Can be used to implement:
    • Cooperative multitasking
    • Actor model of concurrency
subroutines vs coroutines
Subroutines vs. Coroutines

“Subroutines are a special case of coroutines.”

--Donald Knuth

Fundamental Algorithms. The Art of Computer Programming

Routine 2

Routine 1

Routine 1

Routine 2

yield

yield

call

return

yield

return

yield

call

Subroutines

Coroutines

programming model1

Event handler2

Event handler1

Programming Model

call

MoteLib'sIdle loop

return

call

return

continue

Task 1

yield

continue

Task 2

yield

Handled by MoteLib

Handled by developer

implementation details
Implementation Details
  • How to ask MoteLib to call our tasks?
    • MoteLib provides setLoopRoutine(), allowing a function to be called every idle loop
  • How to have a task yield and correctly come back to where it left?

void myroutine() {

// something to be executed continuously

}

void boot() {

:

setLoopRoutine(myroutine);

}

implementing continuation
Implementing Continuation
  • Each coroutine must be able to continue from where it last yielded

Routine 1

MainLoop

continue

yield

continue

yield

duff s device
Duff's Device
  • Invented to optimize data transfer by means of loop unwinding
  • Switch cases are used like GOTO labels

do {

*to = *from++;

} while(--count > 0);

register n = (count + 7) / 8;

switch(count % 8) {

case0: do { *to = *from++;

case7: *to = *from++;

case6: *to = *from++;

case5: *to = *from++;

case4: *to = *from++;

case3: *to = *from++;

case2: *to = *from++;

case1: *to = *from++;

} while(--n > 0);

}

protothreads
Protothreads
  • Invented by Adam Dunkels and Oliver Schmidt
    • Used in the Contiki OS
  • Provides light-weight mechanism for concurrent programming using standard C macros and switch-case statements
  • Heavily inspired by Duff's Device and Simon Tatham's Coroutines in C
  • See
    • http://dunkels.com/adam/pt/expansion.html
protothreads1

Events require one stack

Protothreads
  • Protothreads require only one stack
  • E.g, four protothreads, each with its own stack

Just like events

Protothread 2

Protothread 3

Protothread 4

Protothread 1

six line implementation
Six-line implementation
  • Protothreads implemented using the C switch statement
  • Heavily inspired by Duff's Device and Simon Tatham'sCoroutines in C

struct pt { unsigned short lc; };

#define PT_INIT(pt) pt->lc = 0

#define PT_BEGIN(pt) switch(pt->lc) { case 0:

#define PT_EXIT(pt) pt->lc = 0; return 2

#define PT_WAIT_UNTIL(pt, c) pt->lc = __LINE__; case __LINE__: \

if(!(c)) return 0

#define PT_END(pt) } pt->lc = 0; return 1

revised sense light c
Revised sense-light.c

#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);

}

//////////////////////////////

PT_THREAD(readLightTask(struct pt *pt))

{

staticuint8_t i;

staticuint16_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);

}

protothreads limitations
Protothreads Limitations
  • Local variables must be manually preserved
    • Local variables are created on stack
    • They are destroyed when function returns
    • So they should be stored in an explicit state object
    • Or declared static, if reentrancy is not required
  • switch-case statements are not allowed
  • Cannot take advantage of multi-processing