stm32标准库iIC读多个数据代码
时间: 2024-12-29 09:34:43 浏览: 11
在STM32系列微控制器中,使用标准I2C库( HAL_I2C_MultipleRead() 函数)来读取多个数据通常涉及以下几个步骤:
```c
#include "stm32f1xx_hal.h"
#include "stm32f1xx_hal_i2c.h"
void read_multiple_data(I2C_HandleTypeDef *hi2c, uint8_t slave_address, uint16_t num_of_elements, uint16_t *data_array)
{
I2C_DMATransferTypeDef dmaBuffer;
uint16_t data_temp = 0;
// 配置I2C传输参数
hi2c->Instance->CR1 &= ~(I2C_CR1_DIR | I2C_CR1_STOP);
hi2c->Instance->CR1 |= I2C_CR1_START; // 发送起始信号
hi2c->Instance->DR = slave_address << 1; // 写入从地址
// 开启DMA传输
dmaBuffer.Channel = hi2c->hdmatx->Channel;
dmaBuffer.Direction = DMA_MEMORY_TO_PERIPH;
dmaBuffer.PeriphInc = DMA_PINC_DISABLE;
dmaBuffer.MemInc = DMA_MINC_ENABLE;
dmaBuffer.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
dmaBuffer.MemDataAlignment = DMA_MDATAALIGN_BYTE;
dmaBuffer.Mode = DMA_NORMAL;
dmaBuffer.Priority = DMA_PRIORITY_HIGH;
dmaBuffer.BlockSize = sizeof(uint16_t); // 每次读取的数据大小
dmaBuffer.NbTransfers = num_of_elements;
HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)data_array, (uint32_t)&hi2c->DR, num_of_elements);
while (!HAL_I2C_GetFlagStatus(hi2c, I2C_FLAG_RXNE)); // 等待接收完成
// 如果需要,将接收到的数据保存到缓冲区
for (uint16_t i = 0; i < num_of_elements; i++)
{
data_temp = (uint16_t)hi2c->Instance->DR; // 读取当前数据
data_array[i] = data_temp;
hi2c->Instance->DR = data_temp >> 8; // 发送下一个地址,继续读取
}
// 结束传输并关闭中断
hi2c->Instance->CR1 &= ~I2C_CR1_START;
HAL_DMA_Abort(&hi2c->hdmatx);
}
阅读全文