Mastering Microcontroller With Embedded Driver Development: Fastbit Embedded Brain Academy Check All Online Courses at
Mastering Microcontroller With Embedded Driver Development: Fastbit Embedded Brain Academy Check All Online Courses at
GPIO Port A
PA.1 PA.15
Port „A‟ having many pins Port „Soller Town‟ having many boats
Each port have Each port have Each port have
8 i/o pins 32 i/o pins 16 i/o pins
GPIO Pin Behind the Scene
How does a GPIO pin is actually
implemented inside the MCU?
Enable Line
Input buffer
YOUR MCU
+VCC
Enable Line
source
Output buffer gate
PMOS
T1
Pin
Pin
drain
T2
NMOS
Input buffer gate
source
MCU GND
Enable Line
Output buffer +VCC
Pin S
T1 P Pin
G
D
Input buffer
T2 N
S
MCU
Enable Line +VCC
Output buffer +VCC
Pin S
T1 P Pin
G
D
Input buffer
T2 N
S
MCU
Enable Line
Output buffer +VCC
Pin S
T1 P Pin
G
D
Input buffer
T2 N
S
MCU
GPIO INPUT MODE
High Impedance(HI-Z) State
Let‟s understand, what exactly is this High
Impedance state, that people talk about when
the pin is in input mode ??
S
T1 P
Pin Floating=Hi-Z
D G
GND
GND
GPIO INPUT MODE
Pull-Up/Pull-Down State
+Vcc
Input Buffer
Pin
Input Buffer Ri Re
Pin
GND
GPIO OUTPUT MODE
Open-drain State
+VCC
S
P T1 Pin
G
D
N T2
S
GND
+VCC
S
P T1 Pin
G
D
N T2
S
GND
GPIO OUTPUT MODE
Open drain with Pull-Up
+VCC +VCC
Ri Re
Pin Pin
D D
G
P G P
S S
GND GND
Open drain with internal pull up Open drain with External pull up
Practical Usage -1
R
R
Pin Pin
D D
LED LED
G N G N
S S
SCL Tx D
SDA Tx D G
N
G
N
S
S
GND GND
GPIO OUTPUT MODE
Push-Pull State
Output Mode with Push-Pull
Configuration +VCC
S
P T1 Pin
G D
N T2
S
GND
+VCC +VCC
Ri Re
Pin Pin
D D
G
P G P
S S
GND GND
Open drain with internal pull up Open drain with External pull up
How to drive a LED from
Push-Pull GPIO Pin ??
+VCC
S
P T1
G D Pin
N T2
S
R
GND
LED
GND
Discovery Board LED Connection
+VCC
S
P T1
G D PD12
Pin
N T2
S R
GND LED_GREEN
Optimizing IO Power
Consumption
Leakage Mechanism By Input Pin Floating
Fixed to High
MCU +VCC +VCC MCU +VCC
S S
T1 P T1
Pin P
Pin
D D
G G
T2 N T2 GND
N
S
S
Fixed to Low
GND GND
Voltage of input
MCU is not fixed
+VCC
May be 0.5Vcc Input Logic Level
or 0.3Vcc
S
T1 P Pin
D G
T2 N
S
GND
GND
Valve opened
Valve Closed partially
No water flows
Water Tickles out
GPIO Programming Structure
Port Direction(Mode)
register
32 bit reg.
32 bit reg. 32 bit reg.
INTERRUPT
When MCU pin is in INPUT
mode it can be configured to
issue an interrupt to the
processor
Input configuration
Input mode : Summary
Slew rate
MEDIUM
Slew rate
HIGH
Slew rate
VERY HIGH
Slew rate
VERY HIGH
Slew rate
Applicability of SPEED register
configuration
Don‟t care
Pin Mode =
INPUT
So, Speed setting is only applicable when the pin is in output mode
GPIO Port Pull-Up/Pull-Down
Register
GPIO Port Input Data Register
GPIO Port Output Data
Register
GPIO Functional Summary
By taking various modes and pull up /pull down resistors combinations
below configurations can be obtained for a GPIO pin
Input floating
Input pull-up
Input-pull-down
Analog
Output open-drain with pull-up or pull-down capability
Output push-pull with pull-up or pull-down capability
Alternate function push-pull with pull-up or pull-down capability
Alternate function open-drain with pull-up or pull-down capability
Alternate Functionality
configuration of a GPIO pin
An MCU GPIO Pin
MODE(Afx) Functionality
AF0 MCO1
AF1 TIM1_CH1
AF2 Not Supported
AF3 Not Supported
AF4 I2C3_ SCL
AF5 Not Supported
AF6 Not Supported
AF7 USART1_ CK
Exercise :
List out all the 16 possible alternation functionalities supported by GPIO
port „A‟ pin number 8 (GPIOA.8)
MODE(Afx) Functionality
AF8 Not Supported
AF9 Not Supported
AF10 OTG_FS_ SOF
AF11 Not Supported
AF12 Not Supported
AF13 Not Supported
AF14 Not Supported
AF15 EVENT OUT
Exercise :
List out all the alternation functionalities supported by GPIO port „C‟ pin
number 6 (GPIOC.6)
Solution :
List out all the alternation functionalities supported by GPIO port „C‟ pin
number 6 (GPIOC.6)
MODE(Afx) Functionality
AF0 Not Supported
AF1 Not Supported
AF2 TIM3_CH1
AF3 TIM8_CH1
AF4 Not Supported
AF5 I2S2_MCK
AF6 Not Supported
AF7 Not Supported
Solution :
List out all the alternation functionalities supported by GPIO port „C‟ pin
number 6 (GPIOC.6)
MODE(Afx) Functionality
AF8 USART6_TX
AF9 Not Supported
AF10 Not Supported
AF11 Not Supported
AF12 SDIO_D6
AF13 DCMI_D0
AF14 Not Supported
AF15 EVENT OUT
GPIO Alternate
Function Register
Example
AFx = AF8
( This info you can only get from datasheet of the MCU not from
RM in the case of ST‟s MCUs)
Solution: PA0 as UART4_TX
AFR settings
GPIOA_AFRL
Solution: PA1 as UART4_RX
AFx = AF8
GPIOA_AFRL
Solution: PA10 as TIM1_CH3
AFx = AF1
GPIOA_AFRH
Enabling /Disabling GPIO Port
Peripheral Clock
RCC Peri. Clock Enable Registers
RCC_AHB1ENR
RCC_AHB2ENR
RCC_AHB3ENR
RCC_APB1ENR
RCC_APB2ENR
Peripheral Driver
Development
High level project
architecture
Sample Applications
Driver Layer
(Device header)
gpio_driver.c , .h i2c_driver.c , .h Stm3f407xx.h
spi_driver.c , .h uart_driver.c , .h
STM3F407x MCU
3 Sample Applications
Driver Layer
(Device header)
gpio_driver.c , .h i2c_driver.c , .h Stm3f407xx.h
2
1
spi_driver.c , .h uart_driver.c , .h
STM3F407x MCU
What is Device Header file and what it
contains ?
This is a header file („C‟ header file in our case) which contains Microcontroller
specific details such as
Stm3f407xx.h
This simply means that registers of peripherals hanging on APB2 bus will appear
on address 0x40010000 onwards in the memory map of the MCU.
Defining base addresses of AHB1
peripherals, APB1 and APB2 peripherals
AHB1
APB1
APB2
0x40020000
MODE Reg. OUTPUT TYPE Reg. SPEED Reg. PUPDR Reg. IDR Reg. ODR Reg. BSRR Reg.
GPIO mode
GPIOx
Peripheral Configurable items
For user application
GPIO speed
GPIO outputtype
GPIO Pullup-pulldown
Configure alternate
functionality
Interrupt Handling
GPIO Pin Interrupt Configuration
NVIC_ISER0
IRQ31 IRQ16
0 has no effect
1 enables the interrupt
Interrupt Set-enable Registers
NVIC_ISER1
IRQ63 IRQ48
IRQ47 IRQ41
IRQ34 IRQ33 IRQ32
0 has no effect
1 enables the interrupt
Interrupt Set-enable Registers
NVIC_ISER2
IRQ95 IRQ80
0 has no effect
1 enables the interrupt
Interrupt Clear-enable Registers
NVIC_ICER0
IRQ31 IRQ16
0 has no effect
1 disable interrupt
Interrupt Priority Registers
NVIC_IPR0-NVIC_IPR59
Exercise
Write a program to toggle the on board LED with some delay .
Case 1 : Use push pull configuration for the output pin
Case 2 : Use open drain configuration for the output pin
Discovery Board LEDs
CH3
CH1
USB Logic
Analyzer
CH2
CH0
GND GND
Probing LED Toggling using USB Logic Analyzer
CH0
USB Logic analyzer
CH1
To PC
GND
Exercise
Write a program to toggle the on board LED whenever the on board button is pressed
Exercise
Write a program to connect external button to the pin number PB12 and external LED to PA14
Toggle the LED whenever the external button is pressed
Exercise
Toggle a GPIO pin with no delay between
GPIO high and GPIO low and measure the
frequency of toggling using logic analyzer
Exercise
Connect an external button to PD5 pin and toggle the
led whenever interrupt is triggered by the button press.
1. Four I/O pins are dedicated to SPI communication with external devices.
2. MISO: Master In / Slave Out data. In the general case, this pin is used to
transmit data in slave mode and receive data in master mode
3. MOSI: Master Out / Slave In data. In the general case, this pin is used to
transmit data in master mode and receive data in slave mode.
4. SCK: Serial Clock output pin for SPI master and input pin for SPI slaves.
5. NSS: Slave select pin. Depending on the SPI and NSS settings, this pin can be
used to select an individual slave device for communication
SCLK SCLK
MOSI MOSI Slave1
MISO MISO
Master gpio1 ss
gpio2
gpio3 SCLK
MOSI Slave2
MISO
ss
SCLK
MOSI Slave3
MISO
ss
Protocol Type Max distance(ft.) Max Speed Typical usage
(bps)
USB 3.0 dual simplex 9 (typical) 5G Mass storage,
serial (up to 49 video
with 5 hubs)
SCLK
MOSI
MISO Slave3
ss
SCLK
Master SCLK
Send
MOSI
MOSI
Receive
MISO MISO
gpio ss
MINIMAL SPI BUS
The SPI bus allows the communication between one master device and
one or more slave devices. In some applications SPI bus may consists of just
two wires - one for the clock signal and the other for synchronous data
transfer. Other signals can be added depending on the data exchange
between SPI nodes and their slave select signal management.
Serial Clock
SCLK SCLK
Master Out Slave In Slave
Master MOSI MOSI
MISO MISO
gpio ss
SPI Hardware :Behind the scenes
SPI Hardware :Behind the scenes
SCLK
SPI clock
SCLK
generator
Master Slave
MISO
SPI Hardware :Behind the scenes
1
SCLK
SPI clock
SCLK
generator
Master Slave
MISO
SPI Hardware :Behind the scenes
1 2
SCLK
SPI clock
SCLK
generator
Master Slave
MISO
SPI Hardware :Behind the scenes
1 2 3
SCLK
SPI clock
SCLK
generator
Master Slave
MISO
SPI Hardware :Behind the scenes
1 2 3 4
SCLK
SPI clock
SCLK
generator
Master Slave
MISO
SPI Hardware :Behind the scenes
1 2 3 4 5
SCLK
SPI clock
SCLK
generator
Master Slave
MISO
SPI Hardware :Behind the scenes
1 2 3 4 5 6
SCLK
SPI clock
SCLK
generator
Master Slave
MISO
SPI Hardware :Behind the scenes
1 2 3 4 5 6 7
SCLK
SPI clock
SCLK
generator
Master Slave
MISO
SPI Hardware :Behind the scenes
1 2 3 4 5 6 7 8
SCLK
SPI clock
SCLK
generator
Master Slave
MISO
CUSTOMIZING SPI BUS : BUS CONFIGURATIONS
The SPI allows the MCU to communicate using different configurations, depending
on the device targeted and the application requirements.
FULL-DUPLEX COMMUNICATION
Master Slave
MSBit LSBbit MSBit LSBbit
Up to 16-bit shift MISO MISO Up to 16-bit shift
register register
MOSI MOSI
In this configuration, the shift registers of the master and slave are linked using two unidirectional
lines between the MOSI and the MISO pins. During SPI communication, data is shifted
synchronously on the SCK clock edges provided by the master. The master transmits the data to
be sent to the slave via the MOSI line and receives data from the slave via the MISO line.
Remember that in SPI communication ,slave will not
initiate data transfer unless master produces the
clock.
HALF -DUPLEX COMMUNICATION
Master Slave
MSBit LSBbit MSBit LSBbit
MISO MISO
8-bit shift register 8-bit shift register
R
MOSI MOSI
In this configuration, one single cross connection line is used to link the shift registers of the
master and slave together. During this communication, the data is synchronously shifted
between the shift registers on the SCK clock edge in the transfer direction selected
reciprocally by both master and slave
SIMPLEX COMMUNICATION
Master Slave
MSBit LSBbit MSBit LSBbit
MISO MISO
8-bit shift register 8-bit shift register
MOSI MOSI
Simplex single master, single slave application (master in transmit-only/slave in receive-only mode)
MOSI MOSI
SCK SCK
SPI Clock
generator
NSS NSS
MOSI MOSI
SCK SCK
SPI Clock
generator
NSS NSS
Software NSS management (SSM = 1): in this
configuration, slave select information
is driven internally by the SSI bit value in
register SPIx_CR1. The external NSS pin is
free for other application uses.
Hardware or software slave select management can
be set using the SSM bit in the SPIx_CR1 register:
Scenario of single master and single slave
Master Slave
MSBit LSBbit MSBit LSBbit
MISO MISO
8-bit shift register 8-bit shift register
MOSI MOSI
SCK SCK
SPI Clock
generator
NSS NSS
Hardware NSS management (SSM = 0):
Hardware NSS management (SSM = 0): Nss pin must be pulled low to active salve
Nss pin must be in output mode. to communicate with master
The NSS pin is managed by the
hardware
Hardware or software slave select management can be set using the SSM bit in the
SPIx_CR1 register:
In this application you
cannot use software slave
management . You have
to use hardware slave
management
SPI Communication Format
SPI Communication Format
•The serial clock (SCK) synchronizes the shifting and sampling of the information on
the data lines
•The communication format depends on the clock phase, the clock polarity and
the data frame format. To be able to communicate together, the master and
slaves devices must follow the same communication format.
CPOL(CLOCK POLARITY)
The CPOL (clock polarity) bit controls the idle state value of
the clock when no data is being transferred
If CPOL is reset, the SCLK pin has a low-level idle state. If
CPOL is set, the SCLK pin has a high-level idle state.
CPOL =0
CPOL =1
CPHA(CLOCK PHASE)
Data line 1 0 1
Data line 1 0 1
CPHA=1
1 Data will appear on the lines during first edge of the SCLK
CPHA=1
2 Slave captures the data here ( 2nd edge of the SCLK)
CPHA=1 1
Data will appear on the lines during first edge of the SCLK
L
CPHA=0 1 Data will appear on the lines during 2nd edge of the lock
2 Slave captures the data here ( 1st edge of the SCLK)
CPHA=0
Different SPI Modes
If CPHASE=1
Data will be sampled on the trailing edge of the
clock.
If CPHASE=0
Data will be sampled on the leading edge of the
clock.
SPI peripherals of your MCU
AHB1
APB1
APB2
First you have to know the speed of the APBx bus on which
the SPI peripheral is connected
HSI
16MHz
HSE
PLL
PLL
Driver Layer
(Device header)
gpio_driver.c , .h i2c_driver.c , .h Stm3f407xx.h
spi_driver.c , .h uart_driver.c , .h
STM3F407x MCU
SPI Initialization / peripheral clock
control
SPI TX
SPI RX
APIs
SPI Driver
SPI Interrupt config. &
handling
SPI_BusConfig
SPI_DFF
SPIx Peripheral Configurable items
For user application
SPI_CPHA
SPI_CPOL
SPI_SSM
SPI_Speed
SPI handle structure and
configuration structure
SPI Configuration Structure
Yes
Len=0 ? Exit from the function
No
Wait until the Tx buffer is empty End
16 bit
DFF ? 1
0
8Bit
Load DR with 1 byte of data Load DR with 1 byte of data
And increment the buffer address And increment the buffer adress
Len-- Len--
Receive data Start
Yes
Len=0 ? Exit from the function
No
Wait until the Rx Buffer is non
empty End
16 bit
DFF ? 1
0
8Bit
Read DR for 1 byte of data Read DR for 2 bytes of data
And increment the rx buffer address And increment the rx buffer address
Len-- Len--
Exercise :
In this exercise master is not going to receive anything for the slave. So you may not configure the
MISO pin
Note.
Slave does not know how many bytes of data master is going to send. So master first sends the
number bytes info which slave is going to receive next.
Things you need
1 .Arduino board
2. ST board
3. Some jumper wires
4. Bread board
When the button on the master is pressed, master sends a command to the slave and
slave responds as per the command implementation .
Master Slave
Master sends a command
NACK 0xA5
Slave response ACK or NACK BYTE
ACK 0xF5
IF ACK 1 or more Command Arguments
Take action
IF NACK
according to
command
Display error
message
Then, connect it
back
CMD_SENOSR_READ <analog pin number >
<analog pin number > Analog pin number of the Arduino board ( A0 to A5)
(1 byte)
Slave Action : Slave should read the analog value of the supplied pin
Slave Action : Receive the message and display via serial port
Enter main()
All inits
Execute CMD_LED_CTRL
Execute CMD_SENSOR_READ
Execute CMD_LED_READ
Firmware Write 0xAB Data Register
APB1/APB2
Read
Rx buffer
Shift Register
TX buffer
Write
Firmware Write 0xAB Data Register
APB1/APB2
Read
Rx buffer
Shift Register
TX buffer
Write
Firmware Read Data Register
APB1/APB2
Read
Rx buffer
0xAB
Shift Register
TX buffer
Write
SPI interrupts
During SPI communication , interrupts can be generated by the following
events:
• Transmit Tx buffer ready to be loaded
• Data received in Rx buffer
• Master mode fault ( in single master case you must avoid this error
happening )
• Overrun error
SPI_1
NVIC Processor
SPI_2 Core
ARM Cortex M4
SPI_3
MCU
Exercise-1
#define SPI_READY 0
#define SPI_BUSY_IN_RX 1
#define SPI_BUSY_IN_TX 2
SPI receive data API (Interrupt mode)
SPI receive data with interrupt
SPI ISR Handling Implementation
Handling SPI interrupt in the Code
Enter ISR
Len-- Len -= 2
MISO MISO
Master
Slave
gpio1 Nss
In STM32F4xx based microcontroller, the NSS pin can be
handled by 2 ways
NSS Pin state is handled by „SSI‟ bit in the CR1 register SCLK
MOSI
If SSI bit = 1 , then NSS goes HIGH
+VCC MISO
SSI=1
Slave
Nss
Software Slave Management
MOSI
If SSI bit = 1 , then NSS goes HIGH
If SSI bit = 0, then NSS goes LOW
MISO
SSI=0
Slave
Nss
Software Slave Management
MOSI
If SSI bit = 1 , then NSS goes HIGH
If SSI bit = 0, then NSS goes LOW
MISO
MISO MISO
Master
Sla
gpio1 Nss
ve
Master need not use its NSS pin is handled by SSI bit
another pin to drive the NSS of Control register by software
pin low, that saves one pin for
master.
What is Hardware slave Management?
SCLK SCLK
MOSI MOSI Slave1
Master MISO MISO
gpio1 Nss
gpio2
gpio3 SCLK
MOSI Slave2
MISO
Nss
SCLK
MOSI Slave3
MISO
Nss
Implementing Master rx API
Verify ACK
Master Sends Data Stream
Pass
Verify ACK
Master gets data stream from slave
Pass
Verify Data
Stream
Pass Blink BlueLED
Reason-1:
Non-Proper Configuration of I/O lines for Alternate
functionality
Debug Tip:
Recheck the GPIO Configuration registers to see what values
they have
Case 1: Master cannot able to produce
clock and data
Reason-2:
Configuration Overriding
Debug Tip:
Dump out all the required register contents just before you begin
the transmission
Case 2
Reason-1:
Not pulling down the slave select pin to ground before sending data to
the slave
Debug Tip:
Probe through the logic analyzer to confirm slave select line is
really low during data communication
Case 2: Master is sending data but
slave is not receiving data !
Reason-2 :
Non-Proper Configuration of I/O lines for Alternate functionality
Debug Tip:
Probe the alternate function register
Case 2: Master is sending data but
slave is not receiving data !
Reason-3 :
Non enabling the peripheral IRQ number in the NVIC
Debug Tip:
Probe the NVIC Interrupt Mask register to see whether the bit
position corresponding to the IRQ number is set or not
Case 3
Reason-1 :
Not enabling the TXE or RXNE interrupt in the SPI configuration register
Debug Tip:
Check the SPI configuration register to see TXEIE and RXNEIE bits
are really set to enable the interrupt !
Case 3: SPI interrupts are not getting triggered
Reason-2:
Non enabling the peripheral IRQ number in the NVIC
Debug Tip:
Probe the NVIC Interrupt Mask Register to see whether the bit
position corresponding to the IRQ number is set or not
Case 4
Reason-1 :
Using Long Wires in high frequency communication
Debug Tip:
use shorter wires or reduce the SPI serial frequency to 500KHz to
check things work well
SCLK SCLK
MOSI MOSI Slave1
MISO MISO
Master gpio1 Nss
gpio2
gpio3 SCLK
MOSI Slave2
MISO
Nss
SCLK
MOSI Slave3
MISO
Nss
Cross Check These Settings
PLLN
HSI
X SysClk AHB
16MHz PLLM PLLP AHB
/
HSE / VCO / APB1
8 – 26 MHz /
PLLQ
/
APB2
PLL /
USB OTG,SDIO,etc
The HSI RC oscillator which is inside the MCU has the advantage of
providing a clock source at low cost . Because there is no external
components required to use this clock. It also has a faster start-up
time than the external crystal oscillator however, the frequency is
less accurate than an external crystal oscillator.
STM32F4xx Discovery board
STM32F411RE Nucleo-64
Connection Diagram
SPI2 SPI2
SCLK(PB13) SCLK(PB13)
MISO(PB14) MISO(PB14)
MOSI(PB15) MOSI(PB15)
NSS
USER button
GND GND
STM32F4 discovery STM32F4 discovery
Master Slave
How to enable the High Speed
External Crystal Oscillator and use it
as System Clock ?
Let‟s measure the frequency of
different clock sources like
HSI,HSE,PLL by using USB logic
Analyzer !
Connection between USB Logic
Analyzer and Discovery board
Understanding Connection
Diagram
To PC
USB Logic analyzer
GND CH2 CH1 CH0
SPI2 SPI2
SCLK(PB13) SCLK(PB13)
MISO(PB14) MISO(PB14)
MOSI(PB15) MOSI(PB15)
USER button
GND GND
STM32F4 discovery STM32F4 discovery
Master Slave
PART-2
Pronounced as
“I squared C “ or “ I two C “
What is I2C ?
It is just a protocol to achieve serial data communication between
integrated circuits(ICs) which are very close to each other. (but more
serious protocol than SPI because companies have come forward to
design a specification )
ACK
Pins
+vcc
R1 R2
SCL
SDA
Addressing
+vcc
R1 R2 Pull up resistors
SCL
SDA
SCL
For proper functioning
Enable Pull up Resistor of the I2C bus , pull up
resistor value has to be
calculated according
to the I2C formula ( will
discuss later)
OD
SDA
Trouble shooting tip : When the bus is idle, both SDA and SCL are pulled to +Vdd
GND SDA & SCL Tip
Whenever you face
3.3V
problems in I2C , probe
the SDA and SCL line
after I2C initialization.
It must be held at HIGH
(3.3 V or 1.8V
depending up on IO
voltage levels of your
board)
I2C Modes
Every byte put on the SDA line must be eight bits long.
Each byte must be followed by an Acknowledge Bit
Data is transferred with the Most Significant Bit (MSB) first
START and STOP conditions
All transactions begin with a START (S) and are terminated by a STOP (P)
A HIGH to LOW transition on the SDA line while SCL is HIGH defines a START condition.
A LOW to HIGH transition on the SDA line while SCL is HIGH defines a STOP condition.
I2C Protocol: Start condition timings
Min. Setup Time For a Start Condition (tSU;STA)
Setup Time for Stop Condition (tSU;STO) is measured as the time between 70%
amplitude of the rising edge of SCL and 30% amplitude of a rising SDA signal
during a stop condition.
Points to Remember
START and STOP conditions are always generated by the master. The bus
is considered to be busy after the START condition.
The bus is considered to be free again a certain time after the STOP
condition.
When the bus is free another master(if present) can get the chance to
claim the bus.
The bus stays busy if a repeated START (Sr) is generated instead of a STOP
condition.
Most of the MCU‟s I2C peripherals support both master and slave mode.
You need not to configure the mode because when the peripheral
generates the start condition it automatically becomes the master and
when it generates the stop condition it goes back to slave mode.
I2C Protocol: Address Phase
I2C Protocol: Address Phase
I2C Protocol: ACK/NACK
I2C Protocol: ACK
The Acknowledge signal is defined
as follows:
The transmitter releases the SDA line
during the acknowledge clock pulse
so the receiver can pull the SDA line
LOW and it remains stable LOW
during the HIGH period of this clock
pulse
When SDA remains HIGH during this ninth clock pulse, this is defined as the Not
Acknowledge signal.
The master can then generate either a STOP condition to abort the transfer, or a
repeated START condition to start a new transfer.
Data validity
The data on the SDA line must be stable during the HIGH period of the clock. The
HIGH Or LOW state of the data line can only change when the clock signal on the
SCL line is LOW . One clock pulse is generated for each data bit transferred.
Master Writing data to slave
SCL
SDA
SCL
1 2 3 4 5 6 7 8
SDA
A7 A6 A5 A4 A3 A2 A1
SCL
1 2 3 4 5 6 7 8 9
SDA
A7 A6 A5 A4 A3 A2 A1
SCL
1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8
SDA
A7 A6 A5 A4 A3 A2 A1 D7 D6 D5 D4 D3 D2 D1 D0
SCL
1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9
SDA
A7 A6 A5 A4 A3 A2 A1 D7 D6 D5 D4 D3 D2 D1 D0
1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9
D7 D6 D5 D4 D3 D2 D1 D0 D7 D6 D5 D4 D3 D2 D1 D0
1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9
D7 D6 D5 D4 D3 D2 D1 D0 D7 D6 D5 D4 D3 D2 D1 D0
Master Reading
data from slave
SCL
SDA
SCL 7
1 2 3 4 5 6
SDA
A7 A6 A5 A4 A3 A2 A1
SCL 7 8
1 2 3 4 5 6
SDA
A7 A6 A5 A4 A3 A2 A1
SCL 7 8 9
1 2 3 4 5 6
SDA
A7 A6 A5 A4 A3 A2 A1
SCL 7 8 9 2 7 8
1 2 3 4 5 6 1 3 4 5 6
SDA
A7 A6 A5 A4 A3 A2 A1 D7 D6 D5 D4 D3 D2 D1 D0
SCL 7 8 9 2 7 8 9
1 2 3 4 5 6 1 3 4 5 6
SDA
A7 A6 A5 A4 A3 A2 A1 D7 D6 D5 D4 D3 D2 D1 D0
SCL 7 8 9 2 7 8 9
1 2 3 4 5 6 1 3 4 5 6
SDA
D7 D6 D5 D4 D3 D2 D1 D0 D7 D6 D5 D4 D3 D2 D1 D0
SCL 7 8 9 2 7 8 9
1 2 3 4 5 6 1 3 4 5 6
SDA
D7 D6 D5 D4 D3 D2 D1 D0 D7 D6 D5 D4 D3 D2 D1 D0
Repeated Start(Sr)
(Start again without Stop)
I2C
0x45
MCU EEPROM
(Master) (Slave)
SDA
A7 A6 A5 A4 A3 A2 A1 D7 D6 D5 D4 D3 D2 D1 D0
1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9
A7 A6 A5 A4 A3 A2 A1 D7 D6 D5 D4 D3 D2 D1 D0
With repeated start
SCL
1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9
SDA
A7 A6 A5 A4 A3 A2 A1 D7 D6 D5 D4 D3 D2 D1 D0
1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9
A7 A6 A5 A4 A3 A2 A1 D7 D6 D5 D4 D3 D2 D1 D0
I2C peripherals of your MCU
AHB1
APB1
APB2
Driver Layer
(Device header)
gpio_driver.c , .h i2c_driver.c , .h Stm3f407xx.h
spi_driver.c , .h uart_driver.c , .h
STM3F407x MCU
Driver API requirements and
user configurable items
I2C Initialization
I2C Master TX
I2C Driver
I2C Master RX
I2C Slave RX
I2C_DeviceAddress
I2Cx
Peripheral Configurable items
I2C_ACKControl For user application
I2C_FMDutyCycle
Exercise:
PLL
/ APB1 prescaler
16Mhz
Up to 100KHz in SM SCL
Up to 400Khz in FM
Example :
In SM Mode , generate a 100 kHz SCL frequency
APB1 Clock (PCLK1) = 16MHz
If DUTY = 0:
Thigh = CCR * TPCLK1
Tlow = 2 * CCR * TPCLK1
If DUTY = 1: (to reach 400 kHz)
Thigh = 9 * CCR * TPCLK1
Tlow = 16 * CCR * TPCLK1
I2C Duty Cycle
SM
In STM32f4x I2C
thigh tlow
For SM
(Tlow may be equal to Thigh )
For FM
Tlow = 2Thigh
2thigh Or
FM thigh tlow Tlow = 1.8 Thigh
1.7thigh
thigh tlow
I2C Duty Cycle
Thigh(scl) = CCR * TPCLK1
Tlow(scl) = CCR * TPCLK1
SM
thigh tlow
If DUTY = 0:
I2C Duty Cycle Thigh = CCR * TPCLK1
Tlow = 2 * CCR * TPCLK1
If DUTY = 1: (to reach 400 kHz)
Thigh = 9 * CCR * TPCLK1
Tlow = 16 * CCR * TPCLK1
2thigh
FM thigh tlow
1.7thigh
thigh tlow
Implementation
I2C_MasterSendData API
Master sending data to slave
Exercise :
I2C Master(STM) and I2C Slave(Arduino) communication .
When button on the master is pressed , master should send data to the Arduino slave
connected. The data received by the Arduino will be displayed on the Arduino serial
port.
SCL(PB6) A5
I2C1 I2C
SDA(PB9) A4
USER button
GND GND
STM32F4 discovery Arduino
Master Slave
STEP-2
Power your Arduino board and download I2C
Slave sketch to Arduino
Sketch name : 001I2CSlaveRxString.ino
Find out the GPIO pins over which I2C1 can
communicate
I2C pull up resistance , Rise time and
Bus capacitance discussion
Pull-up Resistor(Rp ) Calculation
VOL = LOW-level output voltage
Rp (min) is a function of VCC, VOL (max), and IOL:
IOL = LOW-level output current
tr = rise time of both SDA and SCL
signals
The maximum pullup resistance is a function of the maximum rise time (tr ):
Image taken from :
http://www.ti.com/lit/an/slva704/slva704.pdf
Rise (tr) and Fall (tf) Times
tr is defined as the amount of
time taken by the rising edge to
SDA or SCL reach 70% amplitude from 30%
amplitude for either SDA and
SCL
I2C spec cares about tr value and you have to respect it while calculating the pull up resistor
value.
Higher value of pull up resistors(weak pull-ups) increases tr value. ( not acceptable if tr crosses
max. limit mentioned in the spec )
Lower value of pull up resistors ( strong pull-ups) decreases tr value ( good) but they also lead
higher current consumption (bad)
Using very high value of pull up resistors may
cause issues like this where the pin may not
able to cross the VIH limit (Input Level High
Voltage)
VDD
VIH
VIL
I2C Bus Capacitance(Cb )
accidental capacitors
I2C Bus Capacitance(Cb )
Bus capacitance limits how long your i2c wiring can be and how many
devices you can connect on the bus.
SDA
1 2 3 4 5 6 7 8 9 1
SCL
SDA
The slave is not ready for more data, so it buys
time by holding the clock low.
The master will wait for the clock line to be
released before proceeding to the next frame
Implementation
I2C_MasterReceiveData API
Master Receiving data from slave
Master Receiving 1 byte from slave
Master Receiving more than 1 byte
Exercise :
I2C Master(STM) and I2C Slave(Arduino) communication .
When button on the master is pressed , master should read and display data from
Arduino Slave connected. First master has to get the length of the data from the
slave to read subsequent data from the slave.
1 . Use I2C SCL = 100KHz(Standard mode )
2. Use internal pull resistors for SDA and SCL lines
Things you need
1 .Arduino board
2. ST board
3. Some jumper wires
4. Bread board
5. 2 Pull up resistors of value 4.7K Ω( only if your pin doesn't
support internal pull up resistors )
SCL(PB6) A5
I2C1 I2C
SDA(PB9) A4
USER button
GND GND
STM32F4 discovery Arduino
Master Slave
STEP-2
Power your Arduino board and download I2C
Slave sketch to Arduino
Sketch name : 002I2CSlaveTxString.ino
Procedure to read the data from Arduino Slave
1 2
END
I2C Functional
block and
Peripheral Clock
fpclk (Peripheral Clock Frequency ) must be at least 2MHz
to achieve standard mode I2c frequencies that are up to
100khz
fpclk must be at least 4Mhz to achieve FM mode i2c
frequencies. that is above 100khz but below 400Khz
Peripheral Processor
I2C1_EV_IRQ_LINE IRQn
31
Processor
NVIC Core
I2C1_ER_IRQ_LINE
32
ARM Cortex M4
I2C Interrupting the Processor
31
32
33
34
79
80
IRQ numbers are specific to MCUs. Please check the vector table of your RM
Bus Error
This error happens when the interface detects an SDA rising or falling
edge while SCL is high, occurring in a non-valid position during a byte
transfer
Overrun Error
Happens during reception, when a new byte is received and the data
register has not been read yet and the New received byte is lost.
Under-run Error
Happens when In transmission when a new byte should be sent and
the data register has not been written yet and the same byte is sent
twice
PEC Error
Happens when there is CRC mismatch, if you have enabled the CRC
feature
Time-Out Error
Happens when master or slave stretches the clock , by holding it
low more than recommended amount of time.
BTF flag in TX and preventing underrun
I2C_MasterReceiveDataIT API
Modifying handle structure to store
place holder variables
Implementing
I2C_MasterSendDataIT API
Implementing
I2C_MasterReceiveDataIT API
Adding I2C IRQ number macros
Implementing
I2C_IRQInterruptConfig();
I2C_IRQPriorityConfig();
I2C ISR handling
ISR1 ISR2
I2C_EV_IRQHandling I2C_ER_IRQHandling
When BTF flag is set
TXE=1 RXNE=1
SR DR SR DR
EMPTY EMPTY FULL FULL
STOP generation
Receive data
Exercise :
I2C Master(Arduino) and I2C Slave(STM32) communication .
SCL(PB6) A5
I2C1 I2C
SDA(PB9) A4
USER button
GND GND
STM32F4 discovery Arduino
Master Slave
STEP-2
Power your Arduino board and download I2C
Slave sketch to Arduino
Sketch name: 003I2CMasterRxString.ino
Procedure to read the data from STM32 Slave
1 2
READ Transaction -2
READ Transaction -3
Common Problems in I2C and
Debugging Tips
GND SDA & SCL
Tip
3.3V
Whenever you face
problem in I2C , probe
the SDA and SCL line
after I2C initialization.
It must be held at HIGH
level.
Problem-1: SDA and SCL line not held HIGH
Voltage after I2C pin initialization
Reason-1:
Not activating the pullup resistors if you are using the internal
pull up resistor of an I/O line
Debug Tip:
worth checking the configuration register of an I/O line to see
whether the pullups are really activated or not, best way is to
dump the register contents.
Problem-2: ACK failure
Reason-1:
Generating the address phase with wrong slave address
Debug Tip:
verify the slave address appearing on the SDA line by using
logic analyser.
Problem-2: ACK failure
Reason-2:
Not enabling the ACKing feature in the I2C control register
Debug Tip:
Cross check the I2C Control register ACK enable field
Problem-3: Master is not producing the clock
Debug Tip 1 :
First Check whether I2C peripheral clock is enabled and set to
at least 2MHz to produce standard mode i2c serial clock
frequency
Debug Tip 2 :
Check whether GPIOs which you used for SCL and SDA
functionality are configured properly for the alternate
functionality
To PC
USB Logic analyzer
GND CH1 CH0
SCL(PB6) SCL(PB6)
I2C1 I2C1
SDA(PB9) SDA(PB9)
USER button
GND GND
STM32F4 discovery STM32F4 discovery
Master Slave
To PC
USB Logic analyzer
GND CH1 CH0
SCL(PB6)
I2C1
SDA(PB9)
USER button
GND
STM32F4 discovery
Master Slave
I2C Clock Stretching
There are situations where an I2C slave is not able to co-operate with
the clock speed given by the master and needs to slow down a little.
If slave needs time, then it takes the advantage of clock stretching , and
by holding clock at low, it momentary pauses the I2C operation.
Modifying I2C application to
send/receive more than 32 bytes
Introduction :UART vs USART
Exploring UART Interrupt
Mapping
UART USART
Universal Universal
Asynchronous Synchronous
Receiver Asynchronous
Transmitter Receiver
Transmitter
UART Peripheral supports only asynchronous mode
TX
RX
UART1
RTS
CTS
Understanding UART pins
10101110101 TX
RX
UART1
RTS
CTS
Understanding UART pins
TX TX
UART1 RX RX UART2
RTS RTS
CTS CTS
UART frame formats
9-bit word Length, 1 stop bit
Optional
Parity Next Next Data Frame
Start Data Frame Bit Start
bit
Bit0 Bit1 Bit 2 Bit 3 Bit4 Bit5 Bit6 Bit7 Bit8 Stop bit
bit
2 Stop Bit
Start
bit 5 to 9 data bits
UART Parity
Adding Parity bit is a simplest method of error detection. Parity is
simply the number of ones appearing in the binary form of a number.
55(Decimal) 0b00110111
Parity = 5
Parity
16MHz
APB 2 bus ( 84 MHz Max)
16MHz
USART1/USART6
FPCLK
HSI
16MHz
HSE
PLL
16MHz
APB1 bus ( 42 MHz Max)
USART2
16MHz USART3
FPCLK UART4
UART5
UART Transmitter
Steps to do Data Transmission
Steps to do Data Transmission
Program the M bit in USART_CR1 to define the word length
Program the number of stop bits in USART_CR2 register.
Select the desired baud rate using the USART_BRR register
Set the TE bit in USART_CR1 to enable the transmit block. .
Enable the USART by writing the UE bit in USART_CR1
Now if txe flag is set , then Write the data byte to send , in the
USART_DR register .
After writing the last data into the USART_DR register, wait until
TC=1
Line idle Frame 1 Frame 2 Frame 3
TX Line
DR F1 F2 F3
Set by hW
TC Flag
DR F1 F2 F3
Reception RXNE is set when RXNE is set when RXNE is set when
started F1 fully received F2 fully received F3 fully received
What is oversampling
How does it effect the baudrate
Connecting UART Pins to PC
Using TTL to USB Converter
Using RS232 cable with DB9 Connector
Using TTL to USB Converter
Using RS232 cable with DB9 Connector
Overview
Sample Applications
Startup &
UART Driver
CMSIS APIs
STM32F4xx Microcontroller
Understanding the
Requirements
UART initialization
UART Transmission
UART Driver APIs
UART Reception
Interrupt Handling
Exploring different UART
Peripherals and pins of the
MCU
U(S)ARTs Pin Pack 1 Pin pack 2 Pin pack 3 Bus
TX RX TX RX TX RX
USART1 PA9 PA10 PB6 PB7 APB2
APB1/APB2
RDR
RX shift register
TX shift register
TDR
Firmware Write 0xAB Data Register
USART_DR
APB1/APB2
RDR
RX shift register
TX shift register
Write
TDR
Firmware Read Data Register
USART_DR
Read
APB1/APB2
RDR
0xAB
RX shift register
TX shift register
TDR
UART Status Register
Got interrupt from UART
Interrupt is due
Interrupt is due to Interrupt is due to Interrupt is due to Setting of ERROR
setting of RXNE flag setting of TXE flag setting of TC flag flag
Tx Count--
Tx Count = 0 ?
No
Yes
Disable TXE interrupt
Enable TC interrupt
Disable TC interrupt
Yes No
Is parity used ?
RX Count--
N
Is RX count = 0 ?? Wait till another RXNE
interrupt
y
Disable RXNE interrupt
Disable Error interrupts
Call Application
callback to indicate RX
completed
Debug strings TX
USART2
LED commands RX
MCU
Commands Function
USB
CP2102 USB to
USART2
PC UART Convertor
TX PA3
GND RX
GND MCU
TX
RX PB10
USB
CP2102 USB to
USART Master Application
PC UART Convertor
With
uartprintf library
TX PB11
GND RX
GND
57600 115200
Fpclk = 16MHz OVER8=0
AHB1
APB1
USART USART
I2C1 I2C2 I2C3 USART2 USART3 UART4 UART5
2 3
APB2
USART
USART1 USART6 EXTI SYSCFG
1
USART Driver Development
Sample Applications
Driver Layer
(Device header)
gpio_driver.c , .h i2c_driver.c , .h Stm3f407xx.h
USART_driver.c , .h usart_driver.c , .h
STM3F407x MCU
Driver API requirements and
user configurable items
USART_Mode
USART_Baud
USART_NoOfStopBits
USARTx
Peripheral Configurable items
For user application
USART_WordLength
USART_ParityControl
USART_HWFlowControl
USART Initialization / peripheral
clock control
USART TX
USART RX
APIs
USART Driver
USART Interrupt config. &
handling
If you select oversampling by 8 (OVER8=1) then you can achieve max baudrate up
to FPCLK/8, but In this case the maximum receiver tolerance to clock deviation is
reduced
If you select oversampling by 16 (OVER8=0) then you can achieve max baudrate
up to FPCLK/16, In this case the maximum receiver tolerance to clock deviation is
increased.
UART Baudrate Calculation
Peripheral Clock
The baud rate for the receiver and transmitter (Rx and Tx) are both set to the same
value as programmed in the Mantissa and Fraction values of USARTDIV.
OVER8 =1 , if Oversampling by 8 is used
OVER8=0, if Oversampling by 16 is used
Fck= 16MHz Tx/Rx baud = 9600 bps OVER8=0
(USART Peripheral Clock) (Desired Baudrate) (Oversampling by 16)
Now this value we have to convert in to hex and then program the
USART_BRR register to achieve desired baud rate.
USART uses a fractional baud rate generator - with a 12-bit mantissa and 4-bit fraction
USART_BRR
DIV_Fraction = 0.1875 X 16 = 3
USARTDIV = 0x683
(Program this value into USART_BRR register to generate baudrate of 9600bps)
Now lets take another example of generating baud
rate of 115200 bps.
Div_Mantissa = 17
USARTDIV = 0x113
(Program this value into USART_BRR register to generate baudrate of 115200bps)
Overrun Error
An overrun error occurs when a character is received when RXNE
has not been reset. Data can not be transferred from the shift
register to the RDR register until the RXNE bit is cleared.
When an overrun error occurs:
The ORE bit is set.
The RDR content will not be lost. The previous data is
available when a read to USART_DR is performed
The shift register will be overwritten. After that point, any data
received during overrun is lost.
An interrupt will be generated if enabled.
Firmware Read Data Register
USART_DR
Read
APB1/APB2
RDR
RX shift register
TX shift register
TDR
USB to UART Converter cable
USB to UART Converter module
TX
RX PA2
USB
CP2102 USB to
USART2
PC UART Convertor
TX PA3
GND RX
GND MCU
Exercise
Write a program to send some message over UART from STM32
board to Arduino board. The Arduino board will display the
message (on Arduino serial monitor) sent from the ST board.
For every message STM32 board sends , arduino code will change
the case of alphabets(lower case to upper case and vice versa)
and sends message back to the stm32 board .
The stm32 board should capture the reply from the arduino
board and display using semi hosting.
Arduino Sketch
001UARTRxString.ino