#include "main.h"
I2C_HandleTypeDef hi2c1;
#define SLAVE_ADDR 0x3C << 1 // HAL expects 8-bit address (shifted left)
uint8_t txData[2];
uint8_t rxData[1];
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_I2C1_Init(void);
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_I2C1_Init();
while (1)
{
/*** Write data to a register ***/
txData[0] = 0x00; // Register address
txData[1] = 0xAB; // Data to write
if (HAL_I2C_Master_Transmit(&hi2c1, SLAVE_ADDR, txData, 2, HAL_MAX_DELAY) == HAL_OK) {
// Success
} else {
// Error
}
HAL_Delay(500);
/*** Read data from a register ***/
txData[0] = 0x01; // Register to read
HAL_I2C_Master_Transmit(&hi2c1, SLAVE_ADDR, txData, 1, HAL_MAX_DELAY);
if (HAL_I2C_Master_Receive(&hi2c1, SLAVE_ADDR, rxData, 1, HAL_MAX_DELAY) == HAL_OK) {
// rxData[0] now contains the received byte
} else {
// Error
}
HAL_Delay(1000);
}
}
/*** I2C1 Initialization ***/
static void MX_I2C1_Init(void)
{
hi2c1.Instance = I2C1;
hi2c1.Init.ClockSpeed = 100000; // Standard mode 100kHz
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;
if (HAL_I2C_Init(&hi2c1) != HAL_OK) {
Error_Handler();
}
}
/*** GPIO Init for I2C1 (PB6=SCL, PB7=SDA on Bluepill) ***/
static void MX_GPIO_Init(void)
{
__HAL_RCC_GPIOB_CLK_ENABLE();
GPIO_InitTypeDef GPIO_InitStruct = {0};
GPIO_InitStruct.Pin = GPIO_PIN_6 | GPIO_PIN_7;
GPIO_InitStruct.Mode = GPIO_MODE_AF_OD;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF4_I2C1;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
}
Loading
stm32-bluepill
stm32-bluepill