Post on 11-Jun-2018
transcript
MCU Interfaces
December 2, 3 2014
Politecnico di Milano, “Advanced Operating Systems”
David Siorpaes
Outline
• STMicroelectronics presentation
• Microcontroller Input/Output
• Analog to Digital Converter interface
• Buses overview and practical examples
• SPI for interfacing with an accelerometer: code review and demo
• Alternate Functions
• I2C for driving a port expander and interfacing with a NFC memory
• UART for driving a Bluetooth module: code review and demo
• Bluetooth module driver hands-on
• Development and debugging tools
2
All code and documentation is available
from Google Code Project:
https://code.google.com/p/stm32-boilerplate/
3
• A global semiconductor leader
• The largest European semiconductor company
• 2013 revenues of $8.08B
• Approx. 45,000 employees worldwide
• Approx. 9,000 people working in R&D
• 12 manufacturing sites
• Listed on New York Stock Exchange, Euronext Paris
and Borsa Italiana, Milano
Who we are 4
As of December 31, 2013
Where you find us 5
Our automotive products
are making driving safer,
greener and more
entertaining
Our smart power products
are allowing our mobile products to operate longer
and making more of our energy resources
Our MEMS & Sensors
are augmenting
the consumer experience
Our Microcontrollers
are everywhere
making everything smarter
and more secure
Our digital consumer products
are powering the augmented
digital lifestyle
Example consumer electronics products
• MEMS devices (accelerometer, gyroscopes, magnetometer, pressure
sensor) in Samsung Galaxy line smartphones
• STM32 MCUs in Microsoft Xbox controller
• MEMS devices in Nintendo controllers
• Telepass device for Autostrade s.p.a.
• Fitbit fitness and health trackers
6
Digital
Convergence
Group
(DCG)
Imaging,
BiCMOS, ASIC
& Silicon
Photonics
(IBP)
Automotive
Product Group
(APG)
Analog, MEMS
& Sensors
(AMS)
Microcontroller,
Memory &
Secure MCU
(MMS)
Embedded Processing Solutions
(EPS)
Industrial &
Power Discrete
Group
(IPD)
Product Segments 7
Sense & Power and Automotive
Products (SP&A)
Effective Q4 2014, ST discontinued its commodity camera module
products and DCG and IBP product groups merged to form DPG.
ST Central Lab Organization
• We belong to a cross-division organization: Advanced Systems
Technology with specific focus on embedded software
• We provide to our internal customers early engineering, prototyping
and integration solutions of emerging software technologies on STM
products.
• Main competence areas
• Firmware design and development on STM32 microcontrollers
• Platform integration, benchmark and optimization
• Linux and Android OSes
• Current activities
• Optical Heart Rate Monitoring application
• Open Development Environment initiative for STM32 MCUs portfolio
8
A complex system… 10
Gyroscope
Accelerometer
Magnetometer
Pressure Sensor
Light Sensor
Camera
Touchscreen
GPS
NFC
Battery Gauge
MCU Applications
• Typically, MCU applications implement this simple common
architecture:
• Sense
• Compute
• Communicate and/or actuate
11
Sense Compute Communicate/
Actuate
Accessing MCU interfaces
• MCU peripherals are exposed to programmer through a set of
memory mapped registers
• Registers are used to
• Configure peripheral (e.g.: speed, data format, interrupt generation,…)
• Data I/O: by reading/writing selected registers data is received/sent from/to the
peripheral
• Status indication: Transmission Completed, RX FIFO not empty,…
• Access to registers is abstracted by C libraries
13
MCU data transfer schemes
• Poll
• MCU actively polls peripheral status bits waiting for data to be sent/received
• Interrupt
• MCU is interrupted as data is received or data transmission is completed
• DMA
• MCU delegates data transfer to a dedicate Direct Memory Access engine
14
Analog sensors
• Simplest sensors are analog, i.e.: information is expressed as a
voltage or current
• Temperature sensors
• Gas sensors
• Photodiodes, phototransistors, photoresistors,...
• Analog to Digital Converter (ADC) is used to acquire data
15
MCU Analog Sensor
Buffer,
Filter,
Amplifier,
TIA,...
Voltage A
D
C
Digital Sensors
• Most sensors have digital nature
• ADC conversions are performed onboard
• Data is conveyed digitally by means of a BUS
18
MCU Digital Sensor I
F
BUS
What is a bus ?
• A bus is a bunch of wires used to transfer digital information from one
device to another
• A bus definition includes a set of electrical, timing and protocol rules
that describe how to convey information from A to B
• Trivial examples:
• GPIO that conveys one single bit of information: on and off
• Eight GPIOs + strobe bit convey a byte of information. Used by old printer parallel
ports
19
Buses taxonomy
Buses categories
• Serial vs Parallel
• Synchronous vs Asynchronous
• Master/Slave vs uniform roles
• On-chip vs off-chip
20
Buses Examples
• USB
• SCSI
• UART, I2C, SPI
• AMBA
• CSI, DSI
• Display Port, HDMI
• CAN
Buses for embedded applications
• We will focus on the most important buses typically used in
embedded applications to connect the microcontroller to external
peripherals
• Sensors: e.g.: accelerometers, gyros, magnetometers, pressure sensors,…
• Actuators/UI: (e.g.: LED drivers, Port Expanders, displays)
• Storage (e.g.: SD-Cards, serial memories,…)
• Basic and widely used buses are:
• UART
• SPI
• I2C
21
SPI BUS
• Serial Peripheral Interface. Developed by Motorola
• Master/Slave bus. Communication is always initiated by ‘Master’
device and is bi-directional
• Full-duplex synchronous bus: a clock signal triggers data transfer
• Four wire bus:
• SCLK: Clock
• MISO: Master Input Slave Output
• MOSI: Master Output Slave Input
• CS (or SS): Chip Select (or Slave Select). Out of Band addressing
23
STM32 LIS3DH
SPI BUS implementation
• Very simple hardware implementation: master and slave shift
registers are clocked synchronously to drive MISO/MOSI lines
• At every clock pulse, a bit is exchanged between Master and Slave
even if no information exchange is needed by one of the two sides
• After eight clock periods, Master and Slave registers are swapped
24
How SPI works
• When Master wants to address the Slave it asserts the Chip Select
signal and starts driving the clock signal
• For both directions:
• Data is sampled on Clock Rising edge
• Data is propagated on Clock Falling edge
25
CS
SCLK
MISO
MOSI
Interfacing with the device
• SPI just provides raw, bi-directional data communication mean
• Communication protocol on top of SPI is defined by the specific
device
• However, a very common protocol is to use a register-based data
communication scheme:
• Device specifies a set of “registers” for implementing control and data paths
• Master reads/writes such registers using well defined SPI communication patterns
• Let’s have a look at the LIS3DH accelerometer specification…
26
LIS3DH accelerometer
• An accelerometer senses mechanical accelerations on three axis
• Applications: Motion activated functions, Free-fall detection,
Click/double click recognition, Pedometer, Display orientation,
Vibration monitoring and compensation,…
27
Low level SPI Access 32
STM32
Standard Peripheral Library/Cube
LIS3DH driver
Low Level SPI access
Application
LIS3DH driver 35
STM32
Standard Peripheral Library/Cube
LIS3DH driver
Low Level SPI access
Application
39
• Modern MCUs are
very complex and rich of
peripherals
• But MCU pins are a very
scarce resource…
Alternate Functions
• Most MCU pins can have different mappings
• GPIO Input, GPIO Output
• Analog Input, Analog Output
• Alternate Function: connection to internal peripherals
• See page 44 of the STM32F4 specification
41
The I2C bus
• SPI is a very common way to interface with devices but has one
severe limitation: N slaves implies 3 + N wires
• More MCU pins
• More complex PCB design
43
[…]
The I2C bus
• Inter Integrated Circuit (I2C) is a standard developed by Philips in
1982 that defines Inter-Chip communication protocol
• Two-wire low speed communication protocol. Data and Clock signals
• Synchronous communication.
• Master-Slave architecture, with possibility to address multiple slaves
“in-band” (vs Out of Band like SPI). 7-bit addresses
44
Pull UP resistors
I2C principles • Communication is always initiated
by the Master. Master drives clock
• Start/Stop conditions define
communication boundaries:
• Start: SCL HI, SDA falling
• Stop: SCL HI, SDA rising
• These are the only two cases when
SDA is allowed to toggle with SCL HI
• Data is transferred by driving SDA
line during SCL LOW.
• SDA is sampled on SCL rising
edge
45
I2C principles
• Master initiates an I2C transaction with a START condition
• The 7-bit address of the device follows the START condition
• LSB indicates whether the Master intends to perform a Read or Write
operation from/to the device
• The addressed device replies with an ACK/NAK bit
• The communication from now on is device specific and usually
includes addressing and reading/writing internal registers (like SPI)
• Data recipient (Either Master or Slave) acknowledges 8 bit
transactions via ACK bit
• Let’s see some examples...
46
NXP’s PCF8574 port expander example
• GPIO pins are a very limited resource in MCU designs
• Port Expanders devices are used to:
• Extend GPIOs availability
• Enable higher current driving capabilities (e.g.: LED drivers for backlight)
• Pulse Width Modulation (PWM)
• “Remotize” actuation block from controller block (e.g.: display, touch sensor)
• Drives up to eight GPIOs
• Configurable address (three free bits)
• No internal registers
47
The hardware/software interface 49
Send Start Sequence
Send Slave Address
Wait for Slave ACK
Send data
Wait for Slave ACK
Send Stop Sequence
Wait for Start OK
UART bus
• Derives from old fashioned TTY terminals and modems
• Very simple bus: just two wires
• Asynchronous interface: both ends must agree on baud rate
• A logical ‘1’ is represented as a high signal level
• Start and stop conditions mark 8-bit data boundaries
52
Start condition Stop condition Data Frame
0
1
Time
A B TX
TX RX
RX
The hardware/software interface
• A ‘write’ operation to Data Register triggers data emission on TX pin
• A ‘read’ operation from Data Register returns the last byte on wire
• Status registers (aka flags) convey information on transmission status
• TXE: Transmit data register empty
• RXNE: Read data register not empty
• FR: Framing Error
• Interrupts can be associated to above flags
• DMA can be used on both TX and RX side
• Let’s see the Bluetooth driver as an example
53
Bluetooth introduction
• Bluetooth is a low range low data rate wireless transmission protocol
• Operates in the 2.4GHz ISM band
• Bluetooth SIG standardization body defines:
• Radio physical link layer
• MAC
• Service discovery
• Application profiles
55
Bluetooth protocol stack 56
Radio
Baseband
Link Manager
Audio
Control
HCI interface
L2CAP
SDP TCS RFCOMM
SPP BNEP OBEX
Required
Optional
Audio
App
Management
Apps
Phone
Apps
IP
Apps vCard
No standard
Network
stack (HW)
Network
stack
(SW or HW)
Application
Layer (SW) Generic
Apps
Stack runs on host. Typical in PC world 57
Bluetooth Radio
Protocol Stack
Application
HCI interface
UART/SPI/USB/…
C Software interface
e.g.: socket
Stack runs on external module 58
Bluetooth Radio
Protocol Stack
Application
Adapter IF
HCI interface
SPI
AT Commands
UART
Bluetooth
Module
Comparing the two approaches
Stack on Host
• No extra MCU, low cost
• Finer grained control, easy to
upgrade, debug, patch
• Bigger footprint
• Flash and RAM
• MCU cycles
• More complex integration
• Usually closed source
• Toolchain/OS considerations
• Real time constraints
Stack off host
• Can be driven by very simple and
low cost MCUs
• Very easy to integrate. No
dependencies with OS and
Toolchains
• Usually supports limited profiles
(Typically SPP only)
• Software needs to manage
control/data path split
59
SPP Profile
• SPP stands for Serial Port Profile. It is meant to act as a bare Serial
Port found in Windows (e.g.: COM1) or Linux (e.g.: /dev/ttyS0)
• Very simple mean to make an embedded device to communicate to a
host system (PC or phone)
• Does not define any protocol or data format on top of plain serial. This
is left to application/middleware developer (cfr.: application profiles
defined in BTLE)
60
SPBT2632 main features
• On module Bluetooth stack
• Data path and control path on UART bus
• Enables SPP profile and, optionally, audio SCO channels
• Seven GPIOs
62
SPBT2632 modes
• Data path and control paths are not
split using registers as seen before
• SPBT2632 and most Bluetooth SPP
modules on market feature two
different “modes”:
• Command mode: module is
disconnected. Accepts commands
and sends events
• Data mode: module is connected.
All data on the interface port is
transmitted/received on/from air
• But… we just have one UART port !
64
See page 10
of the spec
SPBT2632 state machine 65
stm SPBT2632C2A-StateMachine
Reset
Command/DisconnectedBypass/Connected
Command/Connected
[Device Disconnected]
/AT-AB
ConnectionDown
[AT+AB Bypass]
/AT-AB
-BypassMode-
[^#^$^% plus two seconds idle]
/AT-AB -CommandMode-
[Device Disconnected]
/AT-AB
ConnectionDown
[Device Paged]
/AT-AB ConnectionUp 38e7d8e26fdd
AT-AB -BypassMode-
Simplified State Machine 66
Start
Disconnected Connected
Unknown
Reset/”AT-AB BDAddress XXXXXXXX”
Connection/”AT-AB -BypassMode-”
Disconnection/”AT-AB ConnectionDown”
Simple Bluetooth driver code review
We will cover:
• Initialization of needed peripherals
• UART port signals
• GPIO for module reset
• Usage of basic Operating System synchronization mechanisms
(Using RTX OS from ARM)
• DMA mode UART transmission
• IRQ mode UART reception
68
Before coding…
Use case
• Wireless debugging and logging
facility for a wearable fitness device
• Connection is always initiated by
client. I.e.: module is Bluetooth
slave
• Data is collected by a
Linux/Windows PC or Android
smartphone for real-time
visualization and logging
Requirements
• Data flow in downstream only. Must
support up to 20 32-bit channels at
100Hz
• Shall consume as little processing
power as possible
• No stringent fault tolerance
69
Client side APIs
• Windows
• Configuration differs among Windows OS version and vendor drivers
• Provides high level access to SPP profile via COM port emulation
• APIs are identical to serial port communication
• Linux
• Uses ‘HCI tools’ for device configuration, pairing, etc. Unified interface
• Uses UNIX socket abstraction to establish connections and transfer data OR
• Uses ‘rfcomm’ utility to expose a UART like device like Windows
• Android
• Android Java APIs are basically a plain wrapper of Linux C APIs
73
CubeMX
• CubeMX helps configuring MCU pins alternate functions and
generates relevant initialization code for you
76
CubeMX
• CubeMX generates Clock Tree initialization code according to your
application requirements
77
Logic Analyzer
• A logic Analyzer is a debugging
instrument to analyze and decode
digital signals
• Very useful to debug low level
drivers
• Misconfigured pins and/or ports
• Protocol mismatches
• Timing conditions
78
ST-Link Utility
• Low profile debugger, freely
available from ST site
• Features:
• Program/Verify/Download Flash
memory
• Reset MCU, step by step execution
• ITM port. Very useful for immediate
printf-like facility
79