stm32f407 i2c2初始化及数据发送代码
时间: 2024-05-09 07:14:57 浏览: 95
基于stm32F407的i2c双机通讯
以下是STM32F407的I2C2初始化和数据发送代码:
```
#include "stm32f4xx.h"
void I2C2_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
I2C_InitTypeDef I2C_InitStructure;
/* Enable GPIOB clock */
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);
/* Enable I2C2 clock */
RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C2, ENABLE);
/* Configure I2C2 pins: SCL and SDA */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10 | GPIO_Pin_11;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_OD;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOB, &GPIO_InitStructure);
/* Connect pins to I2C2 */
GPIO_PinAFConfig(GPIOB, GPIO_PinSource10, GPIO_AF_I2C2);
GPIO_PinAFConfig(GPIOB, GPIO_PinSource11, GPIO_AF_I2C2);
/* Configure I2C2 */
I2C_InitStructure.I2C_Mode = I2C_Mode_I2C;
I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2;
I2C_InitStructure.I2C_OwnAddress1 = 0x00;
I2C_InitStructure.I2C_Ack = I2C_Ack_Enable;
I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
I2C_InitStructure.I2C_ClockSpeed = 100000; // 100 kHz
/* Initialize I2C2 */
I2C_Init(I2C2, &I2C_InitStructure);
/* Enable I2C2 */
I2C_Cmd(I2C2, ENABLE);
}
void I2C2_SendData(uint8_t addr, uint8_t *data, uint8_t len)
{
uint8_t i;
/* Wait for I2C2 to be ready */
while (I2C_GetFlagStatus(I2C2, I2C_FLAG_BUSY));
/* Generate start condition */
I2C_GenerateSTART(I2C2, ENABLE);
/* Wait for start condition to be generated */
while (!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_MODE_SELECT));
/* Send address of slave device */
I2C_Send7bitAddress(I2C2, addr, I2C_Direction_Transmitter);
/* Wait for address to be sent */
while (!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED));
/* Send data */
for (i = 0; i < len; i++)
{
/* Send data */
I2C_SendData(I2C2, data[i]);
/* Wait for data to be sent */
while (!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_BYTE_TRANSMITTED));
}
/* Generate stop condition */
I2C_GenerateSTOP(I2C2, ENABLE);
}
```
这段代码中,`I2C2_Init()`函数用于初始化I2C2总线,`I2C2_SendData()`函数用于向I2C2设备发送数据。需要注意的是,在使用`I2C2_SendData()`函数发送数据前,需要先调用`I2C2_Init()`函数对I2C2总线进行初始化。此外,还需要根据实际情况修改代码中的设备地址和数据长度等参数。
阅读全文