STM32F103硬件IIC从机
时间: 2023-12-12 13:03:34 浏览: 146
IIC_IIC_STM32F103_out_stm3224c16_
使用STM32F103硬件IIC作为从机的基本流程如下:
1. 配置I2C GPIO引脚为开漏输出模式。
2. 配置I2C时钟频率和I2C模式(标准模式、快速模式或高速模式)。
3. 配置I2C从设备地址和读写模式。
4. 配置I2C中断或DMA接收数据。
5. 开启I2C接收中断或DMA。
以下是使用STM32F103硬件IIC从机的示例代码:
```c
#include "stm32f10x.h"
#define I2C_SLAVE_ADDRESS 0x50 // 从设备地址
#define I2C_SPEED 100000 // I2C时钟频率
void I2C1_GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); // 使能GPIOB时钟
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7; // 配置PB6和PB7为开漏输出模式
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
}
void I2C1_Configuration(void)
{
I2C_InitTypeDef I2C_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1, ENABLE); // 使能I2C1时钟
I2C_InitStructure.I2C_Mode = I2C_Mode_I2C;
I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2;
I2C_InitStructure.I2C_OwnAddress1 = I2C_SLAVE_ADDRESS << 1;
I2C_InitStructure.I2C_Ack = I2C_Ack_Enable;
I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
I2C_InitStructure.I2C_ClockSpeed = I2C_SPEED;
I2C_Init(I2C1, &I2C_InitStructure);
I2C_Cmd(I2C1, ENABLE);
}
void I2C1_NVIC_Configuration(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = I2C1_EV_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void I2C1_DMA_Configuration(void)
{
DMA_InitTypeDef DMA_InitStructure;
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE); // 使能DMA1时钟
DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t) & (I2C1->DR);
DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)I2C_Buffer;
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
DMA_InitStructure.DMA_BufferSize = I2C_BUFFER_SIZE;
DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;
DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;
DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;
DMA_InitStructure.DMA_Priority = DMA_Priority_High;
DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
DMA_Init(DMA1_Channel7, &DMA_InitStructure);
I2C_DMACmd(I2C1, ENABLE);
}
void I2C1_EV_IRQHandler(void)
{
if (I2C_GetITStatus(I2C1, I2C_IT_RXNE) == SET) {
DMA_Cmd(DMA1_Channel7, DISABLE); // 关闭DMA1通道7
I2C_Buffer[I2C_BufferIndex++] = I2C_ReceiveData(I2C1);
if (I2C_BufferIndex >= I2C_BUFFER_SIZE) {
I2C_BufferIndex = 0;
}
DMA_SetCurrDataCounter(DMA1_Channel7, I2C_BUFFER_SIZE);
DMA_Cmd(DMA1_Channel7, ENABLE); // 重新开启DMA1通道7
}
}
int main(void)
{
I2C1_GPIO_Config();
I2C1_Configuration();
I2C1_NVIC_Configuration();
I2C1_DMA_Configuration();
while (1);
}
```
注意:以上代码只是示例,实际使用时需要根据具体情况进行修改。
阅读全文