[STM32F439 EVM] I2C 테스트
[STM32F439 EVM] 에는 PB8(SCL), PB9(SDA)에 I2C가 할당되어 있다.
STM32F439 I2C 초기화 코드
I2C_HandleTypeDef I2cHandle;
#define I2Cx I2C1
#define I2Cx_CLK_ENABLE() __I2C1_CLK_ENABLE()
#define I2Cx_SDA_GPIO_CLK_ENABLE() __GPIOB_CLK_ENABLE()
#define I2Cx_SCL_GPIO_CLK_ENABLE() __GPIOB_CLK_ENABLE()
#define I2Cx_FORCE_RESET() __I2C1_FORCE_RESET()
#define I2Cx_RELEASE_RESET() __I2C1_RELEASE_RESET()
/* Definition for I2Cx Pins */
#define I2Cx_SCL_PIN GPIO_PIN_8
#define I2Cx_SCL_GPIO_PORT GPIOB
#define I2Cx_SCL_AF GPIO_AF4_I2C1
#define I2Cx_SDA_PIN GPIO_PIN_7
#define I2Cx_SDA_GPIO_PORT GPIOB
#define I2Cx_SDA_AF GPIO_AF4_I2C1
void I2CMaster_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
/*##-1- Enable peripherals and GPIO Clocks #################################*/
/* Enable GPIO TX/RX clock */
I2Cx_SCL_GPIO_CLK_ENABLE();
I2Cx_SDA_GPIO_CLK_ENABLE();
/* Enable I2C1 clock */
I2Cx_CLK_ENABLE();
/*##-2- Configure peripheral GPIO ##########################################*/
/* I2C TX GPIO pin configuration */
GPIO_InitStruct.Pin = I2Cx_SCL_PIN;
GPIO_InitStruct.Mode = GPIO_MODE_AF_OD;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FAST;
GPIO_InitStruct.Alternate = I2Cx_SCL_AF;
HAL_GPIO_Init(I2Cx_SCL_GPIO_PORT, &GPIO_InitStruct);
/* I2C RX GPIO pin configuration */
GPIO_InitStruct.Pin = I2Cx_SDA_PIN;
GPIO_InitStruct.Alternate = I2Cx_SDA_AF;
HAL_GPIO_Init(I2Cx_SDA_GPIO_PORT, &GPIO_InitStruct);
I2cHandle.Instance = I2Cx;
I2cHandle.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
I2cHandle.Init.ClockSpeed = 100000;
I2cHandle.Init.DualAddressMode = I2C_DUALADDRESS_DISABLED;
I2cHandle.Init.DutyCycle = I2C_DUTYCYCLE_2;
I2cHandle.Init.GeneralCallMode = I2C_GENERALCALL_ENABLED;
I2cHandle.Init.NoStretchMode = I2C_NOSTRETCH_DISABLED;
I2cHandle.Init.OwnAddress1 = 0xFE;//I2C_ADDRESS<<1;
I2cHandle.Init.OwnAddress2 = 0xFE;
HAL_I2C_Init(&I2cHandle);
}
STM32F439 I2C Read/Write 함수
HAL_I2C_Master_Transmit(), HAL_I2C_Master_Receive() 함수를 사용하면 쉽게 I2C제어가 가능하다.
unsigned char read8(unsigned char addr, unsigned char data)
{
unsigned char result;
unsigned char tx_buf[2];
unsigned char rx_buf[4];
tx_buf[0] = data;
//gTimerTick6 = 0;
while(HAL_I2C_Master_Transmit(&I2cHandle, (uint16_t)addr, (uint8_t*)tx_buf, 1, 10000)!= HAL_OK)
{
//if(gTimerTick6>200)break;
}
//gTimerTick6 = 0;
while(HAL_I2C_Master_Receive(&I2cHandle, (uint16_t)addr, (uint8_t *)rx_buf, 1, 10000) != HAL_OK)
{
//if(gTimerTick6>200)break;
}
result = rx_buf[0];
return result;
}
void write8(unsigned char addr, unsigned char reg, unsigned char data)
{
unsigned char result;
unsigned char tx_buf[2];
unsigned char rx_buf[4];
tx_buf[0] = reg;
tx_buf[1] = data;
//gTimerTick6 = 0;
while(HAL_I2C_Master_Transmit(&I2cHandle, (uint16_t)addr, (uint8_t*)tx_buf, 2, 10000)!= HAL_OK)
{
//if(gTimerTick6>200)break;
}
}