You are on page 1of 43

Chapter 3

Embedded OS
MSc. Nguyen Khanh Loi
nkloi@hcmut.edu.vn

MSc Nguyen Khanh Loi


Content

Chapter 3: Embedded OS for end-devices


v Intro to Contiki-OS
v Programming using Contiki
v Cooja Emulator

2
MSc Nguyen Khanh Loi
Computer Systems

v Traditional systems: separate chips


v Microcontroller: integrate on single chip

Mote
MCU
CPU Timer
Network Peripherals

Memory Storage

3
MSc Nguyen Khanh Loi
Mote Characteristics

v Limited resources
ü RAM, ROM, Computation, Energy
• Wakeup, do work as quickly as possible, sleep

v Hardware modules operate concurrently


ü No parallel execution of code (not Core 2 Duos!)
• Asynchronous operation is first class

v Diverse application requirements


ü Efficient modularity

v Robust operation
ü Numerous, unattended, critical
• Predictable operation
4
MSc Nguyen Khanh Loi
What is an Operating System (OS)?

v OS is a software component in computer systems


v OS controls resources of the computer system
ü Allocation of memory for processes
ü Power management
v OS coordinates activities in the computer system
ü Which process uses the CPU
ü When I/O takes place
v Application programs run on top of OS Services
v Many criteria to classify OS
ü Design goal: general purpose vs OS for specific purposes
ü Target platforms: limitation of resources, reliability
guarantees
5
MSc Nguyen Khanh Loi
General purpose OS

v Design principles and Concepts


v Execution model
v Memory management
v Multitasking and concurrency
v Support for File systems
v Safety and Security Features
v GUI, I/O System, Portability
v Device Drivers and OS Networking

6
MSc Nguyen Khanh Loi
Why OS for WSNs?

v Nodes are designed to operate with limited resources


ü Power: WSN use batteries as a power supply
ü Memory and operational capabilities: sensing is less
resource demanding than computation in conventional OS
v Power management in WSN OS is very important
v Variety of solutions for WSN
ü Several WSN OS: TinyOS, Contiki OS, RTOS, etc
ü Several Simulator tools: Cooja, NS-2, TOSSIM, etc.
ü Several programming languages: C, nesC, etc.
v TinyOS and Contiki: the most popular WSN OS

7
MSc Nguyen Khanh Loi
Traditional Systems

v Well established layers of Application


abstractions Application
User
v Strict boundaries
v Ample resources
System
v Independent Applications at Network Stack
Threads Transport
endpoints communicate P2P
Network
through routers Address Space
Data Link
Files
Physical Layer
Drivers

Hardware

8
MSc Nguyen Khanh Loi
by comparison, WSNs ...

v Highly Constrained resources


ü Processing, storage, bandwidth, power
v Applications spread over many small nodes
ü Self-organizing Collectives
ü Highly integrated with changing environment and network
v Robust
ü inaccessible, critical operation
v Unclear where the boundaries belong

9
MSc Nguyen Khanh Loi
Soft or hard real-time applications

v Classified as non-real-time, hard or soft real-time. However, is somewhat fuzzy.


v Non-real-time: no important deadlines (all deadlines can be missed)
ü Computer programs

Usefulness
v Soft real-time: deadline may not be fulfilled
ü Multimedia transmission and reception
ü Networking, telecom (Mobile) networks
ü Websites and services Soft
v Hard real-time: no deadlines can be missed. Hard
ü Air traffic control
ü Nuclear power plant control Time

10
MSc Nguyen Khanh Loi
What is RTOS?

v Real-time operating system


ü Used in applications that require fast, accurate
response times.
ü Limited resources. RTOS focuses on only a
handful of features.
§ Maximize the number of threads
§ Scheduler
§ Tasks/Multi-task
§ Managed CPU/hardware resources and
providing services to other programs
ü Processing must be done or the system will fail

11
MSc Nguyen Khanh Loi
What is Kernel?

ü Part of the OS that offers core services to application software


ü Offered abstraction layer that hides processor hardware details from the
application software
ü 6 main basic service

12
MSc Nguyen Khanh Loi
Task state

§ RUNNING: executing on the CPU


§ READY: ready to be executed
§ WAITING: waiting for an event
§ INACTIVE: not active

13
MSc Nguyen Khanh Loi
Scheduler

v Part of the kernel that determines which tasks to execute.


v Some commonly used RTOS scheduling algorithms are:
ü Cooperative scheduling
ü Round-robin scheduling
ü Preemptive scheduling

14
MSc Nguyen Khanh Loi
Cooperative scheduling

v Traditional programing.
v Each task can only be executed when another task has completed.
v Weakness: one task can use up all CPU resources.

15
MSc Nguyen Khanh Loi
Round-robin scheduling

v Simple, easy to implement


v Scheduler generally employs time-sharing
v Each task is executed at a predetermined time (time slice) and has no priority

16
MSc Nguyen Khanh Loi
Preemptive scheduling

v Preemption is the act of temporarily interrupting an executing task, with the


intention of resuming it at a later time.

17
MSc Nguyen Khanh Loi
Non-preemptive scheduling

18
MSc Nguyen Khanh Loi
Inter-task communication and resource sharing

v Tasks need to communicate with each other or access shared


resources together.
v Inter-Thread Communication
ü Signal Events
ü Message Queue
ü Mail Queue
v Resource Sharing
ü Mutexes
ü Semaphores

19
MSc Nguyen Khanh Loi
Inter-Thread Communication: Signal Events

v Signals are used to trigger execution states between tasks.


v RTOS allow you to control or wait for signal flags

20
MSc Nguyen Khanh Loi
Inter-Thread Communication: Message Queue

v Message passing is another basic communication model between tasks.


v The data is passed from one thread to another in a FIFO-like operation.
v Using message queue functions, you can control, send, receive, or wait
for messages.

21
MSc Nguyen Khanh Loi
Inter-Thread Communication: Mail Queue

v A mail queue resembles a Message Queue.


v Data that is being transferred consists of memory blocks

22
MSc Nguyen Khanh Loi
Resource Sharing: Mutexes

v Mutual exclusion (widely known as Mutex) is used in various operating


systems for resource managemen.
v Many resources in a microcontroller device can be used repeatedly, but
only by one task at a time.
v Mutexes are used to protect access to a shared resource.

23
MSc Nguyen Khanh Loi
Resource Sharing: Semaphores

v Semaphores are used to manage and protect access to shared resources.


v Semaphores are very similar to Mutexes.
v Semaphore can be used to permit a fixed number of threads to access a
pool of shared resources.

Task Task

Task Task

24
MSc Nguyen Khanh Loi
Contiki OS

v Contiki is designed to address four essential


demand ROM
ü Need for a lightweight OS
ü Dynamic loading/ re-programming in a
resource constrained environment
ü Event-driven kernel model desired
ü Optional Protothread/ Preemptive
multithreading
v A Contiki system is partitioned into core and loaded
programs
ü Processes
§ Application programs
§ Services
ü Core
§ Kernel
§ Program loader
§ Libraries
25
MSc Nguyen Khanh Loi
Cooja GUI

26
MSc Nguyen Khanh Loi
Event-driven and multi-threaded

Event-driven Multi-threaded
- No wait() statements + wait() statements
- No preemption + Preemption possible
- State machines + Sequential code flow
+ Compact code - Larger code overhead
+ Locking less of a problem - Locking problematic
+ Memory efficient - Langer memory requirements

Multi threaded

Event-driven

27
MSc Nguyen Khanh Loi
Contiki model

v Event-driven systems treat processes as event handlers that


monopolize the CPU till completion Þ CPU is unable to
respond to external stimuli
v A multi-threaded model consumes a lot of memory.
v Contiki solves this problem by using a hybrid model:
ü Kernel is event-based
ü Multi-threading implemented as a library

28
MSc Nguyen Khanh Loi
Contiki process

v The process structure comprises of :


ü Process Control Block:
§ Contains the information
about the process name,
process state, pointer to
process thread.
§ Light weighted
ü Process Thread:
§ Contains the code of
process

29
MSc Nguyen Khanh Loi
The Contiki code

Header files

#include "contiki.h" Defines the name of


#include <stdio.h> /* For printf() */ the process

PROCESS(hello_world_process, "Hello world process");


Defines the process
AUTOSTART_PROCESSES(&hello_world_process); will be started every
time module is
PROCESS_THREAD(hello_world_process, ev, data) { loaded
PROCESS_BEGIN();
printf("Hello world\n");
PROCESS_END();
}

Threads must have Event parameter; process can receive data


an end statement process can respond to during an event
events

30
MSc Nguyen Khanh Loi
Process Scheduling

v Cooperative: In Cooperative the process are executed in a continuous


manner and it cannot be preempted until the process is completely executed.
After that the next process is scheduled.
v Preemptive: In Preemptive it stops the execution of cooperative process
whenever there is an interruption due to the I/O or timers.

31
MSc Nguyen Khanh Loi
The Contiki processes

33
MSc Nguyen Khanh Loi
Events in Contiki

vTimer events:
va process may set a timer
vgenerate an event when timer expires
vExternal events:
vI/O Interrupt.
vUART, push-button, a radio chip…
vInternal events:
vAny process has the possibility to address events to any other
process, or itself.
vInter-process communication

34
MSc Nguyen Khanh Loi
Events in Contiki

Event ID Description
PROCESS_EVENT_NONE 0x80 No event.
PROCESS_EVENT_INIT 0x81 Delivered to a process when it is started.

PROCESS_EVENT_POLL 0x82 Delivered to a process being polled.

PROCESS_EVENT_EXIT 0x83 Delivered to an exiting a process.

PROCESS_EVENT_SERVICE_REMOVED 0x84 Unused.

PROCESS_EVENT_CONTINUE 0x85 Delivered to a paused process when resuming execution.

PROCESS_EVENT_MSG 0x86 Delivered to a process upon a sensor event.

PROCESS_EVENT_EXITED 0x87 Delivered to all processes about an exited process.

PROCESS_EVENT_TIMER 0x88 Delivered to a process when one of its timers expired.

PROCESS_EVENT_COM 0x89 Unused.

PROCESS_EVENT_MAX 0x8a The maximum number of the system-defined events.

35
MSc Nguyen Khanh Loi
Contiki timers

v Contiki has two main timer types: etimer and rtimer


v Etimer: generates timed events
ü Declarations:
static struct etimer et;
ü In main process:
while(1) {
etimer_set(&et, CLOCK_SECOND);
PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));
etimer_reset(&et);
}
v Rtimer: uses callback function
ü Callback executed after specified time
rtimer_set(&rt, time, 0 , &callback_function, void *argument);

36
MSc Nguyen Khanh Loi
Contiki timers

37
MSc Nguyen Khanh Loi
Events in Contiki

38
MSc Nguyen Khanh Loi
Events in Contiki

p o st
s_
ces Process 3
Process 1 pro Process 2

39
MSc Nguyen Khanh Loi
Events in Contiki
#include "contiki.h"
#include "process.h"
#include <stdio.h> This message from process 1
PROCESS(myprocess1, "process 1"); This message from process 3
PROCESS(myprocess2, "process 2"); Process 2 is called by my process1
PROCESS(myprocess3, "process 3");
AUTOSTART_PROCESSES(&myprocess1,&myprocess2,&myprocess3);
PROCESS_THREAD(myprocess1, ev, data){
PROCESS_BEGIN();
static int data = 12;
process_post(&myprocess2, 0x100, &data);
printf("This message from process 1\n");
PROCESS_END();
}
PROCESS_THREAD(myprocess2, ev, data) {
PROCESS_BEGIN();
while(1){
PROCESS_WAIT_EVENT();
printf("Process 2 is called by my process1");
break;
}
PROCESS_END();
}
PROCESS_THREAD(myprocess3, ev, data) {
PROCESS_BEGIN();
printf("This message from process 3\n");
PROCESS_END();
}

40
MSc Nguyen Khanh Loi
Contiki Threading

41
MSc Nguyen Khanh Loi
Contiki Threading
#include "contiki.h" PROCESS_THREAD(mythread, ev, data){
#include "sys/mt.h" static int toggle = 0;
#include <stdio.h> static struct etimer timer;
PROCESS(mythread, "demo thread"); static struct mt_thread thread1, thread2;
AUTOSTART_PROCESSES(&mythread); int th1 = 1, th2 = 2;
static int count=0; PROCESS_BEGIN();
void solve(int data) mt_init();
{ mt_start(&thread1, solve, th1);
while(1){ mt_start(&thread2, solve, th2);
printf("[Thread %d] Step 1: etimer_set(&timer, CLOCK_SECOND * 2);
%d\n", data, count); while(1){
mt_yield(); PROCESS_WAIT_EVENT();
printf("[Thread %d] Step 2: if(ev == PROCESS_EVENT_TIMER) {
%d\n", data, count); if(toggle) {
mt_yield(); mt_exec(&thread1);
count ++; toggle--;
} } else {
mt_exit(); mt_exec(&thread2);
} toggle++;
}
etimer_reset(&timer);
}
}
mt_stop(&thread1);
mt_stop(&thread2);
mt_remove();
PROCESS_END();
}

42
MSc Nguyen Khanh Loi
LED Blinking

#include "contiki.h"
#include "dev/leds.h"
#include <stdio.h>
static struct etimer et;
static uint8_t i;
PROCESS(hello_world_process, "Hello world process");
AUTOSTART_PROCESSES(&hello_world_process);
PROCESS_THREAD(hello_world_process, ev, data) {
PROCESS_BEGIN();
etimer_set(&et, CLOCK_SECOND*1);
i =0;
while(1) {
PROCESS_YIELD();
if (ev==PROCESS_EVENT_TIMER) {
leds_toggle(LEDS_BLUE); //LEDS_ORANGE or LEDS_GREEN
printf("Timer fired: i=%d \n",i);
i++;
etimer_restart(&et);
}
}
PROCESS_END();
}

43
MSc Nguyen Khanh Loi
Running Contiki on a Hardware

v Write your code


v Compile Contiki and the application
make TARGET=sky
Make file

v If you plan to compile your code on the chosen platform more than
once;
make TARGE=sky savetarget
v Upload your code
chown :user /dev/ttyUSB0
sudo make TARGET=sky simple_process.upload
v Login to the device
sudo make TARGET=sky login

44
MSc Nguyen Khanh Loi

You might also like