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

Module-1.2 - Embedded Systems Based on Microcontrollers

This document outlines a module on embedded systems based on microcontrollers, focusing on key components such as CPU, memory, and GPIO, as well as programming using Arduino Uno and the Wiring framework. It discusses the architecture of microcontrollers, including the Harvard architecture, and provides insights into programming practices and memory management. The module emphasizes practical application through lab work and the use of specific programming environments like the Arduino IDE.

Uploaded by

arvin.lajani3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Module-1.2 - Embedded Systems Based on Microcontrollers

This document outlines a module on embedded systems based on microcontrollers, focusing on key components such as CPU, memory, and GPIO, as well as programming using Arduino Uno and the Wiring framework. It discusses the architecture of microcontrollers, including the Harvard architecture, and provides insights into programming practices and memory management. The module emphasizes practical application through lab work and the use of specific programming environments like the Arduino IDE.

Uploaded by

arvin.lajani3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 125

v1.

1
20240924

Embedded Systems and IoT


Ingegneria e Scienze Informatiche - UNIBO
a.y. 2024/2025
Lecturer: Prof. Alessandro Ricci

[module 1.2]
EMBEDDED SYSTEMS BASED
ON MICROCONTROLLERS
ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 1
SUMMARY
• In this module we discuss the main component of a
microcontroller and basic microcontroller programming
– CPU and Memory
– GPIO
– Interruptions
– Timer
– Serial communication
• Arduino Uno and Wiring framework are used as
reference platform and programming framework
• The concepts introduced here will be see in practice in
lab

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 2


MICROCONTROLLER ELEMENTS

(immagine tratta da:


http://www.mikroe.com/chapters/view/74/pic-basic-book-chapter-1-world-of-microcontrollers/)
ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 3
MICROCONTROLLER ELEMENTS

• CPU
• Memory unit
• Ports for general purpose
Input/Output (GPIO)
• Analog/digital converters
• Timers
• Bus for serial communication
• Clock
• Power circuit

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 4


A REFERENCE EXAMPLE:
ARDUINO UNO ARCHITECTURE
• Main components
– MCU ATMega328P
• 8 bit, 16 MHz
• Flash memory: 32 KB
• SRAM memory: 2 KB, EEPROM: 1 KB
– 14 pins for digital input/output
• 6 can be used PWM outputs
– 6 analog inputs
– USB connector • Other specs:
– power jack - Operating voltage: 5V
– ICSP header - Input voltage (recom.): 7-12 V
– reset button - DC current per I/O pin: 40 mA
- DC current per 3.3V: 50mA

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 5


A REFERENCE EXAMPLE:
ARDUINO UNO ARCHITECTURE

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 6


MCU ATMega328P
• AVR CPU 8 bits, 16 MHz
– 32 registers
• memory - 16 bits
– Flash memory: 32 KB,
• 0.5 used by the bootloader
– SRAM memory: 2 KB
– EEPROM: 1 KB

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 7


MCU PROGRAMMING
• MCU programming is done by using an external host system (e.g. a
PC), where programs are edited, compiled, creating the executable
(or binary)
• The executable is then uploaded to the MCU by means of specific
HW, or directly by means of the serial communication with the host
PC
• The MCU software stack does not include any operating system
– the executable is directly copied into MCU memory and executed
by the CPU

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 8


THE ARDUINO CASE
• Arduino programs are typically developed on a host PC and
uploaded by means of USB cable
– besides, an ICSP (In-Circuit Serial Programmer) interface is
available for uploading the executable using a specific external
programmer device
• The upload via USB is done by means of a bootloader
– a small program(~0.5KiB) pre-stored (via ICSP)
• Programming environment/IDE: Wiring e Arduino IDE
– Wiring is an open-source C/C++ framework, available for different
kind of microcontrollers and SoC as well
• http://wiring.org.co/
– Arduino IDE is a simple but effective IDE for editing sources,
compiling, uploading binaries (working not only for Arduino..)
– based on GNU tools and other open source projects
• avr-gcc and open-source libraries (e.g. AVR Libc)

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 9


MICROCONTROLLER ELEMENTS

• CPU
• Memory unit
• Ports for general purpose
Input/Output (GPIO)
• Analog/digital converters
• Timers
• Bus for serial communication
• Clock
• Power circuit

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 10


CPU ARCHITECTURE: RECALL
• The CPU behaviour follows the Von Neumann machine model
– fetch-decode-execute execution cycle

• The instruction-execution cycle of a


computer based on Von Neumann
machine consists in:
– fetching from the memory the next
instruction to be executed, putting it in
a speci c register (instruction
register)
– decoding of the instruction, which
may lead to fetch other operands from
the memory
– instruction execution, which may
involve updating registers and writing
register content to the memory

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 11


fi
HARVARD ARCHITECTURE
• It’s a variant of the Von Neumann architecture in which instructions
and data are stored in physically different/separated memories, using
distinct buses
– the name comes from Harvard Mark I relay-based computer
• instructions stored in punch cards and data in electro-
mechanical devices
– architecture typically used in microcontrollers and DSP, with
extensions and variants
• e.g.: Atmel AVR
• Relevant aspects:
– the two memories have typically very different properties, for
instance:
• code in FLASH memory
– fast read access, slow write access
• data in SRAM
– fast read & write access, bigger power consumption &
cost
ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 12
HARVARD ARCHITECTURE

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 13


EXAMPLE: MCU ATMega328P
• MCU based on Harvard architecture
– code instruction
• stored in FLASH (non volatile) - 32 KiB
• 0.5 KB used by the bootloader
– data
• variables / stack stored in SRAM (volatile) - 2 KiB
• long-term / persistent data stored in EEPROM (non volatile) - 1 KiB
• Remarks:
– the amount of memory for data/variables is very small
=> disciplined use of data structure (e.g. minimising the use of strings)
– the stack is stored in RAM
• small memory => constraint on the level of call nesting and recursion

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 14


A COMPARISON AMONG MEMORIES
• Flash memory
– non-volatile memory
– fast read, slow write
– max ~100000 write cycle
– low power consumption and cost
• SRAM memory
– volatile
– fast read, fast write
• on ATMega328P: ~2 clock cycles
– bigger power consumption that FLASH
• EEPROM memory
– non volatile memory
– slow access
– on Arduino: can be read or written using the library:
http://arduino.cc/en/Reference/EEPROM

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 15


CPU ARCHITECTURE
• The CPU executes program instructions encode in machine
language
• Characterised by its own Instruction Set Architecture (ISA)
– set of possible instructions recognised by the CPU
– set of registers
• general or programmable registers (GPR)
– e.g. accumulator
• special purpose registers (SFR)
– Program counter (PC)
» storing the address of the next instruction to be
executed
– Program Status Word (PS)
» information about processor state
• XX bit (XX = 8, 16, 32, 64) CPU
– number of bits used in registers, to specify memory addresses
and values
ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 16
EXAMPLE: AVR8 ARCHITECTURE
• AVR8 is the microprocessor inside the ATMega328P microcontroller
– RISC architecture - code: 8 bits, data: 16 bits - 16 MHz
• CPU registers
– 32 general-purpose 8 bits registers (R0–R31)
• all arithmetic and boolean operations involve these registers
• only load and store operations access the RAM memory
– small set of special-purpose registers:
• PC: 16- or 22-bit program counter
• SP: 8- or 16-bit stack pointer
• SREG: 8-bit status register - tra i bit:
– C Carry flag (used in the sub op=
– Z Zero flag - set when an arithmetic result is zero
– I Interrupt flag - set when interrupts are enabled

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 17


MEMORY ADDRESSING
• Both general-purpose CPU registers and I/O registers (described in
the following) are mapped into low memory (and accessible using
memory addresses in that range)

ATmega328P
- F_END = 32 KiB
- RAM_END = 2 KiB
- E_END = 1 KiB

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 18


A LOOK AT AVR ASSEMBLY
LANGUAGE
• AVR Instruction set - categories:
– arithmetic
– bit manipulation
– memory/registers transfer
– jump
– test/branch
– call
• Look at
– https://en.wikipedia.org/wiki/Atmel_AVR_instruction_set
– full manual:
• http://www.atmel.com/images/Atmel-0856-AVR-Instruction-
Set-Manual.pdf

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 19


ABOUT PERFORMANCE
• Microprocessor clock frequency: 16 MHz
– period: 0.0625 us (microsec) = 62.5 ns (nanosec)
• The most part of the instructions are executed using 1 o 2 clock
cycles, i.e. ~60ns, ~125ns
– precise and detailed data are available on CPU datasheet
• This information allows to make accurate predictions about the
execution time of programs or parts of them, in particular in the worst
case
– important aspect for real-time systems

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 20


BASIC CONTROL ARCHITECTURE:
SUPER LOOP
• The super-loop is the simplest control architecture (a framework)
adopted for microcontroller programming
– very common and widespread since it does not require any
specific HW support (such as interrupts)
• Features
– initialisation
– infinite loop, repeatedly executing some task
/* Main.c */ /* X.h - header */

#include “X.h” void X_Init();


void X(void);
void main(void){
X_Init(); // Prepare for task X
while (1) // for ever ‘super loop’ /* X.c - implementation */
{
X(); Perform the task void X_Init() {…}
} void X(void) {…}
}

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 21


SUPER-LOOP FEATURES
• Pro
– simplicity
• the framework does not require any OS to work
– portability
– reliability and safety
– efficiency
• Cons
– timing not accurare
– fragility and low flexibility
– the basic version: ‘full-power’ => high power consumption

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 22


SUPER-LOOP IN WIRING
• Framework wiring (http://wiring.org.co/)
– open-source framework for programming microcontrollers
– reference language: C/C++
• subset of standard ANSI C++
– super-loop control architecture
• setup() procedure e loop() procedure
– must be implemented by the programmer
• there is a hidden main calling these procedures
– Wiring provides also a set of basic API
• classes, procedures e functions in C/C++
• Source compilation and executable creation by means of a C/C++
compile + linker
– avr-gcc (GNU)
• Among the other tools included in the Arduino distribution: avr-objdump
– to disassemble an executable

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 23


FROM WIRING TO THE EXECUTABLE
• Compiling an empty program in Wiring
– from C source code to AVR8 machine language
00000090 <setup>:
90: 08 95 ret

00000092 <loop>:
92: 08 95 ret
void setup(){ 00000094 <initVariant>:
} 94: 08 95 ret

00000096 <main>:
96: 0e 94 a4 00 call 0x148 ; 0x148 <init>
void loop(){ 9a: 0e 94 4a 00 call 0x94 ; 0x94 <initVariant>
9e: 0e 94 48 00 call 0x90 ; 0x90 <setup>
} a2: c0 e0 ldi r28, 0x00 ; 0
a4: d0 e0 ldi r29, 0x00 ; 0
empty program in a6:
aa:
0e 94 49
20 97
00 call
sbiw
0x92
r28, 0x00
;
;
0x92 <loop>
0
Wiring ac: e1 f3 breq .-8 ; 0xa6 <main+0x10>
ae: 0e 94 00 00 call 0 ; 0x0 <__vectors>
b2: f9 cf rjmp .-14 ; 0xa6 <main+0x10>

Executable disassembly
(created by the tool avr-objdump, -d option)
ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 24
CONTROL LOOP DISASSEMBLY
00000090 <setup>:
90: 08 95 ret
00000092 <loop>:
92: 08 95 ret

00000096 <main>:
int main(void)
{
init();
96: 0e 94 a4 00 call 0x148 ; 0x148 <init>
initVariant();
9a: 0e 94 4a 00 call 0x94 ; 0x94 <initVariant>
setup();
9e: 0e 94 48 00 call 0x90 ; 0x90 <setup>
for (;;) {
loop();
a2: c0 e0 ldi r28, 0x00 ; 0
a4: d0 e0 ldi r29, 0x00 ; 0
a6: 0e 94 49 00 call 0x92 ; 0x92 <loop>
if (serialEventRun) serialEventRun();
aa: 20 97 sbiw r28, 0x00 ; 0
ac: e1 f3 breq .-8 ; 0xa6 <main+0x10>
ae: 0e 94 00 00 call 0 ; 0x0 <__vectors>
b2: f9 cf rjmp .-14 ; 0xa6 <main+0x10>
ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 25
THE EXAMPLE
int c; …
000000a6 <setup>:
a6: 84 e6 ldi r24, 0x64 ; 100
void setup(){ a8: 90 e0 ldi r25, 0x00 ; 0
c = 100; aa: 90 93 01 01 sts 0x0101, r25
} ae: 80 93 00 01 sts 0x0100, r24
b2: 08 95 ret

void loop(){
000000b4 <loop>:
c = c + 1;
b4: 80 91 00 01 lds r24, 0x0100
} b8: 90 91 01 01 lds r25, 0x0101
bc: 01 96 adiw r24, 0x01 ; 1
be: 90 93 01 01 sts 0x0101, r25
c2: 80 93 00 01 sts 0x0100, r24
c6: 08 95 ret

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 26


MICROCONTROLLER ELEMENTS

• CPU
• Memory unit
• Ports for general purpose
Input/Output (GPIO)
• Analog/digital converters
• Timers
• Bus for serial communication
• Clock
• Power circuit

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 27


GENERAL-PURPOSE I/O (GPIO)
• Every microcontroller typically features a set of pin che can be directly used
to drive input/output
• Pins typically are general-purpose: can be programmed to work as input or
output depending on the need
– input
• the value can be read by program
– output
• the value is controlled by the program
• Pins can be either analog or digital
– a digital pin can assume two values only, HIGH or LOW (1 o 0)
– an analog pin can assume any value in a range (0…5 volts)

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 28


EXAMPLE: ARDUINO GPIO
• Arduino pins
– 14 digital pins
• configurable either as input or output
– 6 analog pins
• input only
• Some pins are multiplexed, i.e. serving multiple functions
– e.g.: pin 0 e pin 1 are also used as serial port (for transmitting and
receiving bits)

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 29


ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 30
OPERATING PARAMETERS
• Reference operating parameters for pins:
– voltage (in Volt)
• to be applied on the pin (input case) o produced by the pin
(output case)
• example: 5 V (Arduino), 3.3 V (Raspberry Pi and ESP)
– current (in Ampère)
• that can receive (input) or that can be produced (output)
• example: Arduino: 40 mA, ESP8266 12mA
• Either presence or absence of pull-up circuits/resistors
– internally, the pins can be equipped with pull-up circuits, that allow
for fix the voltage at the max value (referred as +VCC) even when
the pin — configured as input — is not connected to any circuit, i.e.
it is in open-circuit state, to avoid malfunctioning due to signal
floating
– resistors of tens of KOhm are used for this purpose
– this point will be clarified in lab slides

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 31


INPUT/OUTPUT PORTS
• The MCU interacts with the pins (and then with external devices) by
means of ports
– as for the pins, a port can be configured to be either input or
output (to receive signals or to send signals)
• A port is managed by one or multiple special purpose registers
(SRF) connected to the pin that carry the digital or analog signal,
sent or received by the external device
– keeping the state (current value) + current configuration (input/
output)

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 32


EXAMPLE: ATMega328P
• L’ATMega328P has 23 I/O lines grouped by 3 8-bit ports named B, C and D
– port D manages pins 0..7, port B pins 8..13, and port C the analog pins
• Each pin is identified by a label such as PD0, PC1 o PB2.
– for instance, PD0 identifies pin 0 of the port D

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 33


ATMega328P - PORTS AND REGISTERS
• Each port is managed by 3 registers: DDRx, PORTx, PINDx, where x is the
port name. For instance, for the port D;
– DDRD
• this register is both Read/Write and stores the configured direction
for the pins (bit set to 0 => pin configured as INPUT; bit set to 1 =>
pin configured as OUTPUT)
– PORTD
• this register is both Read/Write and stores the pin state, which
changes depending on the pin configuration:
– for INPUT pins, then a bit set to 1 activates the PULL-UP
resistor, while a bit set to 0 deactivates it;
– for OUTPUT pins, then a bit set to 1 represents a state set to
HIGH on the corresponding pin, while a bit set to 0 represents a
state set to LOW
– PIND
• this register is read-only, and stores, for INPUT pins, the signal value
read connected to the pin: 1 if the signal value is HIGH; 0 if the
signal value is LOW.

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 34


ATMega328P - PORTS AND REGISTERS
• Therefore, to configure an OUTPUT pin to the HIGH value, one
must:
– write on the DDRx register to set the direction (OUTPUT)
– write on the PORTx register to set the state (HIGH)
• As already mentioned, in the ATmega328 MCU, and in many other
microcontrollers and general-purpose microprocessors as well, I/O
registers are mapped into the memory
– so that they can be uniformly accessed/manipulated bu writing/
reading bytes/words at the specific memory addresses
– in the ATMega328P, they are located starting from the address
0x20, just after the general purpose registers

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 35


SETTING, WRITING, READING A PIN
IN WIRING
• Wiring API to work with pins:
– pinMode()
• to set the pin direction (INPUT/OUTPUT)
– digitalWrite()
• to set the value of an OUTPUT pin
– digitalRead()
• to read the value of an INPUT pin
• This API internally works with port registers as discussed before

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 36


OUTPUT EXAMPLE: BLINKING LED

#define LED_PIN 13

void setup() {
pinMode(LED_PIN, OUTPUT);
}

void loop() {
digitalWrite(LED_PIN, HIGH);
delay(1000);
digitalWrite(LED_PIN, LOW);
delay(1000);
}

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 37


CODE DETAIL: delay
• delay() is a procedure available in Wiring that executes a busy
waiting for the specified amount of time in milliseconds:

void delay(unsigned long ms)


{
unsigned long start = millis(); from wiring.c
source code
while (millis() - start <= ms)
;
(open-source)
}

• This procedures calls another procedure: millis()


– it returns the current number of milliseconds elapsed since the
power on of the device
– it accesses variables managed by a timer (discussed later in this
module)
• IMPORTANT REMARK
– delay() and busy waiting blocks the loop, impacting on reactivity
of the system
ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 38
INPUT/OUTPUT EXAMPLE:
BUTTON-LED
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin

// variables will change:


int buttonState = 0; // variable for reading the pushbutton status

void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}

void loop(){
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);

// check if the pushbutton is pressed.


// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
} ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 39
INPUT/OUTPUT EXAMPLE:
BUTTON-LED
(the circuit part will be presented and discussed
in detail in lab sessions)

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 40


PIN (MULTIPLEXED) FUNCTIONS
• Besides being general purpose, some pins have a further function
that can be configured/activated:
– pins 0 and 1 => TTL serial interface
– pins 2 and 3 => interrupts
– pins 3,5,6,9,10 e 11 => PWM
– pins 10, 11, 12, 13 => SPI bus
– pins 13 => Builtin led
• Analog pin
– pin A4 and A5 => I2C bus

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 41


ANALOG SIGNALS
• A digital signal on a (digital) pin can assume only two logical values:
HIGH (corresponding to VCC) o LOW (corresponding to GND), that
is 1 or 0
• Instead, an analog signal on a (analog) pin can assume any value in
the voltage range GND-VCC (e.g. 0-5 V)
• So, in order to process with a digital computer an analog signal, it
must be first converted
• The conversion is made by an electronic component called ADC
(Analog-to-Digital Converter), that maps a voltage continuous
value in GND..VCC into a discrete value in a certain range (e.g.
0..1023), depending on the number of bits (resolution) used by the
ADC
– e.g. by using 10 bits, the continuous value is mapped into a
discrete value in the range 0…1023
– the resolution defines the precision of the ADC

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 42


READING ANALOG PINS IN WIRING
• Arduino UNO can manage up to 6 input analog signals by means of
6 analog pins, each using a 10-bit ADC
– pin A0-A5
• The Wiring API to read an the value of an analog pin is:

int analogRead(int PIN)

– internally, this procedure (function) accesses the registers of the


C port
• The library provides also a further utility function, map, to map a
value from a range (e.g. 0…1023) into another application-level
range (e.g. 0..255)

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 43


EXAMPLE: USING A POTENTIOMETER
const int analogInPin = A0; // Analog input pin that the potentiometer is attached to
const int analogOutPin = 9; // Analog output pin that the LED is attached to

int sensorValue = 0; // value read from the pot


int outputValue = 0; // value output to the PWM (analog out)

void setup() {
// initialize serial communications at 9600 bps:
Serial.begin(9600);
}

void loop() {
// read the analog in value:
sensorValue = analogRead(analogInPin);
// map it to the range of the analog out:
outputValue = map(sensorValue, 0, 1023, 0, 255);
// change the analog out value:
analogWrite(analogOutPin, outputValue);

// print the results to the serial monitor:


Serial.print("sensor = " ); Serial.print(sensorValue);
Serial.print("\t output = “); Serial.println(outputValue);

// wait 2 milliseconds before the next loop


// for the analog-to-digital converter to settle
// after the last reading:
delay(2);
}
ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 44
READING A POTENTIOMETER:
THE SKETCH

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers


NOTE ON THE CODE:
LOGGING THROUGH THE SERIAL
• In the code, the println method of the Serial class is used to send
text messages though the serial port to the host PC, connected to
Arduino
• In Arduino IDE, such messages can be visualised by means of the
Serial Monitor
– details about the serial port and its programming will be given
later on in this module

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 46


PULSEWIDTH MODULATION (PWM)
• PWM is a method to emulate an analog output signal on digital
pins, through the generation of a periodic square wave
– i.e. a signal periodically going HIGH and LOW
• The output voltage emulated is defined by the duty cycle of the
signal
– duty cycle: percentage of time in which the signal is HIGH over
the time in which the signal is LOW
• The average voltage value is equal to the duty-cycle * VCC (a value
in 0…VCC) of
– e.g. 50% duty cycle => 0.5*VCC - e.g. 2.5V for VCC = 5V
• Such an emulation approach doesn’t work with every output analog
device / actuator
– it works to drive LEDS (controlling the intensity), direct current
motors (controlling the speed)

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 47


PWM ON ARDUINO
• Pins 3,5,6,9,10 e 11 can be used for PWM output (8 bit)
• API: analogWrite()

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 48


AN EXAMPLE: FADING OF A LED
int led = 9; // the pin that the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by

// the setup routine runs once when you press reset:


void setup() {
// declare pin 9 to be an output:
pinMode(led, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
// set the brightness of pin 9:
analogWrite(led, brightness);
// change the brightness for next time through the loop:
brightness = brightness + fadeAmount;
// reverse the direction of the fading at the ends of the fade:
if (brightness == 0 || brightness == 255) {
fadeAmount = -fadeAmount ;
}
// wait for 30 milliseconds to see the dimming effect
delay(30);
}

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 49


FADE: SCHEMA

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 50


I/O AND INTERRUPTS
• Interrupts are the fundamental mechanism used by the
microcontroller to react to events triggered by external devices
– including sensors perceiving the physical world, timers
• Generally speaking, a CPU provides one or multiple pins — called
IRQ (Interrupt Request) — to receive interrupt signals
– when an interrupt request is receive, the CPU suspends the
execution of current instructions (e.g. the super-loop), it saves on
a stack the address of the next instruction to be executed, and
jumps (tranfers the control) to the routine (procedure) configured
to react to the event - called interrupt handler o interrupt
service routine (ISR)
– the ISR address is stored into a table called interrupt table or
interrupt vectors
• In microcontrollers, IRQ are typically connected to one or multiple
GPIO

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 51


I/O AND INTERRUPTS: ATMega328P
• The ATMega328P has 2 pins - pin 2 and pin 3 - that can be
configured to generate (to the CPU) external interrupts (*)
• In particular, the pin can be configured to generate an interrupt on
different conditions
– when there is a RISING or FALLING edge
– when there is a CHANGE
– when the signal is LOW

[*] actually it is possible to enable and manage interrupts for all pins, but
limiting to a specific kind of interrupt: PIN CHANGE (vs. EXTERNAL)

https://github.com/GreyGnome/EnableInterrupt

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 52


ATMega328P: INTERRUPT VECTORS

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 53


HANDLING INTERRUPTS IN WIRING
• In Wiring it is possible to directly specify and attach an ISR by means
of the routine:

attachInterrupt(intNum, ISR, mode);

• Parameters:
– intNum: interrupt number (int)
– ISR: pointer to the interrupt handler
(tipo: void (*func)(void))
– mode: when the interrupt should be generated:
CHANGE/FALLING/RISING: at every change HIGH -> LOW,
LOW -> HIGH
LOW/HIGH: when the state is LOW or HIGH

• The utility function digitalPinToInterrupt(numPin) makes it possible


to get the number of the interrupt (see interrupt vectors) given the
specified pin

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 54


EXAMPLE
volatile int count = 0;

void setup()
{
// 0 => detecting pin 2 changes
attachInterrupt(0, inc, CHANGE);
Serial.begin(9600);
}

void loop()
{
Serial.println(count);
}

void inc()
{
count++;
}
BEWARE - concurrency problems here
• race conditions
ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 55
DISABLING INTERRUPTS
• Possibility to disable/enable interrupt from the user programs,
typically to avoid concurrency problems
– by setting a bit in the status register of the CPU
• Instructions
– STI = Set Interrupt (enable)
– CLI = Clear Interrupt (disable)
• In Wiring/Arduino:
– noInterrupts()
– interrupts()

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 56


THE EXAMPLE REVISED
#define BUTTON_PIN 2
volatile int count = 0;
int prev = 0;

void setup()
{
Serial.begin(9600);
attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), inc, RISING);
}

void loop() {
noInterrupts();
int current = count;
interrupts();
if (current != prev){
Serial.println(current);
prev = current;
}
}

void inc() { count++; }

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 57


INTERRUPT HANDLER DESIGN
• When interrupts are disabled, the system is no more reactive to
external events
• For this reason, the design of an interrupt handler should be ruled by
a careful discipline
– interrupt handlers should be short time
– they cannot block or execute infinite loops
– we want low interrupt latency
• interrupt latency = amount of time used to react to an interrupt
=> minimising the time period in which interrupts are disabled
=> using buffers and producers/consumers strategy to do long-
term / heavy computational tasks in reaction to interrupts
(when needed)
• the interrupt handler (producer) produces a task in a
buffer which is fetched and executed later on by the main
loop / super loop

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 58


INTERRUPTS FAQ
• Can a processor being interrupted when executing a single instruction?
– no, typically machine language instructions are executed atomically (modulo complex
instructions that account for multiple memory transfers)
• If two interrupts occur in the same time, which one is served?
– every CPU assigns some priority to interrupts, so that it executes always the interrupt
with higher priority
• About interrupt nesting: can an interrupt request interrupt the execution of an interrupt
handler?
– in most processors YES, so we need to disable interrupt in the interrupt handler (and
re-enable them)
– in AtMega328P / AVR8 NO, it does not support interrupt nestinge
• What happen to interrupt requests when interrupt are disabled?
– typically a CPU keeps track of such requests and execute them as soon as the
interrupts are enabled again
– AVR8 does not track them
• What happens if we disable interrupts and we forgot to enable them again?
– system malfunctioning, crash
• What happens if we disable interrupts multiple times (before re-enabling)?
– nothing, they are idem-potent

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 59


INTERRUPTS ON ARDUINO: NOTES
• On AVR / Arduino, when the interrupt handler is executed, interrupts are
disabled
– it does not support interrupt nesting
• CONSEQUENCE/WARNING: library functions/procedures whose function
depends on interrupts cannot be used in interrupt handlers
– An example: delay()
• it is based on millis() which uses (timer) interrupts
• conversely delayMicroseconds() works, since it is not based on
timers
– it is based on the execution of instructions, knowing their
duration in clock cycles
– https://www.arduino.cc/en/Reference/DelayMicroseconds

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 60


MICROCONTROLLER ELEMENTS

• CPU
• Memory unit
• Ports for general purpose
Input/Output (GPIO)
• Analog/digital converters
• Timers
• Bus for serial communication
• Clock
• Power circuit

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 61


TIMER
• The timer plays a fundamental role to realise time-oriented
behaviour, in which time becomes an important aspect in task
specification
• It is used to:
– measure time intervals
– to create PWM signals
– to create timeouts and alarms
– to create multi-tasking based on preemptive scheduling
• It can be represented as a simple counter which is incremented at
the HW level at some frequency
• Programmable timers allow for:
– configure the frequency
– access and read the current value of the counter
– attach interrupts to implement time-triggered behaviours based
on time events

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 62


ATMega328 EXAMPLE
• The ATMega328 has 3 internal timers
– timer0
– timer1
– timer2
• Each timer has a counter which is incremented each clock cycle (of
the timer)
– timer0 and timer2 have 8-bit counters
– timer1 has a 16-bit counter

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 63


API USING TIMERS
• Timers are exploited to implement high-level functionalities provided by
Wiring. Examples:
– millis() procedure, using time 0

unsigned long millis()


{
unsigned long m; NOTE
uint8_t oldSREG = SREG;
- timer0_millis = variabile that
contains the value of the timer0
cli();
counter
m = timer0_millis;
- interrupts disabled to avoid race
SREG = oldSREG; conditions
return m;
}

– analogWrite() procedure, for PWM signals

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 64


TIMER AND INTERRUPTS ON
ATMega328 -
• Different working modalities for managing interrupts in timers
– one is CTC (Clear Timer on Compare Match)
• In CTC modality, timer interrupts lare generated when the counter
reaches a certain value
– this value must be stored in a register called compare match
register
• When the timer counter reaches this value, the counter is reset and
starts again counting
• By choosing the value of the CTC register, we specify interrupts
frequency
– by knowing that timer counter is updated at 16 MHz
• see example:
http://www.instructables.com/id/Arduino-Timer-Interrupts

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 65


TIMER AND INTERRUPTS ON
ATMega328: DETAILS
• Counters are updated at 16 MHz
– so each tick occurs every 1/16,000,000 of a second (~63ns),
• timer0 and timer2 are 8 bit => they take 256*63 = 16128 ns = 16.1 us to go
in overflow (e restart to 0)
• timer1 is 16 bit => it takes 65536*63 = 4128768 ns ~ 4129 us ~ 4.1 ms
• This frequency can be modulated by specifying a prescaler value, which
essentially functions as divider of the original frequency(16 MHz):

timer speed (Hz) = (Arduino clock speed (16MHz)) / prescaler

• So e.g. by specifying a prescaler = 1 => counter incremented at 16MHz,


prescaler = 8 => incremented at 2 MHz, .. prescaler = 1024 => 16 KHz.
– the value of the prescaler can be 1, 8, 64, 256, and 1024.

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 66


TIMER AND INTERRUPTS ON
ATMega328: DETAILS
• Given the prescaler, then the interrupt generation frequency is:

desired interrupt frequency (Hz) =


16,000,000Hz / (prescaler * (compare match register + 1))

• +1 since the value 0 in the CTC is the first significant value


• Then solving wrt the CTC:

compare match register =


( 16,000,000Hz/ (prescaler * desired interrupt freq)) - 1

we check if this value is less than 256 if we use timer 0 and 2, leads than
65536 if we use timer1
– if this does not hold, then we have to increase the prescaler

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 67


TIMER AND INTERRUPTS ON
ATMega328: DETAILS
• Example: suppose that we want 1 interrupt per second (1 Hz). Then:

compare match register = (16,000,000 / (prescaler * 1)) -1

• if we use a prescaler = 1024, then we get:

compare match register = (16,000,000 / (1024 * 1)) - 1 = 15,624

• Since the value is grater than 256 but less than 65536, then we can use
timer 1.

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 68


REGISTERS CONFIGURATION
• Each timer has 2 registers to store timer configuration: TCCRxA, TCCRxB
(where x = timer number 1..3)
– 8-bit registers
– the most important bits are the 3 least significant ones CSx2, CSx1,
CSx0, determining timer clock configuration

• CTC modality is enabled by activating specific bit in TCCRxB


• CTC register is labelled as OCRxA

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 69


ARDUINO EXAMPLE
void setup(){ /* setup the timer1 (16 bit) to
Serial.begin(9600); * a specific freq
setupTimer(1000); */
} void setupTimer(int freq){
// disabling interrupt
volatile boolean timerFlag = false; cli();
TCCR1A = 0; // set entire TCCR1A register to 0
ISR(TIMER1_COMPA_vect){ TCCR1B = 0; // same for TCCR1B
timerFlag = true; TCNT1 = 0; //initialize counter value to 0
} /*
* set compare match register
int count = 0; * OCR1A = (16*2^20) / (100*PRESCALER) - 1
* (must be < 65536)
void step() * by assuming a prescaler = 1024, then
{ * OCR1A = (16*2^10)/freq
count++; */
if (count % 100 == 0){ OCR1A = 16*1024/freq;
Serial.println(count); // turn on CTC mode
} TCCR1B |= (1 << WGM12);
} // Set CS11 for 1024 prescaler
TCCR1B |= (1 << CS12) | (1 << CS10);
void loop(){ // enable timer compare interrupt
/* wait for timer signal */ TIMSK1 |= (1 << OCIE1A);
while (!timerFlag){} // enabling interrupt
timerFlag = false; sei();
step(); }
} ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 70
REMARKS
• In the example, timer1 (16 bit) is configured to generate a tick (then
an interrupt) 100 times per second (100 Hz).
• In the main loop, at each tick a count is incremented and sent to
serial line every 100 increments
– so a message per second is printed
• ISR is a macro used to directly declare the interrupt handler
• volatile attribute in timerFlag

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 71


“OFFICIAL" TIMER LIBS
• Different timer libraries available for Arduino, that allow for easing the
management of the timer
• A main one is TimerOne
– https://code.google.com/p/arduino-timerone
– it provides classes that allow to configure the times and to attach
interrupt routine

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 72


AN EXAMPLE: TIME-DRIVEN
BLINKING
#include<TimerOne.h>

const int LED_PIN = 13;


boolean flagState = false;

void blinkHandler(){
if (!flagState){
digitalWrite(LED_PIN, HIGH);
} else {
digitalWrite(LED_PIN, LOW);
}
flagState = !flagState;
}

void setup()
{
pinMode(LED_PIN,OUTPUT);
Timer1.initialize(1000000); // set a timer of length 10^6 micro sec = 1 sec
Timer1.attachInterrupt(blinkHandler); // runs blinkHandler on each timer interrupt
}

void loop(){}

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 73


TIMER AND PWM
• In the lib implementation managing the GPIO in Wiring for Arduino,
timers are used to realise PWM output signals
• In particular:
– Timer0 is used for pin 5 and 6
– Timer1 is used for pins 9 and 10
– Timer2 is used for pins 11 e 3

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 74


THE WATCH DOG TIMER
• It is a timer that counts until some specified value, after than a reset
signal is produced to reboot the system
– in normal functioning, the watch dog periodically receives a signal
before reaching the threshold, resetting the counter
– if no signal is received on time, than it means that the
microprocessor encountered a problem (e.g. deadlock) and it is
reset
• Widespread in embedded systems

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 75


REMARK: MULTIPLEXING AND
INTERFERENCES
• Timers and interrupts are exploited to multiple functions provided by
Wiring
– e.g. for PWM
• There could be than interferences and malfunctioning if more than
one functionality based on the same timer is used
• To avoid problems => carefully check the API documentation

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 76


POWER MANAGEMENT
• A very important functionality supported by most microcontrollers is
power management, with the possibility to exploit low power
consumption modality (sleep mode)
• ATMega328P Example(*)
– 5 sleep modalities (increasing power reduction)
• Idle Mode
• ADC Noise Reduction Mode
• Power-save Mode
• Standby Mode
• Power-down Mode

(*) http://www.atmel.com/Images/Atmel-2486-8-bit-AVR-microcontroller-ATmega8_L_datasheet.pdf, pag 32

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 77


ATMEGA SLEEP MODE
• Idle Mode
– stopping the CPU but allowing SPI, USART, Analog Comparator, ADC, Two-wire Serial Interface,
Timer/Counters, Watchdog, and the interrupt system to continue operating. This sleep mode
basically halts clkCPU and clkFLASH, while allowing the other clocks to run.
• ADC Noise Reduction Mode
– stopping the CPU but allowing the ADC, the external interrupts, the Two-wire Serial Interface
address watch, Timer/Counter2 and the Watchdog to continue operating (if enabled). This sleep
mode basically halts clkI/O, clkCPU, and clkFLASH, while allowing the other clocks to run
• Power-save Mode
– This mode is identical to Power-down, with one exception: If Timer/Counter2 is clocked
asynchronously, Timer/Counter2 will run during sleep.
• Standby Mode
– this mode is identical to Power-down with the exception that the Oscillator is kept running. From
Standby mode, the device wakes up in 6 clock cycles
• Power-down Mode
– the External Oscillator is stopped, while the external interrupts, the Two-wire Serial Interface
address watch, and the Watchdog continue operating (if enabled). Only an External Reset, a
Watchdog Reset, a Brown-out Reset, a Two-wire Serial Interface address match interrupt, or an
external level interrupt on INT0 or INT1, can wake up the MCU. This sleep mode basically halts
all generated clocks, allowing operation of asynchronous modules only.
– When waking up from Power-down mode, there is a delay from the wake-up condition occurs
until the wake-up becomes effective. This allows the clock to restart and become stable after
having been stopped.
ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 78
the ATmega8,
Initial Value as0 the TOSC
0 and 0XTAL inputs
0 share
0 the same
0 physical
0 pins.
0

Figure
• Bit 710 on page
– SE: Sleep25Enable
presents the different clock systems in the ATmega8, and their distribu-

gister
ATMEGA PWR MANAGEMENT
tion. The figure is helpful in selecting an appropriate sleep mode.
The SE bit must be written to logic one to make the MCU enter the sleep mode when the SLEEP
instruction
The is executed.
MCU Control To avoid
Register the control
contains MCU entering the sleep
bits for power mode unless it is the programmer’s
management.
purpose, it is recommended to set the Sleep Enable (SE) bit just before the execution of the
Bit 7 6 5 4 3 2 1 0
SLEEP instruction.
SE SM2 SM1 SM0 ISC11 ISC10 ISC01 ISC00 MCUCR
• Bits 6..4 – SM2..0: Sleep Mode Select Bits 2, 1, and 0
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
These bits select
Initial Value 0 between
0 the five
0 available
0 sleep
0 modes0 as shown
0 in Table
0 13.
•Table
Bit 713.
– SE: Sleep
Sleep Enable
Mode Select
The SESM2bit must be written
SM1 to logicSM0
one to make theMode
Sleep MCU enter the sleep mode when the SLEEP
instruction is executed. To avoid the MCU entering the sleep mode unless it is the programmer’s
purpose,0 it is recommended
0 to set0 the Sleep
IdleEnable (SE) bit just before the execution of the
SLEEP0instruction. 0 1 ADC Noise Reduction
• Bits06..4 – SM2..0:1 Sleep Mode 0Select Bits 2, 1, and 0
Power-down
These 0bits select between
1 the five available
1 sleep modes as shown in Table 13.
Power-save
ATmega8(L)
1 Sleep Mode
Table 13. 0 Select 0 Reserved
Standby1
SM2
Mode SM1 0 When the 1 SM2..0Sleep
SM0
bits are 110 and an external crystal/resonator clock option is selected, the
Reserved
Mode
SLEEP instruction makes(1)the MCU enter Standby mode. This mode is identical to Power-down
01 01 0 Standby
with the 0exceptionIdle
that the Oscillator is kept running. From Standby mode, the device wakes up
Note: 0 1. Standby mode
0 isin 6
onlyclock
1 cycles.
available with external
ADC Noise crystals or resonators
Reduction
0 1 0 Power-down
Table 14. Active Clock Domains and Wake-up Sources in the Different Sleep Modes
0 1 1 Power-save
Active Clock Domains Oscillators Wake-up Sources
1 0 0 Reserved
TWI SPM/
Sleep 1 0 1 ReservedMain Clock Timer Osc. INT1 Address Timer EEPROM Other
Mode clkCPU clkFLASH clkIO clkADC clkASY Source(1) Enabled Enabled INT0 Match 2 Ready ADC I/O
1 1 0 Standby
Idle X X X X X(2) X X X X X X
Note: 1. Standby mode is only available with external crystals or resonators 33
ADC Noise
X X X X(2) X(3) X X X X
Reduction
Power
X(3) X
Down
Power
X(2) X(2) X(3) X X(2)
Save
Standby(1) X X(3) X
Notes: 1. External Crystal or resonator selected as clock source 33
2. If AS2 bit in ASSR is set
ESIOT ISI-LT
3. Only level interrupt- INT1
UNIBO
and INT0 Embedded systems based on microcontrollers 79
ARDUINO EXAMPLE

void sleepNow() // here we put the arduino to sleep


{
set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here

sleep_enable(); // enables the sleep bit in the mcucr register


// so sleep is possible. just a safety pin

/* Now it is time to enable an interrupt.


attachInterrupt(0,wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
// wakeUpNow when pin 2 gets LOW

sleep_mode(); // here the device is actually put to sleep!!


// THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP

sleep_disable(); // first thing after waking from sleep:


// disable sleep...
detachInterrupt(0); // disables interrupt 0 on pin 2 so the
// wakeUpNow code will not be executed
// during normal running time.

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 80


CONSUMPTION
(ATMega8 datasheet) ATmega8(L)

Figure 119. Active Supply Current vs. Frequency (1MHz - 20MHz)

30
5.5V
25 5.0V

4.5V
20
ICC (mA)

15

10
3.3V

5 3.0V
2.7V

0
0 2 4 6 8 10 12 14 16 18 20
Frequency (MHz)

Figure 120. Active Supply Current vs. VCC (Internal RC Oscillator, 8MHz)

18

16
-40°C
14
25°C
12 85°C
ICC (mA)

10

0
2.5 3 3.5 4 4.5 5 5.5
VCC (V)

Test examples:
https://learn.sparkfun.com/tutorials/reducing-arduino-power-consumption

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 81


MICROCONTROLLER ELEMENTS

• CPU
• Memory unit
• Ports for general purpose
Input/Output (GPIO)
• Analog/digital converters
• Timers
• Bus for serial communication
• Clock
• Power circuit

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 82


BUSES AND PROTOCOLS
• Protocols to exchange data through single pins can become complex
depending on the external communicating I/O device
• To this purpose, specific communication interfaces, buses and
protocols have been introduced
• Two main kinds: serial and parallel
– parallel interfaces allow for transferring multiple bits at the same
time, by means of multiple lines
• 8-bit, 16-bit, 32-bit bus
– serial interfaces send and receive streams of bits in a sequential
way, using a single line/channel

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 83


SERIAL INTERFACES/BUSES
• Two main categories
– asynchronous
• no clock line is used for sychronisation
• two lines: TX to transmit, RX to receive
• examples: USB, RS-232 e TTL
• oldest and simpler protocol
– synchronous
• a clock signal is used to synchronise the communication
among the parts
– this allows to achieve higher speed than asynchronous
serial
• examples: I2C and SPI synchronous serial buses

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 84


ASYNCHRONOUS SERIAL
• In serial asychronous interface, since there is not a specific clock
line, the synchronisation is achieved trough a protocol, to ensure an
error-free and robust bit transmission
• The protocol can be configured by specifying some parameters, that
must be adopted by both the communicating parts:
– baud rate
– data frame
– synchronous bits
– parity bit

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 85


BAUD RATE
• Transmission speed in bits per seconds
• A typical value used in 9600 bps
– other standard values are 1200, 2400, 4800, 19200, 38400,
57600, and 115200
• The higher is the baud rate, the higher is the speed
– however there is a limit (typically 115200), related to
microcontrollers capabilities
– using higher values could lead to transmission errors

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 86


DATA FRAME
• Each data block - typically one byte - is transmitted inside a (bit) packet
called frame. These frames are created adding to the data block also a
synchronization bit and a parity bit:

• The data chunk (block) represents the real data transmitted: each packet
can have a data chunk from 5 to 9 bit (typical value: 8)
• About little endian or big endian
– part of the protocol includes agreeing also on data endianness dei dati,
i.e. the order used to send the bit (from the most significative or the less
significative).
• default if not specified: less significative
• Synchronisation bits include a start bit and a stop bit, to mark the beginning
and end of the packet (there is always a single start bit, while stop bits can
be 2).
• Parity bits (optional) are used for simple low-level error checking.
ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 87
CONCRETE EXAMPLE
• Il 9600 8N1 - 9600 baud, 8 data bits, no parity, and 1 stop bit - is one of the
most used protocol
• Transmission example
– suppose to transmit ASCII characters 'O' and ‘K'. ASCII value of O is 79,
i.e. 01001111. The value of K in binary is 01001011. Bits are sent starting
from the least significative:

– since we are transferring at 9600 bps, the time used to keep the signal
high (or low) is 1/(9600 bps), i.e. 104 µs per bit.
– for each byte there are 10 bits sent: one start bit, 8 data bits, and one
stop bit => at 9600 bps we are sending 960 (9600/10) byte per sec.

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 88


SERIAL HARDWARE
• At the hardware level, an async serial bus is composed by two lines (wires):
– one to transmit bits
– one to receive bits
• Two pins are needed then - one to receive (RX) and one to transmit (TX)

• RX and TX nomes are referred to the device itself


– RX pin of one device must be connected to the TX pin of the other
device

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 89


HARDWARE IMPLEMENTATIONS OF
SERIAL
• RS-232
– first HW serial communication protocol
widely used as a communication
method for computers and devices by
serial ports
• TTL
– Transistor-Transistor Logic
– a serial communication commonly
found in UART (universally
asynchronous receiver/transmitter)
transmission method, very common in
microcontrollers
• used in Arduino

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 90


UART
• A main component of a serial system is UART (universal asynchronous
receiver/transmitter), that is the circuit block that manage the data to and
from the serial interface.
• It functions as a converter between the parallel interface (data bus) and the
serial interface
– on one side of the UART there is a 8-bit (ore more) data bus (plus some
control pin), on the other side there are the 2 serial lines

• UARTs exist also as stand-alone integrate circuits, however typically they are
embedded inside microcontrollers
– example: Arduino Uno - based on ATmega328 - has a single UART,
while Arduino Mega - based on su ATmega2560 - has 4
ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 91
UART

A0 TXD
A1 RXD
A2 RTS
CTS Driver /
D0 etc Receiver
D1
D2 UART
...
D7

Connector
IRQ/
WE/
OE/
CE/

Clock
circuit

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 92


OTHER ASPECTS
• Full-duplex o half-duplex
– a serial interface in which both the devices can send and receive
data can be either full-duplex or half-duplex
• full-duplex if both the devices can simultaneously transmit
and receive (different data lines)
• half-duplex if the devices can send or receive in turn
• Single-wire
– some serial bus can have a single wire, between a device which
always send and a device which always receive
– for instance: Serial Enable LCD

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 93


ASYNC SERIAL ON ARDUINO
• Arduino UNO has one serial port hardware TTL, multiplexed on
GPIO 0 e 1
– pin 0 (RX) is used to receive, pin 1 (TX) to transmit
– these pins are connected to the corresponding ATmega8U2 USB-
to-TTL-serial chip pins
• this converts a serial TTL into an USB and viceversa
– these pins are used for more than one function
• serial and GPIO
• they are mutually exclusive — when using for one function,
the other does not work
• Serial library/class in Wiring
– full access and control of the (async) serial
– can be used to send and receive messages and raw data to the
system connected via USB

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 94


SERIAL LIBRARY
• Serial class is an extension of Stream and includes methods such
as:
– begin(), end()
• to begin and end the communication session
– read(), readBytes(), readBytesUntil(), peek(), available()
• to receive data
– parseFloat(), parseInt()
– write(), flush()
• to transmit data
– print(), println()
• to transmit strings
– setTimeout()
– serialEvent()

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 95


EXAMPLE
• Echo program

char data;

void setup()
{
Serial.begin(9600);
}
Using e.g. ArduinoIDE SerialMonitor, it
is possible to send characters that are
void loop()
read and re-sent to the connected PC
{
if (Serial.available()){
data = Serial.read();
Serial.print(data);
}
}

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 96


SYNCHRONOUS SERIAL
• Synchronous serial interfaces use a clock signal to synchronise and
one or multiple lines for sending/receiving data
– more complex than serial async, but typically higher speed
– main examples: SPI e I2C

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 97


I2C BUS/PROTOCOL
• I2C ("eye squared see" o "eye two see") is a standard bus/protocol
– good speed, minimising the numero of pins required: only 2
– introduced by Philips in ‘80s, then standardised inn ’90
– also called "Two-wire" (TW) since it uses 2 lines for the
communication (data, clock)
• Specs
– 7-bit or 10-bit bus
– bus speed achieves 100 kbit/s in standard mode e 10 kbit/s in
low-speed mode
• recent version have a fast mode at 400 kbit/s, andf fast mode
plus (1Mbit/s) and High-Speed mode (3.4Mbit/s)

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 98


I2C ARCHITECTURE
• Master-slave architecture
– the I2C bus is controlled by a master device
• typically the microcontroller
– it includes one or multiple slave devices that receive info from the
master
• All devices share two lines
– a signal clock (Serial Clock Line, SCL), necessary to synchronise
the communication
– a bidirectional data line (Serial Data Line, SDA) to send and
receive data

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 99


I2C ARCHITECTURE

(chapter 8, [EA])

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 100


MASTER-SLAVE PROTOCOL
• Communication is always started by the master
– slaves can only respond
• Commands send by the master on the bus are received by all slaves
– each slave has its own 7 bit unique ID, which is sent by the master
when it starts the communication
– only the target slave reacts to the message sent by the master
• Typical communication schema:
– Master sends start bit
– Master sends the 7-bit id of the slave device
– Master sends read (0) o write (1) bit, either if it wants to write data on
device registers or read data from
– Slave responds with an ack (ACK bit, active when it is 0)
– In write mode, the master sends data as a sequence of bytes and the
slaves replies with ACKs. In read mode, the master receives a stream of
bytes, sending an ACK after each byte received
• When communication is finished, the master sends a STOP bit

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 101


I2C IN ARDUINO/ATmega328P -
WIRE LIBRARY
• Arduino/ATmega328P natively supports I2C
– 2 pins: A4 e A5
• multiplexed pins (used also for analog reads)
• Wire library
– docs: http://arduino.cc/en/Reference/Wire
– class Wire, extension of Stream
– methods
• begin()
• beginTransmission(), endTransmission()
• write(), requestFrom(), read()
• available()
• onReceive(), onRequest()

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 102


I2C EXAMPLE
• Example:
– using the temperature sensor TC74,
which works with I2C
• Notes
– pin multiplexing: SDA (data) e SCL
(clock) pin are connected to A4 e A5
– when the Wire library is initialised, then
these pics are used for I2C and cannot
be used to analog reads

NOTE: 2 pull-up resistor are needed


(e.g. 4.7 KOhm)

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 103


THE DATASHEET
• Component datasheet
– http://ww1.microchip.com/downloads/en/DeviceDoc/21462D.pdf
• It includes I2C protocol info:

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 104


THE DATASHEET

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 105


THE PROTOCOL
• Table 4-1 => 2 registers to be read da leggere
– one stores the temperature in Celsius
– one the chip config
• Tables 4-3 and 4-4 show hoe the info are stored in the 8-bit register
• Protocol to read the temperature
1.it sends the device id/address in write mode and send a 0 (read cmd)
2.it sends the device id/address in read mode and request a 8 bits (1 byte)
data
3.it waits to receive all 8 bits

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 106


ARDUINO PROGRAM
//Include Wire I2C library
#include <Wire.h> - Wire.beginTrasmission
=> starts the communication session with
int temp_address = 72; //1001000 in decimale the slave
void setup() - Wire.write
{ => sends a 0, specifying that we want to
Serial.begin(9600); read the value of the data register
Wire.begin(); /* lib init */
- Wire.endTrasmission
}
=> sends a stop to notify that we finished
void loop() writing
{
Wire.beginTransmission(temp_address); then
Wire.write(0);
Wire.endTransmission(); - Wire.requestFrom
=> the master waits to receive a byt
Wire.requestFrom(temp_address, 1);
- Wire.available()
while(Wire.available() == 0);
int c = Wire.read();
=> checks if the data has arrived
Serial.print(c); - Wire.read()
Serial.print("C "); => reads the vale
delay(500);
} Example taken from “Exploring Arduino” [EA], p. 171

Complete source code on github


https://github.com/sciguy14/Exploring-Arduino
ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 107
OTHER EXAMPLES OF I2C DEVICES
• Sensors
– MPU6050
• sensore combinato accelerometro+giroscopio
• http://invensense.com/mems/gyro/mpu6050.html
– LSM330
• sensore combinato bussola+accelerometro
• http://www.st.com/web/en/catalog/sense_power/FM89/
SC1448/PF253882
• Actuators/output
– LED Display
• 16x2 char lines

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 108


SPI
• Originally introduced by Motorola, the SPI bus implements a full-
duplex serial protocol that allows for a bidirectional communication
between the master and the slaves
– as I2C it is a serial protocol, based on master-slave schema
– differently from I2C, SPI uses different lines for transmitting and
receiving data, and a specific line to select the slave to
communicate with
• It is not an official formal standard
– so there could be slight differences among implementations and
supported commands
• SPI device are synchronous, as I2C
– data are sent in sync using a shared signal clock (SCLK)

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 109


SPI ARCHITECTURE
• Master-slave architecture
– The SPI bus is controlled by a master device
• typically the microcontroller
– it contains one or multiple slave device that receive info from the
master
• 3 lines for communicating
– a shared clock signal (Shared Serial Clock, SCK)
• used to coordinate the communication
– a shared Master Out Slave In (MOSI) line
• used to send data from the master to the slave
– a shared Master In Slave Out (MISO) line
• used to send data from the slave to the master
– a shared SS (Slave Select) line
• used to select the slave

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 110


SPI ARCHITECTURE

(typically the micro)

(taken from chart 8, [EA])

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 111


MULTISLAVE CONNECTIONS
• Two possibilities to connect multiple slaves to the same master
– using more/multiple SS lines
– using a daisy chain connection

(https://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus)
ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 112
SPI AND ARDUINO/ATmega328P
• Arduino/ATmega328P natively supports SPI
– 4 GPIO (multiplexed): pin 10, 11, 12, 13
• 10 => SS
• 11 => MOSI
• 12 => MISO
• 13 => SCK

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 113


WIRING: THE SPI LIBRARY
• SPI Library - interact with SPI devices
– https://www.arduino.cc/en/Reference/SPI

• Methods
• opening and closing the communication session

SPI.beginTransaction(settings)

SPI.endTransaction();

• transferring data

receivedVal = SPI.transfer(val)
receivedVal16 = SPI.transfer16(val16)
SPI.transfer(buffer, size)

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 114


DETAILS: SETTING
• The configuration specified in beginTransaction includes:
- max speed to be used
- data format - either MSB (Most Significant Bit) or LSB (Least
Significant Bit)
- sampling data modality
• 4 transmission modes, specifying the clock edge to be used
either for sampling or sending data (clock phase) and the
value HIGH or LOW to be used when the clock is idle (clock
polarity)

• Example:
SPI.beginTransaction(SPISettings(14000000, MSBFIRST,
SPI_MODE0));

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 115


DETAILS: DATA TRANSFER
• transfer() method family to transfer data:

receivedVal = SPI.transfer(val)
receivedVal16 = SPI.transfer16(val16)
SPI.transfer(buffer, size)

val: byte to be sent on the bus


val16: word to be sent on the bus
buffer: byte array where to send/receive date

• SPI transfer allows for sending and receiving data simultaneously


– not only single bytes but multiple bytes, using a buffer

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 116


PROTOCOL
• Sequence of actions to communicate with a slave:
• we set the slave select pin SS on LOW
• by means of a digitalWrite on pin SS
• we call SPI.transfer() to transfer the data
• we set the slave select pin SS on HIGH

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 117


AN EXAMPLE
• Using a digital potentiometer: Microchip MCP4231
– as analog potentiometers, it has an adjustable wiper which determines
the resistance between a terminal of the wiper and one of the other
terminals
– 103E variant => resistance interval: 0 … 10 kOhm
• MCP4231 has 2 potentiometers on the same chip
– 7-bit resolution

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 118


To help you reference this information, Figures 9-2 t

DATASHEET: PINOUT
of the key parts of this datasheet. First, take a look at th
the first page of the datasheet.

• Pins P0A, P0W, and P0B


• control pin of the first potentiometer

Credit: © 2013 Microchip Technology, Inc.


• Pins P1A, P1W, and P1B
• control pin of the second potentiometer
• VDD: power (5V)
• VSS: ground
• CS: it is the SS pin of SPI Figure 9-2: MCP4231 Pin-out diagram

• the bar on top means that it is active when the signal is LOW
• 0V => selected, 5V => not selected
• SDI, SDO:
• serial data in and out pins (i.e. MOSI and MISO on the SPI)
• SCK: clock signal of SPI
• SHDN e WP
• used for shutdown and write protect functions. Not used. WP is
unconnected and SHDN is active when LOW => it must be kept at HIGH to
keep the chip active.

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 119


wiper. Just like an ordinary potentiometer, there is a fixed resistance
the A and B terminals of each digital potentiometer. The wiper itself
a resistance that you should take into account. Consider the informa
DATASHEET: DETAILS the fifth page of the datasheet (see Figure 9-3).

188 Part III ■ Communication Interfaces


• Rab is the resistance of the
First, note the resistance of the potentiometer, denoted by RAB. Four available
potentiometer
variants of this chip are available, each with a different resistance value, ranging

Credit: © 2013 Microchip Technology, Inc.


• The
fromwiper
5kΩ topin has
100kΩ. Theitsdevices
own themselves
resistance are marked with their variation.
(Rw):
In thisfrom 75you
chapter, to use
160theOhm
103 variant, which has a resistance of about 10kΩ.
Importantly, DigiPots are generally not very accurate devices. You can see from
the datasheet that the actual resistance for your device may vary as much as
±20%! Also worth noting is the wiper resistance. The actual wiper pin has a
resistance somewhere between 75 and 160Ω. This can be significant, especially
when driving a speaker or an LED.
You also need to understand the SPI commands that you must to issue to the
• Commands - it.
device to control 2 In
types
the case of the MCP4231, you issue two commands to the
Figure 9-3: MCP4231 AC/DC characteristics table
device: The first specifies the register to control (there is one register for each
• 8-bit command: to increment the potentiometer using a single byte
DigiPot), and the second specifies the value to set the potentiometer. Take a look at
• 16-bit
the command:
SPI communication to set the
specification complete
excerpted from thestate
datasheet in Figure 9-4.

Credit: © 2013 Microchip Technology, Inc.


Figure 9-4: MCP4231 SPI command formats
ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 120
EXAMPLE: CONTROLLING LED
Chapter 9 ■ The SPI Bus 189

the next 2 bits are the first 2 data bits, which should always be 0 because the
potentiometer can only be as high as 128.

INTENSITY
This is all the information you need to wire the DigiPot correctly and to
send SPI commands to it from your Arduino. Now, you wire it up to control
the brightness of some LEDs.

Setting Up the Hardware

• 2 potentiometers to control the intensity of 4 legs To fully flesh out your knowledge of SPI communication, you’ll use two MCP44231
DigiPot ICs, for a total of four controllable potentiometer channels. Each one
is used to control the brightness of two LEDs by varying the series resistance

(example in [EA], chap. 9) Chapter 9 ■ The SPI Bus 191


in-line with the LED. When used in this fashion, you need to use only two
terminals of each potentiometer. One end of each potentiometer connects to
the 5V rail (through a resistor), and the wiper pin connects to the anode of the
LED. Consider the schematic Figure 9-5, which shows this connection scheme.

Image created with Eagle.


Image created with Fritzing.

Figure 9-5: Potentiometer LED setup

Figure 9-6: Potentiometer LED setup

The code in Listing 9-1 executes all these steps and includes a function for
passing the SS pin, register byte, and command to a given chip via SPI. The SPI
.begin() command enables you to initialize the SPI interface on the hardware
SPI pins of the Arduino, and you can use SPI.transfer() to actually send data
ESIOT ISI-LT - UNIBO
over the SPI bus. Embedded systems based on microcontrollers 121
EXAMPLE: SOURCES
#include <SPI.h>

const int SS1 = 10; // Slave Select Chip 1


const int SS2 = 9; // Slave Select Chip 2
const byte REG0=B00000000; // Register 0 Write command
const byte REG1=B00010000; // Register 1 Write command

void setup()
{
/* set pin directions for SS */
pinMode(SS1, OUTPUT);
pinMode(SS2, OUTPUT);

/* initialize SPI */
SPI.begin();
}

(chap. 9, [EA])

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 122


EXAMPLE: SOURCES
void loop() { /* this will set 1 LED */
for (int i=0; i<=128; i++) /* to the specified level */
{ /* Chip 1 (SS 10) Register 0 is Red */
setLed(SS1, REG0, i); /* Chip 1 (SS 10) Register 1 is Yellow */
setLed(SS1, REG1, i); /* Chip 2 (SS 9) Register 0 is Green */
setLed(SS2, REG0, i); /* Chip 2 (SS 9) Register 1 is Blue */
setLed(SS2, REG1, i); void setLed(int SS, int reg, int level)
delay(10); {
} /* Set the given SS pin low */
delay(300); digitalWrite(SS, LOW);
/* Choose the register to write to */
for (int i=128; i>=0; i--) SPI.transfer(reg);
{ /* Set the LED level (0-128) */
setLed(SS1, REG0, i); SPI.transfer(level);
setLed(SS1, REG1, i); /* Set the given SS pin high again */
setLed(SS2, REG0, i); digitalWrite(SS, HIGH);
setLed(SS2, REG1, i); }
delay(10);
}
delay(300);
}

(chap. 9, [EA])
ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 123
I2C AND SPI - COMPARISON
• Many devices - including accelerometers, digital potentiometers,
displays, … - are available both on I2C and SPI
• Comparison
– I2C
• only 2 lines
• slave addressing modality more agile
– SPI
• can work with higher speed
• pull-up resistors not needed

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 124


REFERENCES
• [EA] Jeremy Blum. Exploring Arduino. Wiley
• Wiring
– http://wiring.org.co/
• MikroElektronika books about micro-controllers
– http://www.mikroe.com/chapters/view/74/pic-basic-book-
chapter-1-world-of-microcontrollers/

ESIOT ISI-LT - UNIBO Embedded systems based on microcontrollers 125

You might also like