【STM32】STM32CubeIDE HAL库硬件IIC驱动OLED例程
板子G474RE。
IIC协议就不说了。模拟IIC也习惯了,看看官方的硬件IIC。
Master features 主模式特性
I2C Speed Mode: IIC模式设置 快速模式和标准模式。实际上也就是速率的选择。
I2C Clock Speed:I2C传输速率,默认为100KHz
Slave features 从模式特性
Clock No Stretch Mode: 时钟没有扩展模式
Primary Address Length selection: 从设备地址长度 设置从设备的地址是7bit还是10bit 大部分为7bit
Primary slave address: 从设备初始地址
Dual Address Acknowledged: 双地址确认
暂时了解1,2,3,4即可。默认配置。
在xxx_hal_i2c.h文件中
/******* Blocking mode: Polling */ HAL_StatusTypeDef HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_Slave_Receive(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_Mem_Write(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_IsDeviceReady(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout);
重点:
HAL_I2C_Mem_Write(&hi2c3,OLED_ADDRESS,0x00,I2C_MEMADD_SIZE_8BIT,pData,1,100);
*hi2c: I2C设备号指针,设置使用的是那个IIC
DevAddress: 从设备地址 从设备的IIC地址 例E2PROM的设备地址 0xA0
MemAddress: 从机寄存器地址 ,每写入一个字节数据,地址就会自动+1
MemAddSize: 从机寄存器地址字节长度 8位或16位
写入数据的字节类型 8位还是16位 I2C_MEMADD_SIZE_8BIT I2C_MEMADD_SIZE_16BIT
*pData:所要传输的数据
Size:参数为传输数据的大小
Timeout:参数为操作超时时间
如何修改:
修改两个函数:
void Write_IIC_Command(unsigned char I2C_Command)//写命令
void Write_IIC_Data(unsigned char IIC_Data)//写数据
void Write_IIC_Command(unsigned char I2C_Command)//写命令
{
uint8_t *pData;
pData = &I2C_Command;
HAL_I2C_Mem_Write(&hi2c3,OLED_ADDRESS,0x00,I2C_MEMADD_SIZE_8BIT,pData,1,100);
}
void Write_IIC_Data(unsigned char IIC_Data)//写数据
{
uint8_t *pData;
pData = &IIC_Data;
HAL_I2C_Mem_Write(&hi2c3,OLED_ADDRESS,0x40,I2C_MEMADD_SIZE_8BIT,pData,1,100);
}
/* * 第1个参数为I2C操作句柄 第2个参数为从机设备地址 第3个参数为从机寄存器地址 第4个参数为从机寄存器地址长度 第5个参数为发送的数据 第6个参数为传输数据的大小 第7个参数为操作超时时间 */
注意:这个不太常用,可以了解。简单认为HAL_I2C_Mem_Write一次发送=两次 HAL_I2C_Master_Transmit发送(一次设备地址,一次数据地址)。
HAL_StatusTypeDef HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout);
如果只往某个外设中写数据,则用Master_Transmit。 如果是外设里面还有子地址,例如我们的E2PROM,有设备地址,还有每个数据的寄存器存储地址, 则用Mem_Write。 Mem_Write是2个地址,Master_Transmit只有从机地址。
工程代码:
链接:https://pan.baidu.com/s/1gw4TVz6t0tJwapB6iEmbJw 提取码:bqdk
