MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 1
Programming GPIO pins
Timers / Counters, Watchdog Timer
PWM generation
ADC, DAC, LED, switches
Keypad, LCD
3
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 3
Nucleo Features
STM32L152RE ultra-low-power ARM Cortex-M3 based microcontroller
Two extension connectors: Arduino Uno and ST Morpho
Embedded ST –LINK/V2-1 Debugger/Programmer
Flexible board power supply: 3.3 V, 5 V, 7 - 12 V
User LED (LD2), Two push buttons: USER and RESET
MBED Enabled
Interfaces supported on USB: Virtual COM port, Debug port, Mass
storage (USB Disk drive) for drag 'n‘ drop programming
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 4
STM32 Nucleo-64 - Board Details
Image credit: Zephyr Ref. URL : https://docs.zephyrproject.org/latest/boards/arm/nucleo_l152re/doc/index.html
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 5
STM32 Nucleo-64 - Board Details
Image credit: Zephyr Ref. URL : https://docs.zephyrproject.org/latest/boards/arm/nucleo_l152re/doc/index.html
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 6
STM32 Nucleo-64 - Pin Details (Arduino Headers)
Image credit: arm MBED, Ref. URL : https://os.mbed.com/forum/electronics/topic/15346/?page=1#comment-52189
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 7
STM32 Nucleo-64 - Pin Details (Morpho Headers)
Pins Legend
Image credit: arm MBED, Ref. URL : https://os.mbed.com/forum/electronics/topic/15346/?page=1#comment-52189
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 8
STM32 Nucleo-64 - Pin Details (Morpho Headers)
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 9
STM32L152RE Microcontroller Features
Package Type : LQFP64 (Low-profile Quad Flat Package)
Instruction set Architecture : RISC (Reduced Instruction Set Architecture)
Data bus size : 32-bit
Address bus size : 32-bit
Operating Frequency : 32 MHz max
Operating Voltage : 1.65 V to 3.6 V
Program memory (flash) : 512 KB
Data memory (SRAM) : 80 KB
Data memory (EEPROM) : 16 KB
Input/output ports : 51(Port A(16), B(16), C(16), D(1),H(2))
Timers :9
Watch-dog Timers :2
Interrupts : 56
ADC modules (12-bit) : 21 channels
DAC modules (12-bit) : 2 channels
PWM (used with timers) : 18
Serial communication : SPI(8), USART(5), I2C(2)
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 10
STM32L152RE - Architecture
STM32L152RE – Pin diagram
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 11
Keil Studio Cloud is the successor to the Mbed Online Compiler, and allows you to
develop Mbed 2, Mbed OS 5 and 6 projects on supported Mbed-enabled boards.
Free to use, browser-based IDE for the evaluation and development of embedded,
IoT, and Machine Learning software for Cortex-M devices.
You can compile projects using Arm Compiler 6, run the projects directly on
supported development boards, and debug from supported browsers without the
need to install any software.
You can access Keil Studio Cloud using an Arm or Mbed account (use below link)
and get started by opening a reference design to evaluate.
https://studio.keil.arm.com
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 12
13
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 13
GPIO pin stands for the General-purpose input/output pin on MCU.
In STM-32 NUCLEO-L152RE development board, there 51 GPIO pins are
available and they are organized as Port A(16), B(16), C(16), D(1),H(2).
Most of the GPIO pins are shared with digital or analog or alternate functions, and
can be individually remapped using dedicated registers.
Each of the GPIO pins can be configured by software as output, as input or as
peripheral alternate function.
The use of GPIO is driving LEDs, reading digital signals from switch, issuing
interrupts, and many.
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 14
GPIO pins of STM32 Nucleo L152RE board
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 15
Internal block of the typical STM32 MCU
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 16
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 17
API required:
DigitalOut Identifier(PinName) - Used configure GPIO pin as digital output pin
- Identifier: User defined name to access this digital pin
- PinName: Name of the pin as specified in the Nucleo board pin details
- Examples: DigitalOut myled(LED1); //LED1 is an onboard LED
DigitalOut myA3(PC_0); //PC_0 is 0th pin of port C
operator= (int value) - used to set the digital output as 0 or 1. A shorthand for write() API.
- Example: myA3=1; //set the PC_0 digital output pin value as HIGH or 1
wait(s) – Used to pauses the execution of a program for the amount of time (in seconds)
- s: Float value indicate the number of seconds to pause.
- Example: wait(1.0); //will pause the program for 1 second.
wait(0.5); //will pause the program for 0.5 second
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 18
Example-1 - Blinking of LED on Board
Write a program to blink an on-board LED (LD2) of the STM32 Nucleo-64
board with 0.5s delay between ON and OFF state using Keil Studio Cloud IDE.
Program: Output:
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 19
Example-2 - Blinking of 4 LEDs alternatively in pairs
Write a program to blink four LEDs in alternatively in pairs (1010 and 0101 pattern) with 0.5
Sec delay between each. Implement and verify this logic on the STM32 Nucleo-64 board
using Keil Studio Cloud IDE.
Program: Connection diagram:
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 20
Example-3 - Display Hexadecimal counting sequence in LEDs
Write a C++ program with mbed APIs to display Hexadecimal Counting Pattern from
0 to 15 by blinking LEDs. Implement and verify this logic on the STM32 Nucleo-64
board using Keil Studio Cloud IDE.
API required:
BusOut Identifier(PinNames) - Used to combine a number of DigitalOut pins to write them
at once. You can have up to 16 pins in a Bus.
- Identifier: User defined name to access this digital pin
- PinNames: Name of the pins as specified in the Nucleo board pin details
- Examples: BusOut myleds(a,b,c,d,e,f,g,h); //a-LSB and h-MSB
BusOut hexa(PA_3,PB_13,PAB_14,PB_15); //PA_3-LSB, PB_15-MSB
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 21
Example-3 - Display Hexadecimal counting sequence in LEDs
Program:
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 22
Example-4 - Controlling LED Blinking Sequence using Switch
Write a C++ program with mbed APIs to blink one LED at a time serially in a group of 4 LEDs
using switch.
If switch is LOW, blink the LEDs one at a time from left to right (1000, 0100, 0010, 0001
pattern) with 0.5 Sec delay between each.
If switch is HIGH, blink the LEDs one at a time from right to left (0001, 0010, 0100, 1000
pattern) with 0.5 Sec delay between each.
Implement and verify this logic on the STM32 Nucleo-64 board using Keil Studio Cloud IDE.
API required:
DigitalIn Identifier(PinName) - To read the value of a digital input pin (logic level 0 or 1).
- Identifier: User defined name to access this digital pin
- PinName: Name of the pins as specified in the Nucleo board pin details
- Examples: DigitalIn switch(PA_3); //PA_3 is configured as Digital input pin
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 23
Program:
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 24
Exercise-1 - Controlling LED Blinking Sequence using Switch
Write a C++ program with mbed APIs to design a traffic light controller system for a four lane junction (North,
South, East, West) to coordinate the traffic moves.
Use 12 LEDs (3 for each direction) for traffic light signal and Switch decide the traffic light mode.
If Switch is LOW, traffic light operate in late night mode in which only yellow light (LED) in all lanes blink
for every 2 seconds continuously.
If Switch is HIGH then traffic light operates in normal signalling operation in which similar signal sequence
are applied in opposite lanes (for ex. east and west) with Green signal for 15 Sec. then Yellow for 2 Sec.
and then Red. Meanwhile, north & south lane will be at red.
Once this sequence is completed, switch to next opposite lanes (i.e north & south) and carry out signalling
with Green signal for 10 Sec. then Yellow signal for 2 Sec. and then Red meanwhile, east & west lane will
be in red.
Continuously switch between these two signal sequence.
Implement and verify this logic on the STM32 Nucleo-64 board using Keil Studio Cloud IDE.
Hint: Use 6 Digital pins for lane signalling LEDs (3 for East & West, 3 for North & South) and one Switch for Mode selection
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 25
Example-5 - Interfacing with IR Sensor
Write a C++ program with mbed APIs to test the IR sensor by switching ON the LED
according to the status of the IR sensor. Implement and verify this logic on the STM32
Nucleo-64 board using Keil Studio Cloud IDE.
IR Sensor:
An infrared sensor (IR sensor) is an optoelectronic device widely used to sense some object of the
surroundings. It can measure the heat of an object as well as detects the motion.
IR sensor typically has an IR LED (transmitter emitting IR radiations) & an IR photodiode (responds to
the infrared light), and combining these two gives way to a photo-coupler or optocoupler.
The resistance of photo-diode and its output voltage is directly proportional to the infrared light.
IR sensor can be used for proximity detection, item counter, line following robot etc.,
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 26
IR Sensor pin details
Program:
Connection Diagram:
+5V
GND
PC_6
STM32 NUCLEO
BOARD
PC_8
GND
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 27
Example-7 - Display 0 to 9 in 7-Segment display
Write a C++ program with mbed APIs to display 0 to 9 on 7-segment display unit.
Implement and verify this logic on the STM32 Nucleo-64 board using Keil Studio
Cloud IDE.
7-Segment display:
Seven segment displays are the output display devices that provide a way to display information in
the form of alphanumeric characters and digits.
This is most commonly used in many gadgets, and electronic appliances like digital meters, digital
clocks, microwave oven and electric stove, etc.
These displays consist of seven segments (indicated as A-G) of light emitting diodes (LEDs) and that
is assembled into a structure like numeral 8. In addition, an extra 8th segment is used to display dot
(indicated as H/DP), which is useful while displaying non integer number.
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 28
Example-7 - Display 0 to 9 in 7-Segment display
A seven segment displays are generally available in ten pin package, 8 pins relate to the 8 LEDs,
the remaining two pins at middle are internally shorted.
These segments come in two outlines they are common cathode and common anode.
In common cathode configuration, the all LED’s negative terminals are connected to the common ground
pin hence HIGH on corresponding positive pin glow particular LED.
In a common anode arrangement, the common pin is given to a logic HIGH and the pins of the LED are
given LOW to display a number.
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 29
Example-7 - Display 0 to 9 in 7-Segment display
Hexa Decimal Individual Segments Illuminated for Common Cathode configuration
Value Digit dp (PC_7) g (PC_6) f (PC_5) e (PC_4) d (PC_3) c (PC_2) b (PC_1) a (PC_0)
0x3F 0 0 0 1 1 1 1 1 1
0x06 1 0 0 0 0 0 1 1 0
0x5B 2 0 1 0 1 1 0 1 1
0x4F 3 0 1 0 0 1 1 1 1
0x66 4 0 1 1 0 0 1 1 0
0x6D 5 0 1 1 0 1 1 0 1
0x7D 6 0 1 1 1 1 1 0 1
0x07 7 0 0 0 0 0 1 1 1
0x7F 8 0 1 1 1 1 1 1 1
0x6F 9 0 1 1 0 1 1 1 1
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 30
Program: Connection Diagram:
(Common cathode)
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 31
Exercise-2 – Letter counter
Use the slotted opto-sensor (IR sensor), push-button switch and one seven-segment
LED display to create a simple letter counter. Increment the number on the display
by one every time a letter passes the sensor. Clear the display when the push
button is pressed. Use an 7-Segment LED to display count from 0 to 9.
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 32
33
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 33
Pulse width modulation(PWM) is a commonly used control technique that generates analog
signals from digital devices such as microcontrollers.
By rapidly switching between ON and OFF state, the digital signal is modified to imitate
an analog signal.
PWM signal is used in applications such as controlling motors, lights, actuators, etc.,
In STM-32 NUCLEO-L152RE development board, PWM signal is generated as one of the
function of timers and there are 18 PWM supports pins are available.
The output voltage of the PWM signal will be the percentage of the duty cycle. For
example,
For a 100% duty cycle, if the operating voltage is 5 V then the output will also be
34 5 V.
If the duty cycle is 50%, then the output voltage will be 2.5 V.
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 34
PWM signal stays “ON” for a given time and stays “OFF” for a certain time, the
percentage of time for which the signal remains “ON” is known as the duty cycle.
If the signal is always “ON,” then the signal must have a 100 % duty cycle. The
formula to calculate the duty cycle is given as follows:
Duty Cycle= Ton / (Ton +Toff) * 100 (percentage)
Period = Ton+Toff
Period = 1/Frequency
35
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 35
36
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 36
STM32 Nucleo-64 - Pin Details (Morpho Headers)
Pins Legend
37
Image credit: arm MBED, Ref. URL : https://os.mbed.com/forum/electronics/topic/15346/?page=1#comment-52189
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 37
API required:
38
https://os.mbed.com/docs/mbed-os/v6.16/apis/pwmout.html
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 38
Example-1 Controlling LED brightness with 75% duty cycle
Write a C++ program with mbed APIs to control the brightness of the LED using a
PWM signal with duty cycle 75%. Assume PWM period as 2 Seconds. Implement and
verify this logic on the STM32 Nucleo-64 board using Keil Studio Cloud IDE.
Program:
39
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 39
Example-2 - Increasing/decreasing LED brightness using variable duty cycle
Write a C++ program with mbed APIs to gradually increase and decrease LED brightness
using PWM signal with variable duty cycle. Assume the LED is connected to PC_8 PWM pin,
time period of the PWM signal as 10ms, increment/decrement duty cycle value is 10% and
delay between each increment/decrement duty cycle is 0.5s. Implement and verify this logic
on the STM32 Nucleo-64 board using Keil Studio Cloud IDE.
40
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 40
Program:
41
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 41
Example-3 - Generate a music note SA-RE-GA-MA-PA-THA-NEE using PWM
Write a C++ code with mbed APIs to generate a music note SA-RE-GA-MA-PA-THA-NEE on
the buzzer using PWM signal. Frequency for each music tone is listed below.
Implement and verify this logic on the STM32 Nucleo-64 board using Keil Studio Cloud IDE.
42
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 42
Program:
43
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 43
Exercise-1 - Warning signals system for Automotive
Write a C++ program with mbed APIs to design a warning signals system for Automotive with the
following logic.
Use 4 switch and one buzzer to generate four warning signals such as indicator signal, horn
sound, seat belt warning and reversing signal.
Assume each of these warning signals must have 50% duty cycle and 0.5s delay between their
ON and OFF state.
Activate the respective warning signal as per the following switch status,
If Switch-1 is HIGH, generate a indicator signal (2 Hz)
If Switch-2 is HIGH, generate a Horn signal (400 Hz)
If Switch-3 is HIGH, generate a Seat belt warning signal (612 Hz)
If Switch-4 is HIGH, generate a Reversing signal (1000 Hz)
If all switches are LOW, the buzzer should be in OFF state
Implement and verify this logic on the STM32 Nucleo-64 board using Keil Studio Cloud IDE.
Hint: Use 4 Digital pins for switches to select the warning signal(Busin) & one buzzer to generate the different
44 warning
sound(PWM).
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 44
Introduction to Servo Motor
A Servo Motor is a type of actuator that provides high precision control of linear or
angular position.
A simple servo motor consists of a small DC motor, a potentiometer for providing position
feedback, a gear system for increased torque and a control system.
Servo Motors are used in applications where very high precision motion is required like
assembly robots, security cameras, solar tracking system etc.
Typically, simple servo motors consists of three wires, colour coded as Red(supply),
Brown(ground) and Orange (control signal).
A servo motor is controlled by sending a series of pulses through the signal line. The
frequency of the control signal should be 50Hz or a pulse of 20ms.
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 45
Introduction to Servo Motor
The control signal is usually a PWM signal, unlike PWM signal used to control the speed of
DC Motor, it is used to determine the position of the servo motor and these type of servos
can usually rotate 180 degrees
Generally pulses with 1ms duration correspond to 0° degrees position, 1.5ms duration to
90° and 2.5ms to 180° (may vary with different models) .
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 46
Example-4 - Controlling the servo motor at one degree at a time
Write a program to control the servo motor by rotating slowly from 0 degrees to 180
degrees, 45 degree at a time. When the motor has to be rotated 180 degrees, it will return
to the initial position. Implement and verify this logic on STM32 board.
Program #include "mbed.h"
PwmOut PWM1(PC_8); Connection diagram
int main() {
while(1){
PWM1.period_ms(20);
PWM1.pulsewidth_us(500);
wait(1);
PWM1.pulsewidth_us(1000); // 45 degree
wait(1);
PWM1.pulsewidth_us(1500); // 90 degree
wait(1);
PWM1.pulsewidth_us(2000); // 135 degree
wait(1);
PWM1.pulsewidth_us(2500); // 180 degree
wait(1);
}
}
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 47
48
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 48
Introduction to USB Virtual Serial Port
The mbed Microcontroller can communicate with a host PC through a "USB Virtual Serial
Port" over the same USB cable that is used for programming.
This enables you to:
Print out messages to a host PC terminal
Read input from the host PC keyboard
Communicate with applications and programming languages running on the host
PC that can communicate with a serial port, e.g. python, java and so on.
The Serial Interface can be used on supported pins and USBTX/USBRX
Note that USBTX/USBRX are not pins; they represent the pins that route to the interface
USB Serial port so you can communicate with a host PC.
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 49
Example-1 - Controlling on-board LED using USB Virtual serial port
Write a C++ code with mbed APIs to receive a character (H) from PC via host
terminal application (Tera term) & switch ON the LED. For all other character LED1
must be in OFF state. Implement and verify this logic on the STM32 Nucleo-64 board
using Keil Studio Cloud IDE.
API required:
Serial Identifier(USBTX, USBRX) - Used to access “USB Virtual Serial Port”
- Identifier: User defined name to access this USB Virtual Serial Port
- Examples: Serial pc(USBTX, USBRX); //Accessing USB Virtual Serial Port using
the identifier name pc
putc - Used to send a character from Nucleo board to host PC
getc - Used to read a character from host PC to Nucleo board
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 50
Program:
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 51
Example-2 - Increasing/Decreasing Brightness Using Serial Port
Write a C++ program with mbed APIs to gradually increase and decrease LED brightness by receiving a
character (“i” for increase and “d” for decrease) from PC via host terminal application (Tera term) using PWM
signal with variable duty cycle. Implement and verify this logic on the STM32 Nucleo-64 board using Keil Studio
Cloud IDE.
Program:
•The default period is
0.020s, and the default
pulse width is 0.
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 52
Introduction to ADC
An Analog to Digital Converter(ADC) is a electronic circuit that converts analog signal into
digital form which could be understood by a digital device
The list of possible analog input signals is endless such as s light, temperature, speed,
pressure etc.
ADC effectively measures the analog input voltage and gives a binary output number
proportional to its size.
ADC types: Successive Approximation, Dual slope, delta-sigma, flash type etc.,
ADC has maximum and minimum permissible input values.
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 53
Introduction to ADC
Not all the pins on a microcontroller have the ability to do analog to digital conversions.
On the STM32 Nucleo L152RE board, these pins have an ‘Analog In’ indicate these pins can
read analog voltage.
There are more than 20 analog channels available supporting Analog In function
The ADC on the Nucleo is a 12-bit ADC meaning it has the ability to detect 4096 (2^12)
discrete analog levels.
An input of 0 volts would result in a decimal 0 and an input of 5 volts would give the
maximum of 4096.
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 54
Introduction to ADC
The resolution for an ADC is the smallest distinguishable change in analog input that causes
the digital output to change. 𝑽𝒓
Resolution = 𝒏
𝟐
Nucleo ADC is 12-bit. This leads to a resolution of 5/4096, or 1.2 mV.
𝑽𝒊 𝟐.𝟏𝟐𝐕
ADC conversion D= × 𝟐𝒏 D=
𝟓
× 𝟒𝟎𝟗𝟔 = 𝟏𝟕𝟑𝟕
𝑽𝒓
Where, D the digital output value, Vi is the input voltage, Vr the reference voltage, n no. of
bits in the output
The output binary number D is an integer, for an n-bit number can take any value from 0 to
(2n - 1).
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 55
API required:
AnalogIn Identifier(PinName) – Used to access ADC of the specified pin name.
- Identifier: User defined name to access the specified ADC pin
- PinName: Name of the pins as specified in the Nucleo board for ADC pin
read() - Read the input voltage, represented as a float in the range 0 to 1. For example,
if you have a 3.3V system and the applied voltage is 1.65V, then AnalogIn() reads 0.5 as
the value.
read_voltage () - Read the input voltage in volts
get_reference_voltage () - Gets this AnalogIn instance's reference voltage.
operator float () - An operator shorthand for read()
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 56
Example-3 - Increasing/Decreasing Brightness Using Potentiometer
Write a C++ program with mbed APIs to gradually increase and decrease LED brightness by
changing the position of the Potentiometer via ADC. Also print it’s voltage value on serial
monitor. Use Implement and verify this logic on the STM32 Nucleo-64 board using Keil Studio
Cloud IDE.
Program:
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 57
Exercise-1 - Battery level indicator
Write a C++ program with mbed APIs to design a battery level indicator system using
potentiometer and LEDs. The system must display the different level of the voltage with
the help of 5 LEDs as per following conditions.
If the voltage is between 0 to 1V glow LED1 and display “0 to 1V” in serial monitor
If the voltage is between 1 to 2V glow LED1 and LED2 “1 to 2V” in serial monitor
If the voltage is between 2 to 3V glow LED1 to LED3 “2 to 3V” in serial monitor
If the voltage is between 3 to 4V glow LED1 to LED4 “3 to 4V” in serial monitor
If the voltage is between 4 to 5V glow LED1 to LED5 “4 to 5V” in serial monitor
Implement and verify this logic on the STM32 Nucleo-64 board using Keil Studio
Cloud IDE.
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 58
Introduction to LDR
Light Dependent Resistor (LDR) or Photoresistor, is a passive electronic component, basically
a resistor which has a resistance that varies depending of the light intensity.
The resistance is very high in darkness but when there is light that falls on the LDR, the
resistance is falling down to low value.
LDRs are very useful in many electronic circuits, especially in alarms, switching devices,
clocks, street lights and more.
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 59
Example-4 - Auto intensity street light controller
Write a program to design auto intensity street light controller. This system helps the street light to get switched
on automatically as per surrounding brightness. For example, sometimes when the weather become hazy its quite
difficult to see anything then at that point this auto intensity street light gets switched on based on present lighting
condition. Implement and verify this logic on STM32 board.. Connection diagram
Program
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 60
Exercise-2 - Solar tracking system
Write a program to design a solar tracking system for harvesting solar energy efficiently by
the solar panels. This system is constructed by fitting two LDRs, angled away from each
other by around 90, to a servo. Continuously read the light value sensed by the two
LDRs and rotates the servo so that each is receiving equal light. As a sun-tracking
system will be located to track the sun from sunrise to sunset, i.e. not more than 180.
Also, display both LDR values and present Servo motor position on serial window. Implement
and verify this logic on STM32 board.
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 61
62
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 62
Introduction to DAC
In STM32 Nucleo L152RE, the two 12-bit buffered DAC channels (PA_4 & PA_5) can be
used to convert digital signals into analog voltage signal outputs.
DAC has a digital input, represented by D, and an analog output, represented by Vo.
Here, Vr is the value of the voltage reference, D is the value of the binary input word, n is
the number of bits in that word, and Vo is the output voltage.
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 63
Introduction to DAC
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 64
Example-1 – Generate analog voltage and turn on On-board LED
Write a C++ program with mbed APIs to gradually increase analog output voltage on PA_4 and SWITCH ON
on-board LED when output voltage is >0.5VCC. Also print it’s voltage value on serial monitor. Use Implement and
verify this logic on the STM32 Nucleo-64 board using Keil Studio Cloud IDE.
Program:
#include "mbed.h"
AnalogOut aout(PA_4);
DigitalOut dout(LED1);
int main(void)
{
Note: By default “aout” takes a floating point number
while (1)
between 0.0 and 1.0 and outputs this to PA_4.
{
for (float i = 0.0f; i < 1.0f; i += 0.1f)
{
aout = i;
printf("aout = %1.2f volts\n", aout.read() * 5);
dout = (aout > 0.5f) ? 1 : 0; // turn on the led if the voltage is greater than 0.5f * VCC
wait(1.0f);
}
}
}
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 65
Example-2 – Generate Saw tooth waveform on DAC output and View on oscilloscope
Program:
#include "mbed.h"
AnalogOut Aout(PA_4);
float i;
int main() {
while(1){
for (i=0;i<1;i=i+0.001)
{ // i is incremented in steps of 0.001
Aout=i;
wait(0.001); // wait 1 millisecond
}
}
}
Exercise-1 – Generate Triangular waveform (one that counts down as well as up) on DAC output and View
on oscilloscope
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 66
67
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 67
LCD stands for Liquid Crystal Display and It is one kind of electronic display
used in wide range of applications like CD/DVD players, Digital Watch etc.,
The main benefits of LCD are inexpensive; simply programmable, and there
are no limitations for displaying custom characters, simple animations, etc.
The liquid crystals are made up of a part solid, part liquid substance that can
be "twisted" by applying electrical voltage to them.
In the normal state, the crystals inside the liquid are twisted, and light can pass
through, once the crystals are subjected to an electrical current, they untwist,
blocking the light and makes the portion of the screen black.
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 68
Among different sizes of LCDs (16x1, 16x2, 16x4, 20x4), 16x2 LCD display
is very basic module and is very commonly used in various devices and circuits.
A 16x2 LCD means it can display 16 characters per line and there are 2 such
lines. In this LCD each character is displayed in 5x7 pixel matrix.
The 16x2 intelligent alphanumeric dot matrix display is capable of displaying
224 different characters and symbols.
This LCD has two registers, namely, Command and Data.
Command register stores various commands given to the display.
Data register stores data to be displayed.
69
Vss- Ground pin
Vcc- Supply (+5V)
VEE- Contrast pin (0.4 to 0.9V)
RS- Register select (1- data register, 0 – command register)
R/W - Read/ Write mode ( 1-Read mode, 0- Write mode)
E- Enable the LCD module (high to low at this pin enable LCD)
DB0-DB7- Data pins (command and data are send to display)
LED+ & LED- - Anode and Cathode of backlight
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 70
This library allows an Nucleo board to control LiquidCrystal displays (LCDs)
based on the Hitachi HD44780 chipset in 4-bit mode
In Nucleo board TextLCD library is used as #include "TextLCD.h"
The mbed TextLCD library performs the laborious LCD setup routine for us also
tells the LCD object which pins are used for which functions.
To use the TextLCD library - create a named TextLCD object.
Syntax: TextLCD lcd(rs, enable, d4, d5, d6, d7);
Example: TextLCD lcd(PC_0,PC_1,PB_0,PA_4, PA_1, PA_0);
lcd.printf(“Text to print”)- the character to write to the display
For more details Refer: https://os.mbed.com/users/simon/code/TextLCD/
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 71
Functions Description
TextLCD (PinName rs, PinName e, PinName d4, Create a TextLCD interface.
PinName d5, PinName d6, PinName d7)
putc (int c) Write a character to the LCD.
printf (const char *format,...) Write a formated string to the LCD.
locate (int column, int row) Locate to a screen column and row.
cls () Clear the screen and locate to 0,0.
For more details Refer: https://os.mbed.com/users/simon/code/TextLCD/docs/tip/classTextLCD.html
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 72
Method-1 for online compiler:
• Download LCD library from https://os.mbed.com/users/simon/code/TextLCD/ as zip file and extract files
• Add “TextLCD.cpp” and “Text.h” files into project created in Keil studio by right clicking the project folder
and select “upload files…” option
• Now Check whether “TextLCD.cpp” and “TextLCD.h” files included in your project folder or not
Method-2 for offline compiler:
• In Keil studio, right clicking the project folder and select “Add Mbed Library…” option and provide the link
https://os.mbed.com/users/simon/code/TextLCD/ in URL field then click next
• In the net pop window select “default” under “Release, branch, or tag” field and click finish
• Now Check whether “TextLCD.cpp” and “TextLCD.h” files included in your project folder or not
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 73
Example-1 - Display Name and Register number on LCD
Write a program for 16x2 LCD to display your register number (ex: “20BEC1001”) at row-0
3rd position and your name (ex:“ABCDEFGH”) at beginning of the row-1. Assume LCD
operates in 4-bit with EN and RS active state. Design and verify this logic on Nucleo 152RE
board using online Keil Studio platform.
Program Output
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 74
Example-1 - Display Name and Register number on LCD
Pin connections Connection diagram
LCD Pin No. LCD pin Name Nucleo pins
1 VSS GND
2 VCC U5V
3 VEE Pot middle pin
4 RS PC_0
5 RW GND
6 E PC_1
7 D0 not connected
8 D1 not connected
9 D2 not connected
10 D3 not connected
11 D4 PB_0
12 D5 PA_4
13 D6 PA_1
14 D7 PA_0
15 LED+ U5V
16 LED- GND
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 75
Example-2 Read the input from Serial Window and display it in LCD
Write a program to accepts serial input character via Teraterm software from a host
computer and displays it on the LCD. Assume LCD operates in 4-bit with EN and RS active
state. Design and verify this logic on Nucleo-152RE board using online Keil Studio platform.
Program
Output
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 76
Example-3 - Display a POT value on the LCD
Write a program to display the potentiometer value with 4 decimal places on the LCD display
on row-1 5th position. Assume LCD operates in 4 bit with EN and RS active state. Design and
verify this logic on Nucleo 152RE board using online Keil Studio Platform.
Program
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 77
78
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 78
Keypads are input devices that are being widely used in many embedded system
applications including ATM machines, door locks, and vending machines etc.,.
Keypads are used to take input from the user as numbers or characters for further
processing such as password, menu selection and navigating among different options.
One of the most commonly used keypads is the matrix keypad with 4×4 or 4×3 buttons.
The matrix keypad consists of pushbutton that are connected to the row and column lines.
There is one pin for each column and one pin for each row. So the 4×4 keypad has 4+4=8
pins, while the 4×3 keypad has 4+3=7 pins.
The column pins (Col 1–Col4) are connected to the microcontroller as the inputs pins and the
rows pins (Row 1–Row 4) are connected to the output pins of the microcontroller.
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 79
Internal structure of 4x4 keypad
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 80
STEP-1
STEP-2
STEP-3
STEP-4
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 81
The status of each switch is determined by Scanning the rows or columns. If low logic is
given to all the Rows and high logic is given to each Column.
Keypad Scanning
Find Column number
When a switch/key is pressed, the corresponding row and column will get short, allowing current to
flow between them. When the key ‘4’ is pressed, for instance, column 1 and row 2 are connected.
The output of the corresponding column goes to go low.
Since we have made all the rows zero so this gives the column number of the pressed key.
Find Row number
After the detection of the column number, the controller set’s all the rows to high.
Each row is one by one set to zero by the microcontroller and the earlier detected column is checked
and obviously, it becomes zero.
The row due to which the column gets zero is the row number of the pressed key.
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 82
#include “keypad.h” is a mbed library for using 4x4 matrix style keypads with the STM32
Nucleo and supports multiple keypresses.
Default keypad pin map is given below but pin map can be modified by editing the pin
map details given in keypad.h header file.
Functions Description
Keypad identifier (PinName col0, PinName col1,
PinName col2, PinName col3, PinName row0, Create a 4x4 (col, row) or 4x4 keypad interface
PinName row1, PinName row2, PinName row3)
char getKey () Returns the letter of the pressed key
boolgetKeyPressed () Detects if any key was pressed.
void enablePullUp () Enables internal PullUp resistors on the columns pins.
For more details Refer: https://os.mbed.com/users/rlanghbv/code/KeypadLib/shortlog/
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 83
Example-1 Read the input from keypad and display it in LCD & Serial monitor
Write a mbed C++ program to accepts input from a 4x4 keypad and displays it on the
serial monitor and LCD. Assume LCD operates in 4-bit with EN and RS active state. Design and
verify this logic on Nucleo 152RE board using online Keil Studio platform.
Procedure to add “Keypad” library in online compiler:
• Visit this link https://os.mbed.com/users/rlanghbv/code/KeypadLib/shortlog/ and click on “Import
into Keil studio” option and copy the link (http://os.mbed.com/users/rlanghbv/code/KeypadLib/)
• In Keil studio, right clicking the project folder and select “Add Mbed Library…” option and paste the
copied link in the URL field then click next
• In the net pop window select “default” under “Release, branch, or tag” field and click finish
• Now Check whether “keypad.cpp” and “keypad.h” files included in your project folder or not
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 84
Program
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 85
Output
Connection diagram
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 86
Example-2 - Password based door locking system
Write a mbed C++ program to design a password based door locking system in
which the system accepts 4-digit password (last 4-digit of your reg. no) via keypad.
Use the LCD display to message “Enter Password” on the first line and display * symbol
on the second line of the LCD to represent every digit of the password entered. Check
whether entered password matches with actual password, if matched activate the
servo to open the door also display message “Correct Password” on LCD first line and
“Door opening” message on the LCD second line. If password not matched, activate the
buzzer also display message “Incorrect Password” on LCD first line and “Door can’t
open” message on the LCD second line. Assume LCD operates in 4-bit with EN and RS
active state. Design and verify this logic on Nucleo 152RE board using online Keil Studio
platform.
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 87
Program
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 88
Output
Connection diagram
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 89
Exercise-1: Home security system
Write a mbed C++program to design home security system that consists of three main
modules (1) Intruder detection (2) Activate fence light during night time (2) password based
door lock system.
1) The intruder detection system consists of PIR sensor interfaced with processing unit to detect
and alert under human presence condition.
2) Automatically activate the fence lights during night time using LDR.
3) Password based door lock system uses numeric keypad to accept the password (last 4-digit of
your reg. no) from user and LCD to display the message whether permission is granted or not.
Upon receiving correct password signal, enable motor to open the door.
In case of password mismatch or intruder detection condition activate the buzzer. Assume LCD
operates in 4-bit with EN and RS active state. Design and verify this logic on Nucleo 152RE
board using online Keil Studio platform.
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 90
91
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 91
All modern microcontrollers are embedded with timer-counter modules and generally they
are used for generating time bases, counting pulses (input capture mode) generating pulse
width modulation (PWM) signals, triggering external devices (output capture mode) etc.,
The ultra-low-power STM32L152RE devices include seven general-purpose timers, two basic
timers.
General-purpose timers (TIM2, TIM3, TIM4, TIM5, TIM9, TIM10 and TIM11) have all the
features of a typical timer-counter module such as PWM generation, input capture, time-
base generation and output compare
Basic timers (TIM6 and TIM7) are mainly used for DAC trigger generation. These timers
don’t have I/O channels for input capture/PWM generation and so they are strictly used
for time-base generation purposes.
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 92
Timer feature comparison
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 93
Watch-Dog Timer (WDT) used to reset the system when a malfunction occurs.
In normal operation the WDT counts up(or down) while your program periodically resets it (this
is called "kicking the dog“)
If your program crashed and did not kick WDT in time, it will overflow and generate a
hardware reset signal to restarts the system and recovers it from the crash.
STM32L152RE has two watchdog timers: Independent Watchdog (IWDG) and System
Window Watchdog (WWDG).
Window watchdog (WWDG)
Suited for applications which require the watchdog to react within an accurate time window.
The window watchdog is based on a 7-bit down counter that can be set as free-running.
It detects not only that a counter is overflowing, but also that its timing is earlier than expected.
since WWDG runs on the microcontroller’s clock, so it can be stopped.
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 94
Independent watchdog (IWDG) is a counter that runs and resets itself when it overflows.
IWDG used to detect and resolve malfunctions resulting from software failures.
It triggers a restart sequence when it is not refreshed within the expected time window.
IWDG is based on a 12-bit down counter, can be used either as a watchdog to reset the
device when a problem occurs or as a free-running timer for application timeout management.
The reason it is called an independent type is because the independent 37 kHz internal RC
clock that runs the timer is separate from the main clock of the microcontroller.
Even if the microcontroller’s clock stops due to some fault, it can still be reset if the IWDG is
running.
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 95
The mbed timer is based on the 32-bit counters, and can time up to a maximum of (231-1)
µs, i.e., something over 30 min.
Based on the theory above, one might expect the timer to count up to (232-1). However, 1
bit is reserved in the API object as a sign bit, so only 31 bits are available for counting.
API Required – TIMER
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 96
Example-1 : Calculate time taken to print message
Measures the time taken to write a message to the screen, and displays that message.
Compile and run the program, with Tera Term.
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 97
Example-2 : Calculate time taken to print message
The program creates two timers, named timer_fast and timer_slow. The main program
starts these running, and tests when each exceeds a certain number. When the time
value is exceeded, a function is called, which flips the associated led.
(PC_3);
(PC_4);
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 98
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN 99
Introduction to ultrasonic sensor
An ultrasonic sensor is an electronic device that measures the distance of a target object by
emitting ultrasonic sound waves, and converts the reflected sound into an electrical signal.
Ultrasonic sensors have two main components:
Transmitter (which emits the sound using piezoelectric crystals)
Receiver (which encounters the sound after it has travelled to and from the target).
In order to calculate the distance between the sensor and the object, the sensor measures
the time it takes between the emission of the sound by the transmitter to its contact with the
receiver.
The formula for this calculation is D = ½ T x C (where D is the distance, T is the time, and C
is the speed of sound ~ 343 meters/second).
10
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN
Introduction to ultrasonic sensor
Ultrasonic sensors are used primarily as proximity sensors.
They can be found in automobile self-parking technology, anti-collision safety systems,
robotic obstacle detection systems also used as level sensors to detect, monitor, and
regulate liquid levels in closed containers.
The HC-SR04 ultrasonic sensor offers excellent non-contact range detection with high
accuracy and stable readings from 2 cm to 400 cm.
It comes complete with ultrasonic transmitter and receiver module.
The HC-SR04 Ultrasonic Module has 4 pins, Ground (Gnd), VCC (5V) , Trig and Echo. The
trig and echo pins to any Digital I/O pin on the Nucleo Board.
10
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN
Introduction to ultrasonic sensor
Steps involved in measuring distance using HC-SR04 Ultrasonic module are,
Transmit trigger pulse of at least 10 us to the HC-SR04 Trig Pin.
Then the HC-SR04 automatically sends Eight 40 kHz sound wave and generate the
rising edge at Echo pin.
When the rising edge capture occurs at Echo pin, start the Timer and wait for falling
edge on Echo pin.
As soon as the falling edge is captured at the Echo pin, read the count of the Timer. This
time count is the time required by the sensor to detect an object and return back from
an object (to and from).
10
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN
Introduction to ultrasonic sensor
10
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN
Distance = (Speed x Time)/ 2
Distance = (0.034 cm/µs x 500 µs) / 2
Distance = 8.5 cm
When no obstacles then timeout after 38ms When obstacle detected pulse width of 50 µS to 25 mS received
10
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN
Example-3 - Read the distance value from HC-SR04 and print it on serial monitor
Write a program to read distance value from HC-SR04 ultrasonic sensor module in cm
and print it on the serial monitor. Implement and verify this logic on the STM32 Nucleo-
64 board using Keil Studio Cloud IDE.
Program
10
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN
Example-4 - Reverse parking sensor module
Write a program to design a reverse parking sensor module. This module consist of
HC-SR04 ultrasonic sensor, LCD and buzzer interfaced with Nucleo. The ultrasonic
sensor continuously measure the distance (in cm) between the car and obstacle, then
display it on the first row of the LCD. Whenever the measured distance is lesser than
30cm generate warning signal to driver using buzzer also display a message
“Obstacle !!!” on the second row of the LCD display. Implement and verify this logic on
the STM32 Nucleo-64 board using Keil Studio Cloud IDE.
10
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN
Program
10
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN
Exercise-1 - Smart Parking system
Write a program to design smart parking system using HC-SR04 ultrasonic sensor, servo
motor, buzzer, LCD and STM32 Nucleo-64 board.
The ultrasonic sensor module place near the gate entrance continuously check for the
incoming vehicles. The LCD display “Smart Parking” on the first row and “Avail. slot: XY” in
second row of the display.
When a vehicle comes closer to the ultrasonic sensor detection area and parking slot is
available then the system open a gate barrier to 90° (close after 10 seconds) to allow the
vehicle enter into the parking slot and decrement parking slot by 1.
If no parking slot available then display a message “No Parking slot” on LCD (2nd line) and
switch on the buzzer (for 5 Seconds). Have a similar system on the exit and increment the
free slot by 1 for every vehicle leaves the parking slot.
Simulate and verify this logic on Nucleo using Tinkercad circuits simulator.
Note: XY is number of available slot and initially assume total available parking slot is 5.
10
MODULE-5 BECE403E - EMBEDDED SYSTEM DESIGN