/*
 * i2c1.c — Shared I2C1 bus (PB8=SCL, PB9=SDA, 100 kHz)
 *
 * Used by barometer and magnetometer drivers.
 * Call i2c1_init() once before any I2C probes.
 */
#include "i2c1.h"
#include "stm32f7xx_hal.h"

I2C_HandleTypeDef hi2c1;

int i2c1_init(void) {
    __HAL_RCC_GPIOB_CLK_ENABLE();
    __HAL_RCC_I2C1_CLK_ENABLE();

    GPIO_InitTypeDef gpio = {0};
    gpio.Pin       = GPIO_PIN_8 | GPIO_PIN_9;  /* PB8=SCL, PB9=SDA */
    gpio.Mode      = GPIO_MODE_AF_OD;
    gpio.Pull      = GPIO_PULLUP;
    gpio.Speed     = GPIO_SPEED_FREQ_HIGH;
    gpio.Alternate = GPIO_AF4_I2C1;
    HAL_GPIO_Init(GPIOB, &gpio);

    hi2c1.Instance             = I2C1;
    hi2c1.Init.Timing          = 0x20404768;  /* 100 kHz @ 54 MHz APB1 */
    hi2c1.Init.OwnAddress1     = 0;
    hi2c1.Init.AddressingMode  = I2C_ADDRESSINGMODE_7BIT;
    hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
    hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
    hi2c1.Init.NoStretchMode   = I2C_NOSTRETCH_DISABLE;

    return (HAL_I2C_Init(&hi2c1) == HAL_OK) ? 0 : -1;
}
