FM24C256驱动hal库代码
时间: 2023-10-28 13:14:21 浏览: 181
以下基于HAL库的FM24C256驱动代码:
```c
#include "stm32f4xx_hal.h"
#define FM24C256_ADDRESS 0xA0
I2C_HandleTypeDef hi2c1;
void FM24C256_Init(void)
{
hi2c1.Instance = I2C1;
hi2c1.Init.ClockSpeed = 100000;
hi2c1.Init.DutyCycle = I2C_DUTYCYCLE_2;
hi2c1.Init.OwnAddress1 = 0;
hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
hi2c1.Init.OwnAddress2 = 0;
hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
HAL_I2C_Init(&hi2c1);
}
uint8_t FM24C256_Write(uint16_t address, uint8_t *data, uint16_t size)
{
uint8_t ret;
uint8_t *txBuffer = malloc(size+2);
txBuffer[0] = (uint8_t)(address >> 8);
txBuffer[1] = (uint8_t)(address & 0xFF);
memcpy(&txBuffer[2], data, size);
ret = HAL_I2C_Master_Transmit(&hi2c1, FM24C256_ADDRESS<<1, txBuffer, size+2, HAL_MAX_DELAY);
free(txBuffer);
return ret;
}
uint8_t FM24C256_Read(uint16_t address, uint8_t *data, uint16_t size)
{
uint8_t ret;
uint8_t txBuffer[2];
txBuffer[0] = (uint8_t)(address >> 8);
txBuffer[1] = (uint8_t)(address & 0xFF);
ret = HAL_I2C_Master_Transmit(&hi2c1, FM24C256_ADDRESS<<1, txBuffer, 2, HAL_MAX_DELAY);
if (ret != HAL_OK) return ret;
ret = HAL_I2C_Master_Receive(&hi2c1, FM24C256_ADDRESS<<1, data, size, HAL_MAX_DELAY);
return ret;
}
```
需要注意的是,这里使用的是STM32F4系列的I2C1模块,如果你的芯片型号不同,需要根据芯片型号进行相应的修改。此外,本代码中的FM24C256芯片地址为0xA0,如果你的芯片地址不同,需要进行修改。
阅读全文