跳转至

rocketpi_i2c_at24cxx

效果展示

at24c02

功能说明

面向 RocketPI STM32F401RE 开发板的 AT24C02读写 演示工程。主要特性:

  • 使用软件i2c
  • 移植libdriver

硬件连接

image-20251213024252255

驱动以及测试代码

Core/Src/main.c
/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "driver_at24cxx.h"
#include "driver_at24cxx_read_test.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART2_UART_Init();
  /* USER CODE BEGIN 2 */

  at24cxx_read_test(AT24C02, AT24CXX_ADDRESS_A000);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  __HAL_RCC_PWR_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE2);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = 4;
  RCC_OscInitStruct.PLL.PLLN = 84;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = 7;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
bsp/at24xx/driver_at24cxx_interface.c
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
/**
 * Copyright (c) 2015 - present LibDriver All rights reserved
 * 
 * The MIT License (MIT)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE. 
 *
 * @file      driver_at24cxx_interface_template.c
 * @brief     driver at24cxx interface template source file
 * @version   2.0.0
 * @author    Shifeng Li
 * @date      2021-02-17
 *
 * <h3>history</h3>
 * <table>
 * <tr><th>Date        <th>Version  <th>Author      <th>Description
 * <tr><td>2021/02/17  <td>2.0      <td>Shifeng Li  <td>format the code
 * <tr><td>2020/10/15  <td>1.0      <td>Shifeng Li  <td>first upload
 * </table>
 */

#include "driver_at24cxx_interface.h"

#include "soft_i2c.h"
#include "main.h"

#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define AT24CXX_SOFT_I2C_DELAY_TICKS          120U
#define AT24CXX_INTERFACE_TX_STACK_BUFFER_SIZE 66U

static soft_i2c_bus_t s_at24cxx_soft_i2c_bus;

static void at24cxx_enable_gpio_clock(GPIO_TypeDef *port);
static soft_i2c_status_t at24cxx_scl_write(void *ctx, soft_i2c_pin_state_t state);
static soft_i2c_pin_state_t at24cxx_scl_read(void *ctx);
static soft_i2c_status_t at24cxx_sda_write(void *ctx, soft_i2c_pin_state_t state);
static soft_i2c_pin_state_t at24cxx_sda_read(void *ctx);
static uint8_t at24cxx_interface_write_with_prefix(uint8_t addr,
                                                   const uint8_t *prefix,
                                                   size_t prefix_len,
                                                   const uint8_t *buf,
                                                   uint16_t len);

static void at24cxx_enable_gpio_clock(GPIO_TypeDef *port)
{
#if defined(GPIOA) && defined(__HAL_RCC_GPIOA_CLK_ENABLE)
    if (port == GPIOA)
    {
        __HAL_RCC_GPIOA_CLK_ENABLE();
        return;
    }
#endif
#if defined(GPIOB) && defined(__HAL_RCC_GPIOB_CLK_ENABLE)
    if (port == GPIOB)
    {
        __HAL_RCC_GPIOB_CLK_ENABLE();
        return;
    }
#endif
#if defined(GPIOC) && defined(__HAL_RCC_GPIOC_CLK_ENABLE)
    if (port == GPIOC)
    {
        __HAL_RCC_GPIOC_CLK_ENABLE();
        return;
    }
#endif
#if defined(GPIOD) && defined(__HAL_RCC_GPIOD_CLK_ENABLE)
    if (port == GPIOD)
    {
        __HAL_RCC_GPIOD_CLK_ENABLE();
        return;
    }
#endif
#if defined(GPIOE) && defined(__HAL_RCC_GPIOE_CLK_ENABLE)
    if (port == GPIOE)
    {
        __HAL_RCC_GPIOE_CLK_ENABLE();
        return;
    }
#endif
#if defined(GPIOF) && defined(__HAL_RCC_GPIOF_CLK_ENABLE)
    if (port == GPIOF)
    {
        __HAL_RCC_GPIOF_CLK_ENABLE();
        return;
    }
#endif
#if defined(GPIOG) && defined(__HAL_RCC_GPIOG_CLK_ENABLE)
    if (port == GPIOG)
    {
        __HAL_RCC_GPIOG_CLK_ENABLE();
        return;
    }
#endif
#if defined(GPIOH) && defined(__HAL_RCC_GPIOH_CLK_ENABLE)
    if (port == GPIOH)
    {
        __HAL_RCC_GPIOH_CLK_ENABLE();
        return;
    }
#endif
#if defined(GPIOI) && defined(__HAL_RCC_GPIOI_CLK_ENABLE)
    if (port == GPIOI)
    {
        __HAL_RCC_GPIOI_CLK_ENABLE();
        return;
    }
#endif
#if defined(GPIOJ) && defined(__HAL_RCC_GPIOJ_CLK_ENABLE)
    if (port == GPIOJ)
    {
        __HAL_RCC_GPIOJ_CLK_ENABLE();
        return;
    }
#endif
#if defined(GPIOK) && defined(__HAL_RCC_GPIOK_CLK_ENABLE)
    if (port == GPIOK)
    {
        __HAL_RCC_GPIOK_CLK_ENABLE();
        return;
    }
#endif
}

static soft_i2c_status_t at24cxx_scl_write(void *ctx, soft_i2c_pin_state_t state)
{
    (void)ctx;
    HAL_GPIO_WritePin(AT24CXX_SCL_GPIO_Port, AT24CXX_SCL_Pin,
                      (state == SOFT_I2C_PIN_SET) ? GPIO_PIN_SET : GPIO_PIN_RESET);

    return SOFT_I2C_STATUS_OK;
}

static soft_i2c_pin_state_t at24cxx_scl_read(void *ctx)
{
    (void)ctx;
    return (HAL_GPIO_ReadPin(AT24CXX_SCL_GPIO_Port, AT24CXX_SCL_Pin) == GPIO_PIN_SET)
               ? SOFT_I2C_PIN_SET
               : SOFT_I2C_PIN_RESET;
}

static soft_i2c_status_t at24cxx_sda_write(void *ctx, soft_i2c_pin_state_t state)
{
    (void)ctx;
    HAL_GPIO_WritePin(AT24CXX_SDA_GPIO_Port, AT24CXX_SDA_Pin,
                      (state == SOFT_I2C_PIN_SET) ? GPIO_PIN_SET : GPIO_PIN_RESET);

    return SOFT_I2C_STATUS_OK;
}

static soft_i2c_pin_state_t at24cxx_sda_read(void *ctx)
{
    (void)ctx;
    return (HAL_GPIO_ReadPin(AT24CXX_SDA_GPIO_Port, AT24CXX_SDA_Pin) == GPIO_PIN_SET)
               ? SOFT_I2C_PIN_SET
               : SOFT_I2C_PIN_RESET;
}

static uint8_t at24cxx_interface_write_with_prefix(uint8_t addr,
                                                   const uint8_t *prefix,
                                                   size_t prefix_len,
                                                   const uint8_t *buf,
                                                   uint16_t len)
{
    size_t tx_len = prefix_len + (size_t)len;
    if (tx_len == 0U)
    {
        return 0;
    }

    uint8_t stack_buf[AT24CXX_INTERFACE_TX_STACK_BUFFER_SIZE];
    uint8_t *tx_buf = stack_buf;

    if (tx_len > sizeof(stack_buf))
    {
        tx_buf = (uint8_t *)malloc(tx_len);
        if (tx_buf == NULL)
        {
            return 1;
        }
    }

    if ((prefix_len > 0U) && (prefix != NULL))
    {
        memcpy(tx_buf, prefix, prefix_len);
    }
    if ((len > 0U) && (buf != NULL))
    {
        memcpy(tx_buf + prefix_len, buf, len);
    }

    soft_i2c_status_t status = soft_i2c_master_transmit(&s_at24cxx_soft_i2c_bus, addr, tx_buf, tx_len);

    if (tx_buf != stack_buf)
    {
        free(tx_buf);
    }

    return (status == SOFT_I2C_STATUS_OK) ? 0U : 1U;
}


/**
 * @brief  interface iic bus init
 * @return status code
 *         - 0 success
 *         - 1 iic init failed
 * @note   none
 */
uint8_t at24cxx_interface_iic_init(void)
{
    GPIO_InitTypeDef init = {0};

    at24cxx_enable_gpio_clock(AT24CXX_SCL_GPIO_Port);
    at24cxx_enable_gpio_clock(AT24CXX_SDA_GPIO_Port);

    init.Pin = AT24CXX_SCL_Pin;
    init.Mode = GPIO_MODE_OUTPUT_OD;
    init.Pull = GPIO_PULLUP;
    init.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
    HAL_GPIO_Init(AT24CXX_SCL_GPIO_Port, &init);

    init.Pin = AT24CXX_SDA_Pin;
    HAL_GPIO_Init(AT24CXX_SDA_GPIO_Port, &init);

    HAL_GPIO_WritePin(AT24CXX_SCL_GPIO_Port, AT24CXX_SCL_Pin, GPIO_PIN_SET);
    HAL_GPIO_WritePin(AT24CXX_SDA_GPIO_Port, AT24CXX_SDA_Pin, GPIO_PIN_SET);

    s_at24cxx_soft_i2c_bus.scl.write = at24cxx_scl_write;
    s_at24cxx_soft_i2c_bus.scl.read = at24cxx_scl_read;
    s_at24cxx_soft_i2c_bus.scl.ctx = NULL;
    s_at24cxx_soft_i2c_bus.sda.write = at24cxx_sda_write;
    s_at24cxx_soft_i2c_bus.sda.read = at24cxx_sda_read;
    s_at24cxx_soft_i2c_bus.sda.ctx = NULL;
    s_at24cxx_soft_i2c_bus.delay_fn = NULL;
    s_at24cxx_soft_i2c_bus.delay_ctx = NULL;
    s_at24cxx_soft_i2c_bus.delay_ticks = AT24CXX_SOFT_I2C_DELAY_TICKS;
    s_at24cxx_soft_i2c_bus.stretch_timeout_ticks = 0U;
    s_at24cxx_soft_i2c_bus.initialized = 0U;

    return (soft_i2c_bus_init(&s_at24cxx_soft_i2c_bus) == SOFT_I2C_STATUS_OK) ? 0U : 1U;
}

/**
 * @brief  interface iic bus deinit
 * @return status code
 *         - 0 success
 *         - 1 iic deinit failed
 * @note   none
 */
uint8_t at24cxx_interface_iic_deinit(void)
{
    if (AT24CXX_SCL_GPIO_Port == AT24CXX_SDA_GPIO_Port)
    {
        HAL_GPIO_DeInit(AT24CXX_SCL_GPIO_Port, AT24CXX_SCL_Pin | AT24CXX_SDA_Pin);
    }
    else
    {
        HAL_GPIO_DeInit(AT24CXX_SCL_GPIO_Port, AT24CXX_SCL_Pin);
        HAL_GPIO_DeInit(AT24CXX_SDA_GPIO_Port, AT24CXX_SDA_Pin);
    }

    s_at24cxx_soft_i2c_bus.initialized = 0U;

    return 0;
}

/**
 * @brief      interface iic bus read
 * @param[in]  addr iic device write address
 * @param[in]  reg iic register address
 * @param[out] *buf pointer to a data buffer
 * @param[in]  len length of the data buffer
 * @return     status code
 *             - 0 success
 *             - 1 read failed
 * @note       none
 */
uint8_t at24cxx_interface_iic_read(uint8_t addr, uint8_t reg, uint8_t *buf, uint16_t len)
{
    if (len == 0U)
    {
        return 0;
    }
    if (buf == NULL)
    {
        return 1;
    }

    uint8_t reg_buf[1];
    reg_buf[0] = reg;

    soft_i2c_status_t status = soft_i2c_master_write_read(&s_at24cxx_soft_i2c_bus,
                                                          addr,
                                                          reg_buf,
                                                          sizeof(reg_buf),
                                                          buf,
                                                          len);

    return (status == SOFT_I2C_STATUS_OK) ? 0U : 1U;
}

/**
 * @brief     interface iic bus write
 * @param[in] addr iic device write address
 * @param[in] reg iic register address
 * @param[in] *buf pointer to a data buffer
 * @param[in] len length of the data buffer
 * @return    status code
 *            - 0 success
 *            - 1 write failed
 * @note      none
 */
uint8_t at24cxx_interface_iic_write(uint8_t addr, uint8_t reg, uint8_t *buf, uint16_t len)
{
    if (len == 0U)
    {
        return 0;
    }
    if (buf == NULL)
    {
        return 1;
    }

    uint8_t prefix[1];
    prefix[0] = reg;

    return at24cxx_interface_write_with_prefix(addr, prefix, sizeof(prefix), buf, len);
}

/**
 * @brief      interface iic bus read with 16 bits register address
 * @param[in]  addr iic device write address
 * @param[in]  reg iic register address
 * @param[out] *buf pointer to a data buffer
 * @param[in]  len length of the data buffer
 * @return     status code
 *             - 0 success
 *             - 1 read failed
 * @note       none
 */
uint8_t at24cxx_interface_iic_read_address16(uint8_t addr, uint16_t reg, uint8_t *buf, uint16_t len)
{
    if (len == 0U)
    {
        return 0;
    }
    if (buf == NULL)
    {
        return 1;
    }

    uint8_t reg_buf[2];
    reg_buf[0] = (uint8_t)(reg >> 8);
    reg_buf[1] = (uint8_t)(reg & 0xFFU);

    soft_i2c_status_t status = soft_i2c_master_write_read(&s_at24cxx_soft_i2c_bus,
                                                          addr,
                                                          reg_buf,
                                                          sizeof(reg_buf),
                                                          buf,
                                                          len);

    return (status == SOFT_I2C_STATUS_OK) ? 0U : 1U;
}

/**
 * @brief     interface iic bus write with 16 bits register address
 * @param[in] addr iic device write address
 * @param[in] reg iic register address
 * @param[in] *buf pointer to a data buffer
 * @param[in] len length of the data buffer
 * @return    status code
 *            - 0 success
 *            - 1 write failed
 * @note      none
 */
uint8_t at24cxx_interface_iic_write_address16(uint8_t addr, uint16_t reg, uint8_t *buf, uint16_t len)
{
    if (len == 0U)
    {
        return 0;
    }
    if (buf == NULL)
    {
        return 1;
    }

    uint8_t prefix[2];
    prefix[0] = (uint8_t)(reg >> 8);
    prefix[1] = (uint8_t)(reg & 0xFFU);

    return at24cxx_interface_write_with_prefix(addr, prefix, sizeof(prefix), buf, len);
}

/**
 * @brief     interface delay ms
 * @param[in] ms time
 * @note      none
 */
void at24cxx_interface_delay_ms(uint32_t ms)
{
    HAL_Delay(ms);
}

/**
 * @brief     interface print format data
 * @param[in] fmt format data
 * @note      none
 */
void at24cxx_interface_debug_print(const char *const fmt, ...)
{
    char buf[256];
    va_list ap;
    va_start(ap, fmt);
    int n = vsnprintf(buf, sizeof buf, fmt, ap);
    va_end(ap);
    if (n < 0) return;
    if (n >= (int)sizeof buf) n = sizeof buf - 1;

    for (int i = 0; i < n; ++i) {
        if (buf[i] == '\n') fputc('\r', stdout);
        fputc((unsigned char)buf[i], stdout);
    }
    if (n == 0 || buf[n - 1] != '\n') { fputc('\r', stdout); fputc('\n', stdout); }
}
bsp/soft_i2c/soft_i2c.c
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
#include "soft_i2c.h"

#ifndef __NOP
#define __NOP() __asm volatile ("nop")
#endif

static soft_i2c_status_t soft_i2c_prepare_bus(soft_i2c_bus_t *bus);
static void soft_i2c_delay(const soft_i2c_bus_t *bus);
static soft_i2c_status_t soft_i2c_drive_scl(soft_i2c_bus_t *bus, soft_i2c_pin_state_t state);
static soft_i2c_status_t soft_i2c_drive_sda(soft_i2c_bus_t *bus, soft_i2c_pin_state_t state);
static soft_i2c_status_t soft_i2c_start(soft_i2c_bus_t *bus);
static soft_i2c_status_t soft_i2c_repeated_start(soft_i2c_bus_t *bus);
static void soft_i2c_stop(soft_i2c_bus_t *bus);
static soft_i2c_status_t soft_i2c_write_byte(soft_i2c_bus_t *bus, uint8_t value);
static soft_i2c_status_t soft_i2c_read_byte(soft_i2c_bus_t *bus, uint8_t *value, int last_byte);

/* 初始化软I2C总线:确认GPIO操作回调存在并设置默认延时 */
soft_i2c_status_t soft_i2c_bus_init(soft_i2c_bus_t *bus)
{
    if ((bus == NULL) ||
        (bus->scl.write == NULL) || (bus->scl.read == NULL) ||
        (bus->sda.write == NULL) || (bus->sda.read == NULL)) {
        return SOFT_I2C_STATUS_INVALID_PARAM;
    }

    if (bus->delay_ticks == 0U) {
        bus->delay_ticks = SOFT_I2C_DEFAULT_DELAY_TICKS;
    }

    if (bus->stretch_timeout_ticks == 0U) {
        bus->stretch_timeout_ticks = SOFT_I2C_DEFAULT_STRETCH_TICKS;
    }

    soft_i2c_drive_scl(bus, SOFT_I2C_PIN_SET);
    soft_i2c_drive_sda(bus, SOFT_I2C_PIN_SET);

    bus->initialized = 1U;
    return SOFT_I2C_STATUS_OK;
}

/* 执行起始+地址+数据的写入流程,遇到NACK立即停止 */
soft_i2c_status_t soft_i2c_master_transmit(soft_i2c_bus_t *bus, uint8_t address,
                                           const uint8_t *data, size_t size)
{
    if ((data == NULL) && (size > 0U)) {
        return SOFT_I2C_STATUS_INVALID_PARAM;
    }

    soft_i2c_status_t status = soft_i2c_prepare_bus(bus);
    if (status != SOFT_I2C_STATUS_OK) {
        return status;
    }

    int started = 0;
    status = soft_i2c_start(bus);
    if (status != SOFT_I2C_STATUS_OK) {
        goto done;
    }
    started = 1;

    status = soft_i2c_write_byte(bus, address & (uint8_t)~0x01U);
    if (status != SOFT_I2C_STATUS_OK) {
        goto done;
    }

    for (size_t i = 0; i < size; ++i) {
        status = soft_i2c_write_byte(bus, data[i]);
        if (status != SOFT_I2C_STATUS_OK) {
            goto done;
        }
    }

done:
    if (started) {
        soft_i2c_stop(bus);
    }
    return status;
}

/* 仅执行读流程,负责发送最后一个NACK并停止 */
soft_i2c_status_t soft_i2c_master_receive(soft_i2c_bus_t *bus, uint8_t address,
                                          uint8_t *data, size_t size)
{
    if ((data == NULL) && (size > 0U)) {
        return SOFT_I2C_STATUS_INVALID_PARAM;
    }
    if (size == 0U) {
        return SOFT_I2C_STATUS_OK;
    }

    soft_i2c_status_t status = soft_i2c_prepare_bus(bus);
    if (status != SOFT_I2C_STATUS_OK) {
        return status;
    }

    int started = 0;
    status = soft_i2c_start(bus);
    if (status != SOFT_I2C_STATUS_OK) {
        goto done;
    }
    started = 1;

    status = soft_i2c_write_byte(bus, address | 0x01U);
    if (status != SOFT_I2C_STATUS_OK) {
        goto done;
    }

    for (size_t i = 0; i < size; ++i) {
        const int last_byte = (i + 1U) == size;
        status = soft_i2c_read_byte(bus, &data[i], last_byte);
        if (status != SOFT_I2C_STATUS_OK) {
            goto done;
        }
    }

done:
    if (started) {
        soft_i2c_stop(bus);
    }
    return status;
}

/* 先写后读的组合事务,实现典型寄存器访问 */
soft_i2c_status_t soft_i2c_master_write_read(soft_i2c_bus_t *bus, uint8_t address,
                                             const uint8_t *tx_data, size_t tx_size,
                                             uint8_t *rx_data, size_t rx_size)
{
    if (((tx_data == NULL) && (tx_size > 0U)) ||
        ((rx_data == NULL) && (rx_size > 0U))) {
        return SOFT_I2C_STATUS_INVALID_PARAM;
    }

    soft_i2c_status_t status = soft_i2c_prepare_bus(bus);
    if (status != SOFT_I2C_STATUS_OK) {
        return status;
    }

    int started = 0;
    if (tx_size > 0U) {
        status = soft_i2c_start(bus);
        if (status != SOFT_I2C_STATUS_OK) {
            goto cleanup;
        }
        started = 1;

        status = soft_i2c_write_byte(bus, address & (uint8_t)~0x01U);
        if (status != SOFT_I2C_STATUS_OK) {
            goto cleanup;
        }

        for (size_t i = 0; i < tx_size; ++i) {
            status = soft_i2c_write_byte(bus, tx_data[i]);
            if (status != SOFT_I2C_STATUS_OK) {
                goto cleanup;
            }
        }
    }

    if (rx_size > 0U) {
        if (!started) {
            status = soft_i2c_start(bus);
            if (status != SOFT_I2C_STATUS_OK) {
                goto cleanup;
            }
            started = 1;
        } else {
            status = soft_i2c_repeated_start(bus);
            if (status != SOFT_I2C_STATUS_OK) {
                goto cleanup;
            }
        }

        status = soft_i2c_write_byte(bus, address | 0x01U);
        if (status != SOFT_I2C_STATUS_OK) {
            goto cleanup;
        }

        for (size_t i = 0; i < rx_size; ++i) {
            const int last_byte = (i + 1U) == rx_size;
            status = soft_i2c_read_byte(bus, &rx_data[i], last_byte);
            if (status != SOFT_I2C_STATUS_OK) {
                goto cleanup;
            }
        }
    }

cleanup:
    if (started) {
        soft_i2c_stop(bus);
    }
    return status;
}

/* 确保总线已经初始化,必要时报错 */
static soft_i2c_status_t soft_i2c_prepare_bus(soft_i2c_bus_t *bus)
{
    if (bus == NULL) {
        return SOFT_I2C_STATUS_INVALID_PARAM;
    }

    if (bus->initialized == 0U) {
        return soft_i2c_bus_init(bus);
    }

    return SOFT_I2C_STATUS_OK;
}

/* 根据配置执行半周期延时,可自定义回调或默认NOP循环 */
static void soft_i2c_delay(const soft_i2c_bus_t *bus)
{
    if ((bus != NULL) && (bus->delay_fn != NULL)) {
        bus->delay_fn(bus->delay_ticks, bus->delay_ctx);
        return;
    }

    uint32_t ticks = (bus == NULL || bus->delay_ticks == 0U) ? SOFT_I2C_DEFAULT_DELAY_TICKS : bus->delay_ticks;
    for (volatile uint32_t i = 0; i < ticks; ++i) {
        __NOP();
    }
}

/* 设置SCL电平并处理clock stretching */
static soft_i2c_status_t soft_i2c_drive_scl(soft_i2c_bus_t *bus, soft_i2c_pin_state_t state)
{
    soft_i2c_status_t status = bus->scl.write(bus->scl.ctx, state);
    if (status != SOFT_I2C_STATUS_OK) {
        return status;
    }

    if (state == SOFT_I2C_PIN_SET) {
        uint32_t timeout = (bus->stretch_timeout_ticks == 0U)
                               ? SOFT_I2C_DEFAULT_STRETCH_TICKS
                               : bus->stretch_timeout_ticks;
        while (bus->scl.read(bus->scl.ctx) == SOFT_I2C_PIN_RESET) {
            if (timeout-- == 0U) {
                return SOFT_I2C_STATUS_TIMEOUT;
            }
        }
    }

    return SOFT_I2C_STATUS_OK;
}

/* 设置SDA电平 */
static soft_i2c_status_t soft_i2c_drive_sda(soft_i2c_bus_t *bus, soft_i2c_pin_state_t state)
{
    return bus->sda.write(bus->sda.ctx, state);
}

/* 产生I2C起始条件 */
static soft_i2c_status_t soft_i2c_start(soft_i2c_bus_t *bus)
{
    soft_i2c_status_t status = soft_i2c_drive_sda(bus, SOFT_I2C_PIN_SET);
    if (status != SOFT_I2C_STATUS_OK) {
        return status;
    }

    status = soft_i2c_drive_scl(bus, SOFT_I2C_PIN_SET);
    if (status != SOFT_I2C_STATUS_OK) {
        return status;
    }
    soft_i2c_delay(bus);

    status = soft_i2c_drive_sda(bus, SOFT_I2C_PIN_RESET);
    if (status != SOFT_I2C_STATUS_OK) {
        return status;
    }
    soft_i2c_delay(bus);

    status = soft_i2c_drive_scl(bus, SOFT_I2C_PIN_RESET);
    if (status != SOFT_I2C_STATUS_OK) {
        return status;
    }
    soft_i2c_delay(bus);

    return SOFT_I2C_STATUS_OK;
}

/* 产生重复起始条件,用于读写切换 */
static soft_i2c_status_t soft_i2c_repeated_start(soft_i2c_bus_t *bus)
{
    soft_i2c_status_t status = soft_i2c_drive_sda(bus, SOFT_I2C_PIN_SET);
    if (status != SOFT_I2C_STATUS_OK) {
        return status;
    }
    soft_i2c_delay(bus);

    status = soft_i2c_drive_scl(bus, SOFT_I2C_PIN_SET);
    if (status != SOFT_I2C_STATUS_OK) {
        return status;
    }
    soft_i2c_delay(bus);

    status = soft_i2c_drive_sda(bus, SOFT_I2C_PIN_RESET);
    if (status != SOFT_I2C_STATUS_OK) {
        return status;
    }
    soft_i2c_delay(bus);

    status = soft_i2c_drive_scl(bus, SOFT_I2C_PIN_RESET);
    if (status != SOFT_I2C_STATUS_OK) {
        return status;
    }
    soft_i2c_delay(bus);

    return SOFT_I2C_STATUS_OK;
}

/* 产生停止条件,将总线释放到空闲 */
static void soft_i2c_stop(soft_i2c_bus_t *bus)
{
    soft_i2c_drive_sda(bus, SOFT_I2C_PIN_RESET);
    soft_i2c_delay(bus);
    soft_i2c_drive_scl(bus, SOFT_I2C_PIN_SET);
    soft_i2c_delay(bus);
    soft_i2c_drive_sda(bus, SOFT_I2C_PIN_SET);
    soft_i2c_delay(bus);
}

/* 写入单字节并读取对方ACK */
static soft_i2c_status_t soft_i2c_write_byte(soft_i2c_bus_t *bus, uint8_t value)
{
    for (int8_t bit = 7; bit >= 0; --bit) {
        soft_i2c_pin_state_t state = ((value >> bit) & 0x01U) ? SOFT_I2C_PIN_SET : SOFT_I2C_PIN_RESET;
        soft_i2c_status_t status = soft_i2c_drive_sda(bus, state);
        if (status != SOFT_I2C_STATUS_OK) {
            return status;
        }
        soft_i2c_delay(bus);

        status = soft_i2c_drive_scl(bus, SOFT_I2C_PIN_SET);
        if (status != SOFT_I2C_STATUS_OK) {
            return status;
        }
        soft_i2c_delay(bus);

        status = soft_i2c_drive_scl(bus, SOFT_I2C_PIN_RESET);
        if (status != SOFT_I2C_STATUS_OK) {
            return status;
        }
        soft_i2c_delay(bus);
    }

    soft_i2c_status_t status = soft_i2c_drive_sda(bus, SOFT_I2C_PIN_SET);
    if (status != SOFT_I2C_STATUS_OK) {
        return status;
    }
    soft_i2c_delay(bus);

    status = soft_i2c_drive_scl(bus, SOFT_I2C_PIN_SET);
    if (status != SOFT_I2C_STATUS_OK) {
        return status;
    }
    soft_i2c_delay(bus);

    soft_i2c_pin_state_t ack = bus->sda.read(bus->sda.ctx);

    status = soft_i2c_drive_scl(bus, SOFT_I2C_PIN_RESET);
    if (status != SOFT_I2C_STATUS_OK) {
        return status;
    }
    soft_i2c_delay(bus);

    return (ack == SOFT_I2C_PIN_RESET) ? SOFT_I2C_STATUS_OK : SOFT_I2C_STATUS_ERROR;
}

/* 读取单字节,并根据last_byte决定发送ACK或NACK */
static soft_i2c_status_t soft_i2c_read_byte(soft_i2c_bus_t *bus, uint8_t *value, int last_byte)
{
    uint8_t result = 0U;
    soft_i2c_status_t status = soft_i2c_drive_sda(bus, SOFT_I2C_PIN_SET);
    if (status != SOFT_I2C_STATUS_OK) {
        return status;
    }

    for (int8_t bit = 7; bit >= 0; --bit) {
        status = soft_i2c_drive_scl(bus, SOFT_I2C_PIN_SET);
        if (status != SOFT_I2C_STATUS_OK) {
            return status;
        }
        soft_i2c_delay(bus);

        if (bus->sda.read(bus->sda.ctx) == SOFT_I2C_PIN_SET) {
            result |= (uint8_t)(1U << bit);
        }

        status = soft_i2c_drive_scl(bus, SOFT_I2C_PIN_RESET);
        if (status != SOFT_I2C_STATUS_OK) {
            return status;
        }
        soft_i2c_delay(bus);
    }

    status = soft_i2c_drive_sda(bus, last_byte ? SOFT_I2C_PIN_SET : SOFT_I2C_PIN_RESET);
    if (status != SOFT_I2C_STATUS_OK) {
        return status;
    }
    soft_i2c_delay(bus);

    status = soft_i2c_drive_scl(bus, SOFT_I2C_PIN_SET);
    if (status != SOFT_I2C_STATUS_OK) {
        return status;
    }
    soft_i2c_delay(bus);

    status = soft_i2c_drive_scl(bus, SOFT_I2C_PIN_RESET);
    if (status != SOFT_I2C_STATUS_OK) {
        return status;
    }
    soft_i2c_delay(bus);

    soft_i2c_drive_sda(bus, SOFT_I2C_PIN_SET);

    if (value != NULL) {
        *value = result;
    }

    return SOFT_I2C_STATUS_OK;
}
bsp/soft_i2c/soft_i2c.h
#pragma once

#include <stddef.h>
#include <stdint.h>

/**
 * @file soft_i2c.h
 * @brief 通用软件I2C主机接口定义,与具体平台解耦。
 */

#define SOFT_I2C_DEFAULT_DELAY_TICKS      64U
#define SOFT_I2C_DEFAULT_STRETCH_TICKS  4000U

#ifdef __cplusplus
extern "C" {
#endif

typedef enum {
    SOFT_I2C_STATUS_OK = 0,
    SOFT_I2C_STATUS_ERROR = 1,
    SOFT_I2C_STATUS_TIMEOUT = 2,
    SOFT_I2C_STATUS_INVALID_PARAM = 3
} soft_i2c_status_t;

typedef enum {
    SOFT_I2C_PIN_RESET = 0,
    SOFT_I2C_PIN_SET = 1
} soft_i2c_pin_state_t;

typedef soft_i2c_status_t (*soft_i2c_pin_write_fn)(void *ctx, soft_i2c_pin_state_t state);
typedef soft_i2c_pin_state_t (*soft_i2c_pin_read_fn)(void *ctx);
typedef void (*soft_i2c_delay_fn)(uint32_t ticks, void *ctx);

typedef struct {
    soft_i2c_pin_write_fn write;
    soft_i2c_pin_read_fn read;
    void *ctx;
} soft_i2c_pin_io_t;

typedef struct {
    soft_i2c_pin_io_t scl;
    soft_i2c_pin_io_t sda;
    soft_i2c_delay_fn delay_fn;
    void *delay_ctx;
    uint32_t delay_ticks;
    uint32_t stretch_timeout_ticks;
    uint8_t initialized;
} soft_i2c_bus_t;

/** 初始化总线结构体并拉高SCL/SDA,准备进入空闲状态。 */
soft_i2c_status_t soft_i2c_bus_init(soft_i2c_bus_t *bus);

/** 发送一帧起始+写数据,若任何字节NACK则返回错误。 */
soft_i2c_status_t soft_i2c_master_transmit(soft_i2c_bus_t *bus, uint8_t address,
                                           const uint8_t *data, size_t size);

/** 发送起始后进入读模式,并根据长度自动发送ACK/NACK。 */
soft_i2c_status_t soft_i2c_master_receive(soft_i2c_bus_t *bus, uint8_t address,
                                          uint8_t *data, size_t size);

/** 常见的先写后读组合操作,可用于寄存器访问。 */
soft_i2c_status_t soft_i2c_master_write_read(soft_i2c_bus_t *bus, uint8_t address,
                                             const uint8_t *tx_data, size_t tx_size,
                                             uint8_t *rx_data, size_t rx_size);

#ifdef __cplusplus
}
#endif