|
| 1 | +// SPDX-FileCopyrightText: 2025 Nicolai Electronics |
| 2 | +// SPDX-License-Identifier: MIT |
| 3 | + |
| 4 | +#include <stdbool.h> |
| 5 | +#include <stdint.h> |
| 6 | +#include "bh24_hardware.h" |
| 7 | +#include "bsp/i2c.h" |
| 8 | +#include "driver/gpio.h" |
| 9 | +#include "driver/i2c_master.h" |
| 10 | +#include "esp_check.h" |
| 11 | +#include "esp_err.h" |
| 12 | +#include "freertos/FreeRTOS.h" |
| 13 | +#include "freertos/semphr.h" |
| 14 | + |
| 15 | +static char const* TAG = "BSP I2C"; |
| 16 | + |
| 17 | +// Primary I2C bus |
| 18 | + |
| 19 | +static i2c_master_bus_handle_t i2c_bus_handle_internal = NULL; |
| 20 | +static SemaphoreHandle_t i2c_concurrency_semaphore = NULL; |
| 21 | + |
| 22 | +i2c_master_bus_config_t i2c_master_config_internal = { |
| 23 | + .clk_source = I2C_CLK_SRC_DEFAULT, |
| 24 | + .i2c_port = BSP_I2C_BUS, |
| 25 | + .scl_io_num = BSP_I2C_SCL_PIN, |
| 26 | + .sda_io_num = BSP_I2C_SDA_PIN, |
| 27 | + .glitch_ignore_cnt = 7, |
| 28 | + .flags.enable_internal_pullup = true, |
| 29 | +}; |
| 30 | + |
| 31 | +esp_err_t bsp_i2c_primary_bus_initialize(void) { |
| 32 | + ESP_RETURN_ON_ERROR(i2c_new_master_bus(&i2c_master_config_internal, &i2c_bus_handle_internal), TAG, |
| 33 | + "Failed to initialize I2C bus"); |
| 34 | + i2c_concurrency_semaphore = xSemaphoreCreateBinary(); |
| 35 | + if (i2c_concurrency_semaphore == NULL) { |
| 36 | + return ESP_ERR_NO_MEM; |
| 37 | + } |
| 38 | + xSemaphoreGive(i2c_concurrency_semaphore); |
| 39 | + return ESP_OK; |
| 40 | +} |
| 41 | + |
| 42 | +esp_err_t bsp_i2c_primary_bus_get_handle(i2c_master_bus_handle_t* handle) { |
| 43 | + if (handle == NULL) { |
| 44 | + return ESP_ERR_INVALID_ARG; |
| 45 | + } |
| 46 | + *handle = i2c_bus_handle_internal; |
| 47 | + return ESP_OK; |
| 48 | +} |
| 49 | + |
| 50 | +esp_err_t bsp_i2c_primary_bus_get_semaphore(SemaphoreHandle_t* semaphore) { |
| 51 | + if (semaphore == NULL) { |
| 52 | + return ESP_ERR_INVALID_ARG; |
| 53 | + } |
| 54 | + *semaphore = i2c_concurrency_semaphore; |
| 55 | + return ESP_OK; |
| 56 | +} |
| 57 | + |
| 58 | +esp_err_t bsp_i2c_primary_bus_claim(void) { |
| 59 | + if (i2c_concurrency_semaphore != NULL) { |
| 60 | + xSemaphoreTake(i2c_concurrency_semaphore, portMAX_DELAY); |
| 61 | + } else { |
| 62 | + ESP_LOGW(TAG, "No concurrency semaphore"); |
| 63 | + } |
| 64 | + return ESP_OK; |
| 65 | +} |
| 66 | + |
| 67 | +esp_err_t bsp_i2c_primary_bus_release(void) { |
| 68 | + if (i2c_concurrency_semaphore != NULL) { |
| 69 | + xSemaphoreGive(i2c_concurrency_semaphore); |
| 70 | + } |
| 71 | + return ESP_OK; |
| 72 | +} |
0 commit comments