stm32 IIC从机代码
时间: 2023-09-09 08:12:10 浏览: 77
以下是一个简单的STM32 IIC从机代码示例:
```c
#include "stm32f10x.h"
#define SLAVE_ADDRESS 0x50
void I2C1_EV_IRQHandler(void)
{
if (I2C1->SR1 & I2C_SR1_ADDR) // Address matched
{
I2C1->SR1 &= ~I2C_SR1_ADDR; // Clear the ADDR flag
uint8_t dummy_read = I2C1->SR2; // Read SR2 to clear the ADDR flag
// Do something with the received data
uint8_t data = I2C1->DR;
// ...
I2C1->CR1 |= I2C_CR1_ACK; // Send ACK
}
if (I2C1->SR1 & I2C_SR1_RXNE) // Data received
{
// Do something with the received data
uint8_t data = I2C1->DR;
// ...
}
}
int main(void)
{
// I2C1 GPIO configuration
RCC->APB2ENR |= RCC_APB2ENR_IOPBEN; // Enable GPIOB clock
GPIOB->CRL &= ~(GPIO_CRL_MODE6 | GPIO_CRL_CNF6 | GPIO_CRL_MODE7 | GPIO_CRL_CNF7); // PB6 (SCL) and PB7 (SDA) as input floating
GPIOB->CRL |= GPIO_CRL_CNF6_1 | GPIO_CRL_CNF7_1; // PB6 and PB7 as alternate function open-drain
GPIOB->ODR |= GPIO_ODR_ODR6 | GPIO_ODR_ODR7; // Set PB6 and PB7 high
// I2C1 configuration
RCC->APB1ENR |= RCC_APB1ENR_I2C1EN; // Enable I2C1 clock
I2C1->CR1 &= ~I2C_CR1_PE; // Disable I2C1
I2C1->CR2 |= 36; // Set APB1 clock frequency (36 MHz)
I2C1->CCR |= 180; // Set I2C clock speed (100 kHz)
I2C1->TRISE |= 37; // Set maximum rise time (1000 ns)
I2C1->OAR1 |= SLAVE_ADDRESS << 1; // Set I2C1 own address
I2C1->CR1 |= I2C_CR1_PE; // Enable I2C1
// I2C1 event interrupt configuration
NVIC_EnableIRQ(I2C1_EV_IRQn);
I2C1->CR2 |= I2C_CR2_ITEVTEN; // Enable I2C1 event interrupt
while (1)
{
// Do something
}
return 0;
}
```
注:
- 此示例仅演示了I2C从机的基本实现,未实现I2C主机发送数据的响应。
- I2C1从机地址为0x50,可以根据需要修改。
- 在中断处理程序中,当ADDR标志位被置位时,需要读取SR2寄存器以清除ADDR标志位。在STM32F1系列中,SR2寄存器可以使用任何读取寄存器的方法来读取,此示例中使用了一个`dummy_read`变量来读取SR2寄存器。
- 在中断处理程序中,当RXNE标志位被置位时,表示接收到了数据,需要读取DR寄存器以清除RXNE标志位。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)