AN2824 I2C master programming examples (DMA, interrupts, polling)
Doc ID 15021 Rev 4 5/16
1 I2C master programming examples (DMA, interrupts,
polling)
1.1 Overview
The purpose of this section is to describe the firmware examples of I2C master transmitting
and receiving data using polling, DMA and interrupts, provided with this application note.
Flowcharts of Master Transmitter/Receiver in all modes (DMA, Polling, Interrupts) are also
provided.
You can modify these examples to adapt them to your application requirements.
1.2 Description of the examples
1.2.1 Polling
Master receiver
The master sends the START condition on the bus by setting START bit. The interface waits
for the SB flag to be set and then cleared by writing the slave address in the DR register.
The interface waits for the ADDR flag to be set then cleared by reading the SR1 and SR2
status register. After that, the master waits for the RXNE flag to be set in order to read data
from the data register (EV7).
The EV7 software sequence must complete before the end of the current byte transfer. In
case EV7 software sequence can not be managed before the current byte end of transfer, it
is recommended to use BTF instead.
In order to close the communication, the software must guarantee the ACK bit is cleared in
time in order to receive the last byte with a NACK. For this purpose, method 2 described in
the device reference manuals is used: with this method, DataN_2 is not read, so that after
DataN_1, the communication is stretched (both RxNE and BTF are set). Then:
● Clear the ACK bit before reading DataN-2 in DR to ensure it is cleared before the
DataN Acknowledge pulse.
● After this, just after reading DataN_2, set the STOP/ START bit and read DataN_1.
● After RxNE is set, read DataN.
This is illustrated below:
When 3 bytes remain to be read:
– RxNE = 1 => Nothing (DataN-2 not read).
– DataN-1 received
– BTF = 1 because both shift and data registers are full: DataN-2 in DR and DataN-1 in
the shift register => SCL tied low: no other data will be received on the bus.
– Clear ACK bit
– Read DataN-2 in DR => This starts DataN reception in the shift register.
– DataN received (with a NACK)
– Program START/STOP
– Read DataN-1
评论0