STM32 I2C.
Lately I keep coming across negative reviews of the I2C bus on STM32, saying that working with it is like performing a ritual dance and so on.
Over the past month I managed to get two I2C chips working without any dancing, just careful reading of the datasheet.
The STM32 I2C module has the following features:
In Master mode:
In Slave mode:
By default the module is in Slave mode, but it automatically switches to Master mode after generating a START condition.
The fundamental difference between Master and Slave is that the Master generates the clock signal and always initiates and terminates the data transfer. The Slave, on the other hand, responds to its own address and to the broadcast address, and responding to the broadcast address can be disabled. The Slave also generates the ACK condition, but this can be disabled too.
Such a detailed explanation is necessary because in both modes the device can act as either a transmitter or a receiver.
The structure of the I2C module is shown below.
I2C_CR1 control register:
SWRST(Software reset) — a one in this bit resets all module registers to their default state; it can be used for a reset when an error occurs.
ALERT(SMBus alert) — setting this bit enables generating the alert signal in SMBus mode.
PEC(Packet error checking) — this bit is controlled by software, but it can be cleared by hardware when PEC, START or STOP is transmitted or when PE=0. A one in this bit enables CRC transfer.
POS(Acknowledge/PEC Position (for data reception)) — this bit determines the position of ACK/PEC in a two-byte configuration in Master mode.
ACK(Acknowledge enable) — a one in this bit enables sending ACK/NACK after receiving an address or data byte.
STOP(Stop generation) — setting this bit generates a STOP signal in Master mode.
START(Start generation) — setting this bit generates a START condition in Master mode,
NOSTRETCH(Clock stretching disable (Slave mode)) — if the Slave needs time to process data, it can pause the master's transfer by pulling the SCL line low; the Master will wait and send nothing until the line is released. A zero in this bit allows SCL to be held low.
ENGC(General call enable) — if this bit is set, the module responds with an ACK to the broadcast address 0x00.
ENPEC(PEC enable) — setting this bit enables hardware CRC calculation.
ENARP(ARP enable) — setting this bit enables ARP.
SMBTYPE(SMBus type) — if this bit is zero, the module works as an SMBus device; if one, as an SMBus host.
SMBUS(SMBus mode) — if this bit is zero, the module works in I2C mode; if one, in SMBus mode.
PE(Peripheral enable) — a one in this bit enables the module.
I2C_CR2 control register:
LAST(DMA last transfer) — a one in this bit allows DMA to generate the EOT (End of Transfer) signal.
DMAEN(DMA requests enable) — a one in this bit enables DMA requests when the TxE or RxNE flags are set.
ITBUFEN(Buffer interrupt enable) — if this bit is cleared, all interrupts are enabled except the receive and transmit interrupts.
ITEVTEN(Event interrupt enable) — a one in this bit enables event interrupts.
ITERREN(Error interrupt enable) — a one in this bit enables interrupts on errors.
FREQ[5:0](Peripheral clock frequency) — the module clock frequency must be written to this bit field; it can take values from 2 to 50.
I2C_OAR1 register:
ADDMODE(Addressing mode) — this bit defines the Slave address size: zero corresponds to a 7-bit address, one to a 10-bit address.
ADD[9:8](Interface address) — the upper address bits if the address is 10-bit.
ADD[1:7](Interface address) — the device address.
ADD0(Interface address) — the lowest address bit if the address is 10-bit.
I2C_OAR2 register:
ADD2[7:1] — an alternative address that the Slave will respond to.
ENDUAL(Dual addressing mode enable) — a one in this bit allows the Slave to respond to the alternative address in 7-bit mode.
I2C_DR — the data register; to send data we write to the DR register, and to receive we read it.
I2C_SR1 status register:
SMBALERT(SMBus alert) — set when an alert occurs on the SMBus.
TIMEOUT (Timeout or Tlow error) — set if the SCL line is held low: 10mS for a master, 25mS for a slave.
PECERR (PEC Error in reception) — set on a PEC error during reception.
OVR (Overrun/Underrun) — set on data overrun.
AF (Acknowledge failure) — set when a NACK is received. Write 0 to clear it.
ARLO (Arbitration lost (master mode) ) — set when arbitration is lost. Write 0 to clear it.
BERR (Bus error) — bus error. Set when a START or STOP signal occurs at the wrong moment.
TxE (Data register empty (transmitters)) — set when the DR register becomes empty, or more precisely when its data has been moved to the shift register.
RxNE (Data register not empty (receivers)) — set when a data byte (but not an address) is received.
STOPF(Stop detection (slave mode)) — in slave mode, set when a STOP signal is detected after an ACK. To clear it, read SR1 and then write to CR1.
ADD10 (10-bit header sent (Master mode)) — set when the first byte of a 10-bit address has been sent.
BTF (Byte transfer finished) — this flag is set when a byte has been received/transmitted; it works only when NOSTRETCH is zero.
ADDR(Address sent (master mode)/matched (slave mode)) — in master mode it is set after the address has been sent; in slave mode it is set when the address matches. To clear it, read SR1 and then SR2.
SB(Start bit (Master mode)) — set when a START signal occurs. To clear the flag, read SR1 and write data to the DR register.
I2C_SR2 status register:
PEC[7:0](Packet error checking register) — the frame checksum is written to this bit field.
DUALF(Dual flag (Slave mode)) — a zero in this bit means that the address received by the Slave matches OAR1, otherwise OAR2.
SMBHOST(SMBus host header (Slave mode)) — set when an SMBus Host header is received.
SMBDEFAULT(SMBus device default address (Slave mode)) — set if the default address
for an SMBus device is received.
GENCALL(General call address (Slave mode)) — set if a broadcast address is received in slave mode.
TRA(Transmitter/receiver) — a one in this bit means the module is working as a transmitter, otherwise as a receiver.
BUSY(Bus busy) — the busy flag.
MSL(Master/slave) — a one in this bit means the module is working in Master mode, otherwise in Slave mode.
I2C_CCR clock control register:
F/S(I2C master mode selection) — when this bit is set, the module works in FAST mode, otherwise in STANDARD mode.
DUTY (Fm mode duty cycle) — this bit sets the duty cycle of the SCL signal in FAST mode. If it is zero, tlow/thigh = 2, otherwise tlow/thigh = 16/9.
CCR[11:0](Clock control register in Fm/Sm mode (Master mode)) — in Master mode, sets the clock frequency of the SCL line.
Sm mode or SMBus:
Thigh = CCR * TPCLK1
Tlow = CCR * TPCLK1
Fm mode:
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
Next, substitute the Thigh and Tlow values into the following formula
Tscl = Thigh + Tlow
where Tscl is 10uS for SM and 2.5 uS for FM.
For SM mode we get the following:
CCR * TPCLK1 + CCR * TPCLK1 = 10 000ns
CCR = 10 000/(2* TPCLK1)
I2C_TRISE register:
TRISE[5:0] — defines the rise time. It is calculated using the formula (Tr max/TPCLK1)+1,
where Tr max is 1000nS for SM and 300nS for FM,
and TPCLK1 is the period calculated as 1/F(APB1).
I2C_FLTR filter control register:
ANOFF(Analog noise filter OFF) — a zero in this bit enables the analog filter.
DNF[3:0](Digital noise filter) — a bit field for configuring the digital filter. See the documentation for details.
Module initialization from a working project.
Over the past month I managed to get two I2C chips working without any dancing, just careful reading of the datasheet.
The STM32 I2C module has the following features:
- it can operate in two modes, Fm (fast mode) and Sm (standard mode); the first works at frequencies up to 400KHz, the second up to 100KHz
- a 1-byte buffer with DMA support
- supports hardware checksum calculation
- SMBus (System Management Bus) and PMBus (Power Management Bus) can be implemented on top of it
- two interrupt vectors, generated on successful transfer and when an error occurs
- a noise filter
- can operate in Master or Slave mode
In Master mode:
- generates the clock signal
- generates START and STOP
In Slave mode:
- you can program a primary and an alternative address it will respond to
- detects STOP
By default the module is in Slave mode, but it automatically switches to Master mode after generating a START condition.
The fundamental difference between Master and Slave is that the Master generates the clock signal and always initiates and terminates the data transfer. The Slave, on the other hand, responds to its own address and to the broadcast address, and responding to the broadcast address can be disabled. The Slave also generates the ACK condition, but this can be disabled too.
Such a detailed explanation is necessary because in both modes the device can act as either a transmitter or a receiver.
- Slave transmitter
- Slave receiver
- Master transmitter
- Master receiver
The structure of the I2C module is shown below.
I2C_CR1 control register:
SWRST(Software reset) — a one in this bit resets all module registers to their default state; it can be used for a reset when an error occurs.
ALERT(SMBus alert) — setting this bit enables generating the alert signal in SMBus mode.
PEC(Packet error checking) — this bit is controlled by software, but it can be cleared by hardware when PEC, START or STOP is transmitted or when PE=0. A one in this bit enables CRC transfer.
POS(Acknowledge/PEC Position (for data reception)) — this bit determines the position of ACK/PEC in a two-byte configuration in Master mode.
ACK(Acknowledge enable) — a one in this bit enables sending ACK/NACK after receiving an address or data byte.
STOP(Stop generation) — setting this bit generates a STOP signal in Master mode.
START(Start generation) — setting this bit generates a START condition in Master mode,
NOSTRETCH(Clock stretching disable (Slave mode)) — if the Slave needs time to process data, it can pause the master's transfer by pulling the SCL line low; the Master will wait and send nothing until the line is released. A zero in this bit allows SCL to be held low.
ENGC(General call enable) — if this bit is set, the module responds with an ACK to the broadcast address 0x00.
ENPEC(PEC enable) — setting this bit enables hardware CRC calculation.
ENARP(ARP enable) — setting this bit enables ARP.
SMBTYPE(SMBus type) — if this bit is zero, the module works as an SMBus device; if one, as an SMBus host.
SMBUS(SMBus mode) — if this bit is zero, the module works in I2C mode; if one, in SMBus mode.
PE(Peripheral enable) — a one in this bit enables the module.
I2C_CR2 control register:
LAST(DMA last transfer) — a one in this bit allows DMA to generate the EOT (End of Transfer) signal.
DMAEN(DMA requests enable) — a one in this bit enables DMA requests when the TxE or RxNE flags are set.
ITBUFEN(Buffer interrupt enable) — if this bit is cleared, all interrupts are enabled except the receive and transmit interrupts.
ITEVTEN(Event interrupt enable) — a one in this bit enables event interrupts.
ITERREN(Error interrupt enable) — a one in this bit enables interrupts on errors.
FREQ[5:0](Peripheral clock frequency) — the module clock frequency must be written to this bit field; it can take values from 2 to 50.
I2C_OAR1 register:
ADDMODE(Addressing mode) — this bit defines the Slave address size: zero corresponds to a 7-bit address, one to a 10-bit address.
ADD[9:8](Interface address) — the upper address bits if the address is 10-bit.
ADD[1:7](Interface address) — the device address.
ADD0(Interface address) — the lowest address bit if the address is 10-bit.
I2C_OAR2 register:
ADD2[7:1] — an alternative address that the Slave will respond to.
ENDUAL(Dual addressing mode enable) — a one in this bit allows the Slave to respond to the alternative address in 7-bit mode.
I2C_DR — the data register; to send data we write to the DR register, and to receive we read it.
I2C_SR1 status register:
SMBALERT(SMBus alert) — set when an alert occurs on the SMBus.
TIMEOUT (Timeout or Tlow error) — set if the SCL line is held low: 10mS for a master, 25mS for a slave.
PECERR (PEC Error in reception) — set on a PEC error during reception.
OVR (Overrun/Underrun) — set on data overrun.
AF (Acknowledge failure) — set when a NACK is received. Write 0 to clear it.
ARLO (Arbitration lost (master mode) ) — set when arbitration is lost. Write 0 to clear it.
BERR (Bus error) — bus error. Set when a START or STOP signal occurs at the wrong moment.
TxE (Data register empty (transmitters)) — set when the DR register becomes empty, or more precisely when its data has been moved to the shift register.
RxNE (Data register not empty (receivers)) — set when a data byte (but not an address) is received.
STOPF(Stop detection (slave mode)) — in slave mode, set when a STOP signal is detected after an ACK. To clear it, read SR1 and then write to CR1.
ADD10 (10-bit header sent (Master mode)) — set when the first byte of a 10-bit address has been sent.
BTF (Byte transfer finished) — this flag is set when a byte has been received/transmitted; it works only when NOSTRETCH is zero.
ADDR(Address sent (master mode)/matched (slave mode)) — in master mode it is set after the address has been sent; in slave mode it is set when the address matches. To clear it, read SR1 and then SR2.
SB(Start bit (Master mode)) — set when a START signal occurs. To clear the flag, read SR1 and write data to the DR register.
I2C_SR2 status register:
PEC[7:0](Packet error checking register) — the frame checksum is written to this bit field.
DUALF(Dual flag (Slave mode)) — a zero in this bit means that the address received by the Slave matches OAR1, otherwise OAR2.
SMBHOST(SMBus host header (Slave mode)) — set when an SMBus Host header is received.
SMBDEFAULT(SMBus device default address (Slave mode)) — set if the default address
for an SMBus device is received.
GENCALL(General call address (Slave mode)) — set if a broadcast address is received in slave mode.
TRA(Transmitter/receiver) — a one in this bit means the module is working as a transmitter, otherwise as a receiver.
BUSY(Bus busy) — the busy flag.
MSL(Master/slave) — a one in this bit means the module is working in Master mode, otherwise in Slave mode.
I2C_CCR clock control register:
F/S(I2C master mode selection) — when this bit is set, the module works in FAST mode, otherwise in STANDARD mode.
DUTY (Fm mode duty cycle) — this bit sets the duty cycle of the SCL signal in FAST mode. If it is zero, tlow/thigh = 2, otherwise tlow/thigh = 16/9.
CCR[11:0](Clock control register in Fm/Sm mode (Master mode)) — in Master mode, sets the clock frequency of the SCL line.
Sm mode or SMBus:
Thigh = CCR * TPCLK1
Tlow = CCR * TPCLK1
Fm mode:
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
Next, substitute the Thigh and Tlow values into the following formula
Tscl = Thigh + Tlow
where Tscl is 10uS for SM and 2.5 uS for FM.
For SM mode we get the following:
CCR * TPCLK1 + CCR * TPCLK1 = 10 000ns
CCR = 10 000/(2* TPCLK1)
I2C_TRISE register:
TRISE[5:0] — defines the rise time. It is calculated using the formula (Tr max/TPCLK1)+1,
where Tr max is 1000nS for SM and 300nS for FM,
and TPCLK1 is the period calculated as 1/F(APB1).
I2C_FLTR filter control register:
ANOFF(Analog noise filter OFF) — a zero in this bit enables the analog filter.
DNF[3:0](Digital noise filter) — a bit field for configuring the digital filter. See the documentation for details.
Module initialization from a working project.
void I2C2_Init(void)
{
/*
SDL -> PB10
SDA -> PB11
RST -> PE15
*/
//enable clocking for the ports and the I2C module
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOBEN | RCC_AHB1ENR_GPIOEEN;
RCC->APB1ENR |= RCC_APB1ENR_I2C2EN;
//alternate function, open-drain output, 2 MHz
GPIOB->AFR[1] |= (0x04<<2*4);
GPIOB->AFR[1] |= (0x04<<3*4);
GPIOB->MODER |= GPIO_MODER_MODER10_1;
GPIOB->OTYPER |= GPIO_OTYPER_OT_10;
GPIOB->OSPEEDR &= ~GPIO_OSPEEDER_OSPEEDR10;
GPIOB->MODER |= GPIO_MODER_MODER11_1;
GPIOB->OTYPER |= GPIO_OTYPER_OT_11;
GPIOB->OSPEEDR &= ~GPIO_OSPEEDER_OSPEEDR11;
//PE15 push-pull output 50MHz
GPIOE->MODER |= GPIO_MODER_MODER15_0;
GPIOE->OSPEEDR |= GPIO_OSPEEDER_OSPEEDR15;
AU_RST_HIGH
//configure the module in I2C mode
I2C2->CR1 &= ~2C_CR1_SMBUS;
//specify the module clock frequency
I2C2->CR2 &= ~I2C_CR2_FREQ;
I2C2->CR2 |= 42; // Fclk1=168/4=42MHz
//configure I2C, standard mode, 100 KHz, duty cycle 1/2
I2C2->CCR &= ~(I2C_CCR_FS | I2C_CCR_DUTY);
//set the SCL frequency using the formula 10 000nS/(2* TPCLK1)
I2C2->CCR |= 208; //10 000ns/48ns = 208
//Standart_Mode = 1000nS, Fast_Mode = 300nS, 1/42MHz = 24nS
I2C2->TRISE = 42; //(1000nS/24nS)+1
//enable the module
I2C2->CR1 |= I2C_CR1_PE;
}
void I2C_Write(uint8_t reg_addr, uint8_t data)
{
//start
I2C2->CR1 |= I2C_CR1_START;
while(!(I2C2->SR1 & I2C_SR1_SB)){};
(void) I2C2->SR1;
//send the device address
I2C2->DR = I2C_ADDRESS(ADDR,I2C_MODE_WRITE);
while(!(I2C2->SR1 & I2C_SR1_ADDR)){};
(void) I2C2->SR1;
(void) I2C2->SR2;
//send the register address
I2C2->DR = reg_addr;
while(!(I2C2->SR1 & I2C_SR1_TXE)){};
//write data
I2C2->DR = data;
while(!(I2C2->SR1 & I2C_SR1_BTF)){};
I2C2->CR1 |= I2C_CR1_STOP;
}
uint8_t I2C_Read(uint8_t reg_addr)
{
uint8_t data;
//start
I2C2->CR1 |= I2C_CR1_START;
while(!(I2C2->SR1 & I2C_SR1_SB)){};
(void) I2C2->SR1;
//send the device address
I2C2->DR = I2C_ADDRESS(ADR,I2C_MODE_WRITE);
while(!(I2C2->SR1 & I2C_SR1_ADDR)){};
(void) I2C2->SR1;
(void) I2C2->SR2;
//send the register address
I2C2->DR = reg_addr;
while(!(I2C2->SR1 & I2C_SR1_TXE)){};
I2C2->CR1 |= I2C_CR1_STOP;
//restart!!!
I2C2->CR1 |= I2C_CR1_START;
while(!(I2C2->SR1 & I2C_SR1_SB)){};
(void) I2C2->SR1;
//send the device address, but now for reading
I2C2->DR = I2C_ADDRESS(ADR,I2C_MODE_READ);
while(!(I2C2->SR1 & I2C_SR1_ADDR)){};
(void) I2C2->SR1;
(void) I2C2->SR2;
//read
I2C2->CR1 &= ~I2C_CR1_ACK;
while(!(I2C2->SR1 & I2C_SR1_RXNE)){};
data = I2C2->DR;
I2C2->CR1 |= I2C_CR1_STOP;
return data;
}
