0% found this document useful (0 votes)
184 views

Sensors and RTOS: Prof. Chung-Ta King

This document discusses sensors and real-time operating systems. It begins by describing several common sensors - photoresistors, ultrasonic sensors, and microphones - and providing examples of their use. It then gives an overview of embedded operating systems and real-time systems before introducing real-time operating systems. The document concludes by mentioning the FreeRTOS real-time operating system and some of its features like tasks and its integration with Arduino.

Uploaded by

ymcm2010
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
184 views

Sensors and RTOS: Prof. Chung-Ta King

This document discusses sensors and real-time operating systems. It begins by describing several common sensors - photoresistors, ultrasonic sensors, and microphones - and providing examples of their use. It then gives an overview of embedded operating systems and real-time systems before introducing real-time operating systems. The document concludes by mentioning the FreeRTOS real-time operating system and some of its features like tasks and its integration with Arduino.

Uploaded by

ymcm2010
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 41

CS4101 嵌入式系統概論

Sensors and RTOS

Prof. Chung-Ta King


Department of Computer Science
National Tsing Hua University, Taiwan
(Materials from Prof. P. Marwedel of Univ. Dortmund, Richard Barry, and
http://www.eecs.umich.edu/eecs/courses/eecs373/Lec/RTOS2.pptx)

National Tsing Hua University


Outline
• Sensors
- Photoresistors, ultrasonic sensors, microphone
• Embedded and real-time operating systems
- Embedded operating systems
- Overview of real-time systems
- Real-time operating systems (RTOS)
• FreeRTOS
- Tasks
- Link to FreeRTOS on Arduino

2
National Tsing Hua University
What Is a Sensor?
• A sensor is a device that detects either an absolute
value or a change in a physical or electrical quantity,
and converts that change into a useful input signal
(often analog signals) for a decision making center.

Data Processing, Actuator


Sensor or
Input Control, Connectivity
Output

3
National Tsing Hua University
Sensors
• For capturing physical data
• Sensors can be designed for virtually every physical
and chemical stimulus.
- Heat, light, sound, weight, velocity, acceleration, electrical
current, voltage, pressure, …
- Chemical compounds
• Many physical effects can be used for constructing
sensors
- Law of induction (generation of voltages in an electric
field), light-electric effects. …

4
National Tsing Hua University
Sensor Applications
Acceleration
• Gesture detection
Gyroscopic
• Tilt to control
• Tap detection Magnetic
• Position detection Ambient light sensing
• Orientation Temperature/humidity
Motion detection
Pressure
• Medical
• Barometer/altimeter
• Engine control/tire pressure Video/Audio/Lidar
• Surveillance
• HVAC applications
• Object detection
• Water level
• Depth detection
• Speech recognition
Touch
• Touch detection
• Appliance control panels Multiple sensors working
• Touch panels
together for next generation
applications  sensor fusion

5
National Tsing Hua University
Photoresistor
• Photoresistor is a light-controlled variable resistor,
made of a high resistance semiconductor
• The resistance of a photoresistor decreases with
increasing incident light intensity
- In the dark, a photoresistor can have a resistance as high
as several megohms (MΩ)
- While in the light, a photoresistor can have a resistance as
low as a few hundred ohms

6
National Tsing Hua University
Photoresistor and Arduino

7
National Tsing Hua University
Sample Code for Photoresistor
void setup() {
  Serial.begin(9600);
  pinMode(A0, INPUT);
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW); Analog input (0~5V)
} with 10-bit ADC
int pr_min = 400;
void loop() {
  int pr = analogRead(A0);
/* Read value of A0 input (must in range of 0~1023) */
Serial.println(pr);
  digitalWrite(13, pr > pr_min ? LOW : HIGH);
/* If input value > pr_min, then flash LED */
delay(1000);
}

8
National Tsing Hua University
Ultrasonic Sensor
• An ultrasonic sensor emits an ultrasound that travels
through the air; if there is an object or obstacle on
its path It will bounce back to the sensor
• Considering the travel time and the speed of the
sound, the distance can be calculated
• Ex.: HC-SR04
- Effectual angle: <15°
- Ranging distance : 2cm – 500 cm
- Resolution : 0.3 cm
- 40KHz ultrasonic signal
- 4 pins: Vcc, Trig, Echo, GND

9
National Tsing Hua University
Distance Calculation
• Set the Trig pin on at HIGH for > 10 µs to start
- That will send out an 8-cycle sound wave that can be
received in the Echo pin
- Echo pin will be HIGH based on the time in microseconds
that the sound wave traveled
- Distance = HIGH Duration*(Sonic:340m/s)/2
HC-SR04 Timing Diagram

10 µs tripper pulse
Trigger
Pin
8 x 40kHz sound wave
Transmit
Wave
Width proportional
Echo Pin to measured
distance

10
National Tsing Hua University
Distance Calculation: Example
• So in order to get the distance in cm we need to
multiply the received travel time value from the Echo
pin by 0.034 cm/µs and divide it by 2

11
National Tsing Hua University
Ultrasonic Sensor and Arduino
• HC-SR04 has 4 pins: Ground, Vcc, Trig, Echo
- Vcc is connected to the 5 volt pin, trig and echo pins to
any digital I/O pin on Arduino Uno

12
National Tsing Hua University
Ultrasonic Sensor and Arduino
• pulseIn()reads a pulse (either HIGH or LOW) on
a pin
- Syntax : pulseIn(pin, value) 
- If value is HIGH, pulseIn() waits for the pin to go HIGH,
starts timing, then waits for the pin to go LOW and stops
timing
- Returns the length of the pulse in microseconds or 0 if no
complete pulse was received within the timeout

Echo Pin
Time it takes pulse to leave and
return to sensors

13
National Tsing Hua University
Sample Code for Ultrasonic Sensor
const int trigPin = 12, echoPin = 11;
long duration, distance;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
digitalWrite(trigPin, LOW); // Clears the trigPin
delayMicroseconds(2);
/* Sets the trigPin on HIGH state for 10ms */
digitalWrite(trigPin, HIGH); delayMicroseconds(10);
digitalWrite(trigPin, LOW);
/* Reads Echo pin, returns sound travel time in ms */
duration = pulseIn(echoPin, HIGH);
/* Calculating the distance */
distance = duration*0.034/2;
}

14
National Tsing Hua University
KY-038 Microphone Sound Sensor
• Detect when sound has exceeded a set point
- Sound is detected via a microphone and fed into an
LM393 op amp
- The sound level set point is adjusted via an on-board
potentiometer
- When the sound level exceeds the set point, an LED on the
module is illuminated and the output is sent low

15
National Tsing Hua University
KY-038 Microphone Sound Sensor
• Module has four outputs: (inputs to Arduino)
- AO, analog output: real-time output voltage signal of the
microphone
- DO, digital output:
when the sound
intensity reaches a
certain threshold,
output high and low
signal
- Vcc
- GND

16
National Tsing Hua University
Sample Code for Digital Input
int Led = 13
int sensorpin = 12;
int val = 0;
void setup() {
pinMode(Led, OUTPUT);
pinMode(sensorpin, INPUT);
}

void loop() {
val = digitalRead(sensorpin);
/* digital interface will be assigned a value of
pin 12 to read val */
if (val == HIGH) { digitalWrite(Led, HIGH); }
else { digitalWrite(Led, LOW); }
}

17
National Tsing Hua University
Sample Code for Analog Input
int sensorPin = A0;
int ledPin = 13;
int sensorValue = 0;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop() {
sensorValue = analogRead(sensorPin);
digitalWrite(ledPin, HIGH);
delay(sensorValue);
digitalWrite(ledPin, LOW);
delay(sensorValue);
Serial.println(sensorValue, DEC);
}

18
National Tsing Hua University
Outline
• Sensors
- Photoresistors, ultrasonic sensors, microphone
• Embedded and real-time operating systems
- Embedded operating systems
- Overview of real-time systems
- Real-time operating systems (RTOS)
• FreeRTOS
- Tasks
- Link to FreeRTOS on Arduino

19
National Tsing Hua University
Operating Systems
• The collection of software that manages a
system’s hardware resources
User
- Often include a file system module,
a GUI and other components
Application
• Often times, a “kernel” is
understood to be a subset of Operating System
such a collection
• Characteristics HARDWARE

- Resource management
- Interface between application and hardware
- Library of functions for the application

20
National Tsing Hua University
Embedded Operating Systems
• Fusion of the application and the OS to one unit
• Characteristics:
- Resource management
• Primary internal resources User
- Less overhead
- Code of the OS and the Operating System + Application
application mostly reside in
ROM HARDWARE

21
National Tsing Hua University
Desktop vs Embedded OS
• Desktop OS: applications are compiled separately
from the OS

• Embedded OS: application is compiled and linked


together with the embedded OS
- On system start, application usually gets executed first,
and it then starts the RTOS
- Typically only part of RTOS (services, routines, or
functions) needed to support the embedded application
system are configured and linked in

(Dr Jimmy To, EIE, POLYU)

22
National Tsing Hua University
Characteristics of Embedded OS
• Embedded OS need to be configurable:
- No single OS fit all needs  install only those needed
- e.g., conditional compilation using #if and #ifdef
• Device drivers often not integrated into kernel
- Embedded systems often application-specific  specific
devices  move devices out of OS to tasks
Embedded OS Standard OS

kernel

23
National Tsing Hua University
Characteristics of Embedded OS
• Protection is often optional
- Embedded systems are typically designed for a single
purpose, untested programs rarely loaded, and thus
software is considered reliable
- Privileged I/O instructions not necessary and tasks can do
their own I/O, e.g., switch is address of some switch
Simply use
load register, switch
instead of OS call
• Real-time capability
- Many embedded systems are real-time (RT) systems and,
hence, the OS used in these systems must be real-time
operating systems (RTOSs)
24
National Tsing Hua University
What is a Real-Time System?
• Real-time systems have been defined as:
"those systems in which the correctness of the
system depends not only on the logical result of the
computation, but also on the time at which the
results are produced"
- J. Stankovic, "Misconceptions about Real-Time
Computing," IEEE Computer, 21(10), October 1988.

25
National Tsing Hua University
Real-Time Characteristics
• Pretty much typical embedded systems
- Sensors and actuators all controlled by a processor
- The big difference is timing constraints (deadlines)
• Tasks can be broken into two categories1
- Periodic Tasks: time-driven, recurring at regular intervals
• An air monitoring system taking a sample every 10 seconds
• Flash LEDs in 1 Hz
- Aperiodic: event-driven
• The airbag of a car having to react to an impact
• Press a button

1
Sporadic tasks are sometimes considered as a third category. They are tasks similar to aperiodic tasks but
activated with some known bounded rate, which is characterized by a minimum interval of time between
two successive activations.

26
National Tsing Hua University
Soft, Firm and Hard deadlines
• The instant at which a result is needed is called a
deadline
• If the result has utility even after the deadline has
passed, the deadline is classified as soft, otherwise it
is firm
• If a catastrophe could result if a firm deadline is
missed, the deadline is hard

27
National Tsing Hua University
Goals of an RTOS
• Manage to meet RT deadlines
• Also like
- Deadlines met
• Ability to specify scheduling algorithm
• Interrupts are fast
• Interrupt prioritization easy to set
- Tasks stay out of each others’ way
• Normally through page protection
- Device drivers already written (and tested!) for us
- Portable—runs on a huge variety of systems
- Nearly no overhead so we can use a small device!
• That is a small memory and CPU footprint

28
National Tsing Hua University
Requirements for RTOS
• Predictability of timing behavior of the OS
- Upper bound on execution time for all OS services
- Scheduling policy must be deterministic
- Period in which interrupts are disabled must be short (to
avoid unpredictable delays in processing critical events)
• OS should manage timing and scheduling
- OS has to be aware of task deadlines (unless scheduling is
done off-line)
- OS should provide precise time services with high
resolution
• Important if internal processing of the embedded system is
linked to an absolute time in the physical environment

29
National Tsing Hua University
Functionality of RTOS Kernel
• Processor management
• Memory management resource management
• Timer management
• Task management (resume, wait, etc.)
• Inter-task communication
• Task synchronization

30
National Tsing Hua University
Outline
• Sensors
- Photoresistors, ultrasonic sensors, microphone
• Embedded and real-time operating systems
- Embedded operating systems
- Overview of real-time systems
- Real-time operating systems (RTOS)
• FreeRTOS
- Tasks
- Link to FreeRTOS on Arduino

31
National Tsing Hua University
FreeRTOS
• FreeRTOS is nothing but software that provides
multitasking facilities
- Allows to run multiple tasks and has a simple scheduler to
switch between tasks (priority-based multitasking)
• Fully preemptive
• Always runs the highest priority task that is ready to run
• Context switch occurs if a task/co-routine blocks or a
task/co-routine yields the CPU
- Queues to communicate between multiple tasks
- Semaphores to manage resource sharing between
multiple tasks
- Utilities to view CPU utilization, stack utilization etc.
(http://www.socialledge.com/sjsu/index.php?title=FreeRTOS_Tutorial)

32
National Tsing Hua University
Tasks
• In FreeRTOS each thread of execution is called a task
- Tasks are implemented as C functions that must return
void and take a void pointer parameter:
void ATaskFunction(void *pvParameters);
- A task is a small program that has an entry point, will
normally run forever within an infinite loop, will not exit
void ATaskFunction(void *pvParameters) {
/* Each instance of task will have its own copy of variable
*/
int iVariableExample = 0;
/* A task is normally implemented in infinite loop */
for( ;; ) { /* task functionality */ }
/* Should the code ever break out of the above loop
then the task must be deleted. */
vTaskDelete(NULL); /* NULL: this task */
}
33
National Tsing Hua University
Task Creation
• xTaskCreate( pvTaskCode, pcName, usStackDepth,
pvParameters, uxPriority, pxCreatedTask )
- pvTaskCode: pointer to task entry function, implemented
to never return
- pcName: a descriptive name for the task to facilitate
debugging
- usStackDepth: size of task stack, specified as the number
of variables that the stack can hold
- pvParameters: pointer to parameters for the task
- uxPriority: priority at which the task should run
- pvCreatedTask: pass back a handle by which the created
task can be referenced

34
National Tsing Hua University
Example: Creating a Task
void setup() {
Serial.begin(9600);
while(!Serial){;} // wait for serial port to connect.
/* Now set up two tasks to run independently */
xTaskCreate(
vTask1, /* Pointer to function for the task */
(const portCHAR *) "Task1", /* Name for the task */
128, /* Stack Size */
NULL, /* NULL task parameter */
1, /* This task will run at priority 1 */
NULL ); /* Do not use the task handle */
xTaskCreate( vTask2, "Task2", 1000, NULL, 1, NULL );
/* Now the task scheduler, which takes over control of
scheduling individual tasks, is automatically started */
}

35
National Tsing Hua University
Example: Creating a Task
void vTask1(void *pvParameters) {
(void) pvParameters;

for( ;; ){
/* read the input on analog pin 0 */
int sensorValue = analogRead(A0);
/* print out the value you read */
Serial.println(sensorValue);
/* one tick delay in between reads for stability */
vTaskDelay(1);
}

36
National Tsing Hua University
Link to FreeRTOS on Arduino 
• There is a FreeRTOS implementation in Arduino IDE
- Go to “Sketch” -> “Include Library” -> “Manage
Libraries…” to open Arduino IDE Library manager

37
National Tsing Hua University
Link to FreeRTOS on Arduino
• In the Arduino IDE Library manager (from Arduino
Version 1.6.8) look for the FreeRTOS Library
- Type: “Contributed” and Topic: “Timing”

38
National Tsing Hua University
Link to FreeRTOS on Arduino  
• Under the “Sketch” -> “Include Library”, ensure that
the FreeRTOS library is included in your sketch

39
National Tsing Hua University
Example: Blink_AnalogRead
#include <Arduino_FreeRTOS.h>
/* define two tasks for Blink & AnalogRead */
void TaskBlink(void *pvParameters);
void TaskAnalogRead(void *pvParameters);
void setup() {
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect.
}
/* Now set up two tasks to run independently */
xTaskCreate( TaskBlink, (const portCHAR *)"Blink", 128,
NULL, 2, NULL );
xTaskCreate( TaskAnalogRead, (const portCHAR *)
"AnalogRead", 128, NULL, 1, NULL );

40
National Tsing Hua University
Example: Blink_AnalogRead
void TaskAnalogRead(void *pvParameters) {
(void) pvParameters;

for (;;) {
/* read the input on analog pin 0 */
int sensorValue = analogRead(A0);
/* print out the value you read */
Serial.println(sensorValue);
/* one tick delay in between reads for stability */
vTaskDelay(1);
}
}

41
National Tsing Hua University

You might also like