Compare commits

..

3 Commits

Author SHA1 Message Date
54bf206ec3 for debug 2025-08-14 00:13:49 +08:00
93294b0e3c add M4 test command 2025-08-14 00:07:45 +08:00
d7029d91e7 add Hardware IIC 2025-08-14 00:07:16 +08:00
10 changed files with 705 additions and 303 deletions

View File

@@ -4,6 +4,10 @@
"Git Bash": {
"path": "C:\\Program Files\\Git\\bin\\bash.exe",
"icon": "terminal-bash"
},
"Git-Bash": {
"path": "D:\\Git\\bin\\bash.exe",
"icon": "terminal-bash"
}
},
"terminal.integrated.defaultProfile.windows": "Git-Bash",

View File

@@ -29,6 +29,7 @@ set(TARGET_SRC
Src/led.c
Src/uart_ring_buffer.c
Src/command.c
Src/i2c.c
)
# 设置输出目录

139
I2C_IMPROVEMENTS.md Normal file
View File

@@ -0,0 +1,139 @@
# I2C驱动改进总结
## 🔧 主要改进内容
### 1. **状态机重构**
- **原问题**: 状态机逻辑混乱使用复杂的read_cycle变量
- **改进方案**:
- 使用清晰的`i2c_state_t`枚举定义状态
- 分离写入和读取的状态流程
- 每个状态职责单一,逻辑清晰
```c
typedef enum {
I2C_STATE_IDLE = 0, /* 空闲状态 */
I2C_STATE_START, /* 生成起始条件 */
I2C_STATE_SEND_ADDRESS, /* 发送从设备地址 */
I2C_STATE_CLEAR_ADDRESS, /* 清除地址标志 */
I2C_STATE_TRANSMIT_REG, /* 发送寄存器地址 */
I2C_STATE_TRANSMIT_DATA, /* 发送数据 */
I2C_STATE_RESTART, /* 生成重启条件 */
I2C_STATE_RECEIVE_DATA, /* 接收数据 */
I2C_STATE_STOP, /* 生成停止条件 */
I2C_STATE_ERROR /* 错误状态 */
} i2c_state_t;
```
### 2. **错误处理改进**
- **原问题**: 函数总是返回成功,无法区分错误类型
- **改进方案**:
- 定义详细的状态码枚举
- 添加参数验证
- 实现重试机制
```c
typedef enum {
I2C_STATUS_SUCCESS = 0, /* 操作成功 */
I2C_STATUS_TIMEOUT, /* 超时 */
I2C_STATUS_NACK, /* 无应答 */
I2C_STATUS_BUS_BUSY, /* 总线忙 */
I2C_STATUS_ERROR, /* 一般错误 */
I2C_STATUS_INVALID_PARAM /* 无效参数 */
} i2c_status_t;
```
### 3. **超时处理优化**
- **原问题**: 超时后无限循环重试
- **改进方案**:
- 限制最大重试次数 (`I2C_MAX_RETRY = 3`)
- 超时后进入错误状态
- 重试前添加延时
### 4. **总线重置完善**
- **原问题**: 总线重置不完整,可能无法恢复卡死状态
- **改进方案**:
- 实现标准的9时钟脉冲恢复
- 生成正确的停止条件
- 重新配置GPIO和I2C外设
```c
/* 生成9个时钟脉冲释放卡死的从设备 */
for (i = 0; i < I2C_RECOVERY_CLOCKS; i++) {
gpio_bit_reset(I2C_SCL_PORT, I2C_SCL_PIN);
delay_us(I2C_DELAY_US);
gpio_bit_set(I2C_SCL_PORT, I2C_SCL_PIN);
delay_us(I2C_DELAY_US);
}
```
### 5. **配置问题修复**
- **原问题**: 硬编码从设备地址0xA0
- **改进方案**: 主机地址设为0x00从设备地址作为参数传入
### 6. **代码结构优化**
- **原问题**: 状态机中有大量重复代码
- **改进方案**:
- 统一的超时检查模式
- 清晰的状态转换逻辑
- 一致的错误处理流程
## 📋 新增功能
### 1. **状态字符串函数**
```c
const char* i2c_get_status_string(i2c_status_t status);
```
用于调试时获取状态描述字符串。
### 2. **参数验证**
```c
if (data == NULL || slave_addr > 0x7F) {
return I2C_STATUS_INVALID_PARAM;
}
```
### 3. **调试信息**
使用`DEBUG_VERBOSE`宏控制调试输出。
## 🔍 状态机流程
### 写入流程:
```
START → SEND_ADDRESS → CLEAR_ADDRESS → TRANSMIT_REG →
TRANSMIT_DATA → STOP → SUCCESS
```
### 读取流程:
```
写阶段: START → SEND_ADDRESS → CLEAR_ADDRESS → TRANSMIT_REG → RESTART
读阶段: START → SEND_ADDRESS → CLEAR_ADDRESS → RECEIVE_DATA → STOP → SUCCESS
```
## 🚀 使用示例
```c
// 写入16位数据
uint8_t write_data[2] = {0x12, 0x34};
i2c_status_t status = i2c_write_16bits(0x48, 0x01, write_data);
if (status != I2C_STATUS_SUCCESS) {
printf("Write failed: %s\r\n", i2c_get_status_string(status));
}
// 读取16位数据
uint8_t read_data[2];
status = i2c_read_16bits(0x48, 0x01, read_data);
if (status == I2C_STATUS_SUCCESS) {
printf("Read data: 0x%02X%02X\r\n", read_data[0], read_data[1]);
} else {
printf("Read failed: %s\r\n", i2c_get_status_string(status));
}
```
## 📝 注意事项
1. **编译选项**: 确保包含`<stdbool.h>`以支持bool类型
2. **调试输出**: 定义`DEBUG_VERBOSE`宏启用调试信息
3. **延时函数**: 确保`delay_us()`函数可用
4. **兼容性**: 保留了原有的函数接口以保持向后兼容
这些改进大大提高了I2C驱动的可靠性、可维护性和调试能力。

View File

@@ -13,8 +13,8 @@
/* >>>>>>>>>>>>>>>>>>>>[DEBUG ASSERTIONS DEFINE]<<<<<<<<<<<<<<<<<<<< */
// #define DEBUG_VERBOSE // Debug Assertions Status : Debug Verbose Information
#undef DEBUG_VERBOSE // Debug Assertions Status : No Debug Verbose Information
#define DEBUG_VERBOSE // Debug Assertions Status : Debug Verbose Information
// #undef DEBUG_VERBOSE // Debug Assertions Status : No Debug Verbose Information
/******************************************************************************/
@@ -26,6 +26,8 @@
#define I2C_SDA_PIN GPIO_PIN_0
#define I2C_GPIO_AF GPIO_AF_1
#define I2C_DEBUG_UART USART0
/******************************************************************************/
#define LED_PORT GPIOA

View File

@@ -8,7 +8,6 @@
#include "gd32e23x_it.h"
#include "gd32e23x.h"
#include "systick.h"
#include "main.h"
#include <stdbool.h>
#include <string.h>
#include <stdio.h>
@@ -19,15 +18,45 @@
/******************************************************************************/
#define I2C_SPEED 100*(1000)
#define I2C_SPEED 100000U /* 100kHz */
#define I2C_TIME_OUT 5000U /* 5000 loops timeout */
#define I2C_MAX_RETRY 3U /* Maximum retry attempts */
#define I2C_DELAY_10US 10U /* Delay in microseconds for bus reset */
#define I2C_RECOVERY_CLOCKS 9U /* Clock pulses for bus recovery */
#define I2C_MASTER_ADDRESS 0x00U /* Master address (not used) */
#define I2C_TIME_OUT (uint16_t)(5000)
#define I2C_OK 1
#define I2C_FAIL 0
#define I2C_END 1
/* Legacy compatibility */
#define I2C_OK 1
#define I2C_FAIL 0
#define I2C_END 1
/******************************************************************************/
/* I2C status enumeration */
typedef enum {
I2C_STATUS_SUCCESS = 0, /* Operation successful */
I2C_STATUS_TIMEOUT, /* Timeout occurred */
I2C_STATUS_NACK, /* No acknowledge received */
I2C_STATUS_BUS_BUSY, /* Bus is busy */
I2C_STATUS_ERROR, /* General error */
I2C_STATUS_INVALID_PARAM /* Invalid parameter */
} i2c_status_t;
/* I2C state machine enumeration */
typedef enum {
I2C_STATE_IDLE = 0, /* Idle state */
I2C_STATE_START, /* Generate start condition */
I2C_STATE_SEND_ADDRESS, /* Send slave address */
I2C_STATE_CLEAR_ADDRESS, /* Clear address flag */
I2C_STATE_TRANSMIT_REG, /* Transmit register address */
I2C_STATE_TRANSMIT_DATA, /* Transmit data */
I2C_STATE_RESTART, /* Generate restart condition */
I2C_STATE_RECEIVE_DATA, /* Receive data */
I2C_STATE_STOP, /* Generate stop condition */
I2C_STATE_ERROR /* Error state */
} i2c_state_t;
/* Legacy enumeration for compatibility */
typedef enum {
I2C_START = 0,
I2C_SEND_ADDRESS,
@@ -38,16 +67,65 @@ typedef enum {
/******************************************************************************/
/* Function declarations */
/*!
\brief configure the GPIO ports for I2C
\param[in] none
\param[out] none
\retval none
*/
void i2c_gpio_config(void);
void i2c_config(void);
/*!
\brief configure the I2C interface
\param[in] none
\param[out] none
\retval i2c_status_t
*/
i2c_status_t i2c_config(void);
void i2c_bus_reset(void);
/*!
\brief reset I2C bus with proper recovery
\param[in] none
\param[out] none
\retval i2c_status_t
*/
i2c_status_t i2c_bus_reset(void);
/*!
\brief scan I2C bus for devices
\param[in] none
\param[out] none
\retval none
*/
void i2c_scan(void);
uint8_t i2c_write_16bits(uint8_t slave_addr, uint8_t reg_addr, uint8_t data[2]);
/*!
\brief write 16-bit data to I2C device
\param[in] slave_addr: 7-bit slave address
\param[in] reg_addr: register address
\param[in] data: pointer to 2-byte data array
\param[out] none
\retval i2c_status_t
*/
i2c_status_t i2c_write_16bits(uint8_t slave_addr, uint8_t reg_addr, const uint8_t data[2]);
uint8_t i2c_read_16bits(uint8_t slave_addr, uint8_t reg_addr, uint8_t *data);
/*!
\brief read 16-bit data from I2C device
\param[in] slave_addr: 7-bit slave address
\param[in] reg_addr: register address
\param[out] data: pointer to 2-byte data buffer
\retval i2c_status_t
*/
i2c_status_t i2c_read_16bits(uint8_t slave_addr, uint8_t reg_addr, uint8_t *data);
/*!
\brief get status string for debugging
\param[in] status: i2c_status_t value
\param[out] none
\retval const char* status string
*/
const char* i2c_get_status_string(i2c_status_t status);
#endif //I2C_H

View File

@@ -8,7 +8,6 @@
#include "gd32e23x_it.h"
#include "gd32e23x.h"
#include "systick.h"
#include "main.h"
#include "board_config.h"

View File

@@ -277,14 +277,12 @@ void handle_command(const uint8_t *frame, uint8_t len) {
switch (base_cmd) {
case 1u: // M1命令
set_sensor_report_status(true);
// led_on();
// send_response(RESP_TYPE_OK, s_report_status_ok, sizeof(s_report_status_ok));
uint8_t test_response1[] = { 0xAA, 0xBB, 0xCC, 0xDD };
send_response(RESP_TYPE_OK, test_response1, sizeof(test_response1));
return;
case 2u: // M2命令
set_sensor_report_status(false);
// led_off();
// send_response(RESP_TYPE_OK, s_report_status_ok, sizeof(s_report_status_ok));
uint8_t test_response2[] = { 0xDD, 0xCC, 0xBB, 0xAA };
send_response(RESP_TYPE_OK, test_response2, sizeof(test_response2));
@@ -294,6 +292,9 @@ void handle_command(const uint8_t *frame, uint8_t len) {
case 3u: // M3命令
send_response(RESP_TYPE_OK, s_report_status_ok, sizeof(s_report_status_ok));
return;
case 4u: // M4命令
send_response(RESP_TYPE_OK, s_report_status_err, sizeof(s_report_status_err));
return;
// case 10u: // M10命令
// send_response(RESP_TYPE_OK, s_report_status_ok, sizeof(s_report_status_ok));
// return;

737
Src/i2c.c
View File

@@ -1,9 +1,13 @@
//
// Created by dell on 24-12-20.
// Improved I2C driver with better state machine and error handling
//
#include "i2c.h"
/* Private variables */
static uint8_t i2c_retry_count = 0;
/*!
\brief configure the GPIO ports
\param[in] none
@@ -29,54 +33,81 @@ void i2c_gpio_config(void) {
\brief configure the I2CX interface
\param[in] none
\param[out] none
\retval none
\retval i2c_status_t
*/
void i2c_config(void) {
i2c_status_t i2c_config(void) {
/* configure I2C GPIO */
i2c_gpio_config();
/* enable I2C clock */
rcu_periph_clock_enable(RCU_I2C);
/* configure I2C clock */
i2c_clock_config(I2C0, I2C_SPEED, I2C_DTCY_2);
/* configure I2C address */
i2c_mode_addr_config(I2C0, I2C_I2CMODE_ENABLE, I2C_ADDFORMAT_7BITS, 0xA0);
/* configure I2C address - use 0x00 as master doesn't need specific address */
i2c_mode_addr_config(I2C0, I2C_I2CMODE_ENABLE, I2C_ADDFORMAT_7BITS, I2C_MASTER_ADDRESS);
/* enable I2CX */
i2c_enable(I2C0);
/* enable acknowledge */
i2c_ack_config(I2C0, I2C_ACK_ENABLE);
/* reset retry counter */
i2c_retry_count = 0;
return I2C_STATUS_SUCCESS;
}
/*!
\brief reset I2C bus
\brief reset I2C bus with proper 9-clock recovery
\param[in] none
\param[out] none
\retval none
\retval i2c_status_t
*/
void i2c_bus_reset(void) {
i2c_status_t i2c_bus_reset(void) {
uint8_t i;
/* disable I2C peripheral */
i2c_disable(I2C0);
i2c_deinit(I2C0);
/* configure SDA/SCL for GPIO */
GPIO_BC(I2C_SCL_PORT) |= I2C_SCL_PIN;
GPIO_BC(I2C_SDA_PORT) |= I2C_SDA_PIN;
gpio_output_options_set(I2C_SCL_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, I2C_SCL_PIN);
gpio_output_options_set(I2C_SDA_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, I2C_SDA_PIN);
__NOP();
__NOP();
__NOP();
__NOP();
__NOP();
GPIO_BOP(I2C_SCL_PORT) |= I2C_SCL_PIN;
__NOP();
__NOP();
__NOP();
__NOP();
__NOP();
GPIO_BOP(I2C_SDA_PORT) |= I2C_SDA_PIN;
/* connect I2C_SCL_PIN to I2C_SCL */
/* connect I2C_SDA_PIN to I2C_SDA */
/* configure SDA/SCL as GPIO output for manual control */
gpio_mode_set(I2C_SCL_PORT, GPIO_MODE_OUTPUT, GPIO_PUPD_PULLUP, I2C_SCL_PIN);
gpio_mode_set(I2C_SDA_PORT, GPIO_MODE_OUTPUT, GPIO_PUPD_PULLUP, I2C_SDA_PIN);
gpio_output_options_set(I2C_SCL_PORT, GPIO_OTYPE_OD, GPIO_OSPEED_50MHZ, I2C_SCL_PIN);
gpio_output_options_set(I2C_SDA_PORT, GPIO_OTYPE_OD, GPIO_OSPEED_50MHZ, I2C_SDA_PIN);
/* configure the I2CX interface */
i2c_config();
/* ensure both lines are high initially */
gpio_bit_set(I2C_SCL_PORT, I2C_SCL_PIN);
gpio_bit_set(I2C_SDA_PORT, I2C_SDA_PIN);
delay_10us(I2C_DELAY_10US);
/* generate 9 clock pulses to release any stuck slave */
for (i = 0; i < I2C_RECOVERY_CLOCKS; i++) {
gpio_bit_reset(I2C_SCL_PORT, I2C_SCL_PIN);
delay_10us(I2C_DELAY_10US);
gpio_bit_set(I2C_SCL_PORT, I2C_SCL_PIN);
delay_10us(I2C_DELAY_10US);
}
/* generate stop condition */
gpio_bit_reset(I2C_SDA_PORT, I2C_SDA_PIN);
delay_10us(I2C_DELAY_10US);
gpio_bit_set(I2C_SCL_PORT, I2C_SCL_PIN);
delay_10us(I2C_DELAY_10US);
gpio_bit_set(I2C_SDA_PORT, I2C_SDA_PIN);
delay_10us(I2C_DELAY_10US);
/* reconfigure as I2C pins */
gpio_af_set(I2C_SCL_PORT, I2C_GPIO_AF, I2C_SCL_PIN);
gpio_af_set(I2C_SDA_PORT, I2C_GPIO_AF, I2C_SDA_PIN);
gpio_mode_set(I2C_SCL_PORT, GPIO_MODE_AF, GPIO_PUPD_PULLUP, I2C_SCL_PIN);
gpio_mode_set(I2C_SDA_PORT, GPIO_MODE_AF, GPIO_PUPD_PULLUP, I2C_SDA_PIN);
/* reconfigure the I2CX interface */
return i2c_config();
}
/**
@@ -91,7 +122,13 @@ void i2c_scan(void) {
uint8_t address;
int found_devices = 0;
printf("Scanning I2C bus...\r\n");
// printf("Scanning I2C bus...\r\n");
const char* msg1 = "Scanning I2C bus...\r\n";
for (uint8_t i = 0; msg1[i] != '\0'; i++) {
while (usart_flag_get(I2C_DEBUG_UART, USART_FLAG_TBE) == RESET) {}
usart_data_transmit(I2C_DEBUG_UART, msg1[i]);
}
while (usart_flag_get(I2C_DEBUG_UART, USART_FLAG_TC) == RESET) {}
for (address = 1; address < 127; address++) {
timeout = 0;
@@ -119,7 +156,24 @@ void i2c_scan(void) {
timeout++;
if (timeout < I2C_TIME_OUT) {
i2c_flag_clear(I2C0, I2C_FLAG_ADDSEND);
printf("Found device at 0x%02X\r\n", address);
// printf("Found device at 0x%02X\r\n", address);
const char* msg2_prefix = "Found device at 0x";
for (uint8_t i = 0; msg2_prefix[i] != '\0'; i++) {
while (usart_flag_get(I2C_DEBUG_UART, USART_FLAG_TBE) == RESET) {}
usart_data_transmit(I2C_DEBUG_UART, msg2_prefix[i]);
}
// 发送地址的十六进制表示
uint8_t hex_chars[] = "0123456789ABCDEF";
while (usart_flag_get(I2C_DEBUG_UART, USART_FLAG_TBE) == RESET) {}
usart_data_transmit(I2C_DEBUG_UART, hex_chars[(address >> 4) & 0x0F]);
while (usart_flag_get(I2C_DEBUG_UART, USART_FLAG_TBE) == RESET) {}
usart_data_transmit(I2C_DEBUG_UART, hex_chars[address & 0x0F]);
const char* msg2_suffix = "\r\n";
for (uint8_t i = 0; msg2_suffix[i] != '\0'; i++) {
while (usart_flag_get(I2C_DEBUG_UART, USART_FLAG_TBE) == RESET) {}
usart_data_transmit(I2C_DEBUG_UART, msg2_suffix[i]);
}
while (usart_flag_get(I2C_DEBUG_UART, USART_FLAG_TC) == RESET) {}
found_devices++;
}
@@ -133,344 +187,453 @@ void i2c_scan(void) {
}
if (found_devices == 0) {
printf("No I2C devices found.\r\n");
// printf("No I2C devices found.\r\n");
const char* msg3 = "No I2C devices found.\r\n";
for (uint8_t i = 0; msg3[i] != '\0'; i++) {
while (usart_flag_get(I2C_DEBUG_UART, USART_FLAG_TBE) == RESET) {}
usart_data_transmit(I2C_DEBUG_UART, msg3[i]);
}
while (usart_flag_get(I2C_DEBUG_UART, USART_FLAG_TC) == RESET) {}
} else {
printf("Total %d I2C devices found.\r\n", found_devices);
// printf("Total %d I2C devices found.\r\n", found_devices);
const char* msg4_prefix = "Total ";
for (uint8_t i = 0; msg4_prefix[i] != '\0'; i++) {
while (usart_flag_get(I2C_DEBUG_UART, USART_FLAG_TBE) == RESET) {}
usart_data_transmit(I2C_DEBUG_UART, msg4_prefix[i]);
}
// 发送设备数量
if (found_devices >= 10) {
while (usart_flag_get(I2C_DEBUG_UART, USART_FLAG_TBE) == RESET) {}
usart_data_transmit(I2C_DEBUG_UART, '0' + (found_devices / 10));
}
while (usart_flag_get(I2C_DEBUG_UART, USART_FLAG_TBE) == RESET) {}
usart_data_transmit(I2C_DEBUG_UART, '0' + (found_devices % 10));
const char* msg4_suffix = " I2C devices found.\r\n";
for (uint8_t i = 0; msg4_suffix[i] != '\0'; i++) {
while (usart_flag_get(I2C_DEBUG_UART, USART_FLAG_TBE) == RESET) {}
usart_data_transmit(I2C_DEBUG_UART, msg4_suffix[i]);
}
while (usart_flag_get(I2C_DEBUG_UART, USART_FLAG_TC) == RESET) {}
}
}
uint8_t i2c_write_16bits(uint8_t slave_addr, uint8_t reg_addr, uint8_t data[2]) {
uint8_t state = I2C_START;
/*!
\brief write 16-bit data to I2C device with improved state machine
\param[in] slave_addr: 7-bit slave address
\param[in] reg_addr: register address
\param[in] data: pointer to 2-byte data array
\param[out] none
\retval i2c_status_t
*/
i2c_status_t i2c_write_16bits(uint8_t slave_addr, uint8_t reg_addr, const uint8_t data[2]) {
i2c_state_t state = I2C_STATE_START;
uint16_t timeout = 0;
uint8_t i2c_timeout_flag = 0;
uint8_t data_index = 0;
uint8_t retry_count = 0;
/* enable acknowledge */
/* Parameter validation */
if (data == NULL || slave_addr > 0x7F) {
return I2C_STATUS_INVALID_PARAM;
}
/* Enable acknowledge */
i2c_ack_config(I2C0, I2C_ACK_ENABLE);
while (!(i2c_timeout_flag)) {
while (retry_count < I2C_MAX_RETRY) {
switch (state) {
case I2C_START:
/* i2c master sends start signal only when the bus is idle */
case I2C_STATE_START:
timeout = 0;
/* Wait for bus to be idle */
while (i2c_flag_get(I2C0, I2C_FLAG_I2CBSY) && (timeout < I2C_TIME_OUT)) {
timeout++;
}
if (timeout < I2C_TIME_OUT) {
i2c_start_on_bus(I2C0);
timeout = 0;
state = I2C_SEND_ADDRESS;
} else {
timeout = 0;
state = I2C_START;
#ifdef DEBUG_VERBOES
printf("i2c bus is busy in WRITE BYTE!\n");
#endif
if (timeout >= I2C_TIME_OUT) {
state = I2C_STATE_ERROR;
break;
}
/* Send start condition */
i2c_start_on_bus(I2C0);
state = I2C_STATE_SEND_ADDRESS;
timeout = 0;
break;
case I2C_SEND_ADDRESS:
/* i2c master sends START signal successfully */
case I2C_STATE_SEND_ADDRESS:
/* Wait for start condition to be sent */
while ((!i2c_flag_get(I2C0, I2C_FLAG_SBSEND)) && (timeout < I2C_TIME_OUT)) {
timeout++;
}
if (timeout < I2C_TIME_OUT) {
i2c_master_addressing(I2C0, slave_addr, I2C_TRANSMITTER);
timeout = 0;
state = I2C_CLEAR_ADDRESS_FLAG;
} else {
timeout = 0;
state = I2C_START;
#ifdef DEBUG_VERBOES
printf("i2c master sends start signal timeout in WRITE BYTE!\n");
#endif
if (timeout >= I2C_TIME_OUT) {
state = I2C_STATE_ERROR;
break;
}
/* Send slave address with write bit */
i2c_master_addressing(I2C0, (slave_addr << 1), I2C_TRANSMITTER);
state = I2C_STATE_CLEAR_ADDRESS;
timeout = 0;
break;
case I2C_CLEAR_ADDRESS_FLAG:
/* address flag set means i2c slave sends ACK */
case I2C_STATE_CLEAR_ADDRESS:
/* Wait for address to be acknowledged */
while ((!i2c_flag_get(I2C0, I2C_FLAG_ADDSEND)) && (timeout < I2C_TIME_OUT)) {
timeout++;
}
if (timeout < I2C_TIME_OUT) {
i2c_flag_clear(I2C0, I2C_FLAG_ADDSEND);
timeout = 0;
state = I2C_TRANSMIT_DATA;
} else {
timeout = 0;
state = I2C_START;
#ifdef DEBUG_VERBOES
printf("i2c master clears address flag timeout in WRITE BYTE!\n");
#endif
if (timeout >= I2C_TIME_OUT) {
state = I2C_STATE_ERROR;
break;
}
/* Clear address flag */
i2c_flag_clear(I2C0, I2C_FLAG_ADDSEND);
state = I2C_STATE_TRANSMIT_REG;
timeout = 0;
break;
case I2C_TRANSMIT_DATA:
/* wait until the transmit data buffer is empty */
case I2C_STATE_TRANSMIT_REG:
/* Wait for transmit buffer to be empty */
while ((!i2c_flag_get(I2C0, I2C_FLAG_TBE)) && (timeout < I2C_TIME_OUT)) {
timeout++;
}
if (timeout < I2C_TIME_OUT) {
/* send IIC register address */
i2c_data_transmit(I2C0, reg_addr);
timeout = 0;
} else {
timeout = 0;
state = I2C_START;
#ifdef DEBUG_VERBOES
printf("i2c master sends data timeout in WRITE BYTE!\n");
#endif
if (timeout >= I2C_TIME_OUT) {
state = I2C_STATE_ERROR;
break;
}
/* wait until BTC bit is set */
/* Send register address */
i2c_data_transmit(I2C0, reg_addr);
state = I2C_STATE_TRANSMIT_DATA;
timeout = 0;
data_index = 0;
break;
case I2C_STATE_TRANSMIT_DATA:
/* Wait for byte transfer complete */
while ((!i2c_flag_get(I2C0, I2C_FLAG_BTC)) && (timeout < I2C_TIME_OUT)) {
timeout++;
}
if (timeout < I2C_TIME_OUT) {
/* send register MSB value */
i2c_data_transmit(I2C0, data[0]);
timeout = 0;
} else {
timeout = 0;
state = I2C_START;
#ifdef DEBUG_VERBOES
printf("i2c master sends MSB data timeout in WRITE BYTE!\n");
#endif
if (timeout >= I2C_TIME_OUT) {
state = I2C_STATE_ERROR;
break;
}
/* wait until BTC bit is set */
while ((!i2c_flag_get(I2C0, I2C_FLAG_BTC)) && (timeout < I2C_TIME_OUT)) {
timeout++;
}
if (timeout < I2C_TIME_OUT) {
/* send register LSB value */
i2c_data_transmit(I2C0, data[1]);
/* Send data bytes */
if (data_index < 2) {
i2c_data_transmit(I2C0, data[data_index]);
data_index++;
timeout = 0;
state = I2C_STOP;
/* Stay in this state until all data is sent */
} else {
/* All data sent, proceed to stop */
state = I2C_STATE_STOP;
timeout = 0;
state = I2C_START;
#ifdef DEBUG_VERBOES
printf("i2c master sends LSB data timeout in WRITE BYTE!\n");
#endif
}
/* wait until BTC bit is set */
while ((!i2c_flag_get(I2C0, I2C_FLAG_BTC)) && (timeout < I2C_TIME_OUT)) {
timeout++;
}
if (timeout < I2C_TIME_OUT) {
state = I2C_STOP;
timeout = 0;
} else {
timeout = 0;
state = I2C_START;
#ifdef DEBUG_VERBOES
printf("i2c master sends data timeout in WRITE BYTE!\n");
#endif
}
break;
case I2C_STOP:
/* send a stop condition to I2C bus */
case I2C_STATE_STOP:
/* Send stop condition */
i2c_stop_on_bus(I2C0);
/* i2c master sends STOP signal successfully */
/* Wait for stop condition to complete */
while ((I2C_CTL0(I2C0) & I2C_CTL0_STOP) && (timeout < I2C_TIME_OUT)) {
timeout++;
}
if (timeout < I2C_TIME_OUT) {
timeout = 0;
state = I2C_END;
i2c_timeout_flag = I2C_OK;
} else {
timeout = 0;
state = I2C_START;
#ifdef DEBUG_VERBOES
printf("i2c master sends stop signal timeout in WRITE BYTE!\n");
#endif
if (timeout >= I2C_TIME_OUT) {
state = I2C_STATE_ERROR;
break;
}
break;
default:
state = I2C_START;
i2c_timeout_flag = I2C_OK;
timeout = 0;
#ifdef DEBUG_VERBOES
printf("i2c master sends start signal in WRITE BYTE.\n");
/* Success */
return I2C_STATUS_SUCCESS;
case I2C_STATE_ERROR:
/* Send stop condition to release bus */
i2c_stop_on_bus(I2C0);
/* Increment retry counter */
retry_count++;
if (retry_count >= I2C_MAX_RETRY) {
#ifdef DEBUG_VERBOSE
// printf("I2C write failed after %d retries\r\n", I2C_MAX_RETRY);
const char* msg5_prefix = "I2C write failed after ";
for (uint8_t i = 0; msg5_prefix[i] != '\0'; i++) {
while (usart_flag_get(I2C_DEBUG_UART, USART_FLAG_TBE) == RESET) {}
usart_data_transmit(I2C_DEBUG_UART, msg5_prefix[i]);
}
while (usart_flag_get(I2C_DEBUG_UART, USART_FLAG_TBE) == RESET) {}
usart_data_transmit(I2C_DEBUG_UART, '0' + I2C_MAX_RETRY);
const char* msg5_suffix = " retries\r\n";
for (uint8_t i = 0; msg5_suffix[i] != '\0'; i++) {
while (usart_flag_get(I2C_DEBUG_UART, USART_FLAG_TBE) == RESET) {}
usart_data_transmit(I2C_DEBUG_UART, msg5_suffix[i]);
}
while (usart_flag_get(I2C_DEBUG_UART, USART_FLAG_TC) == RESET) {}
#endif
return I2C_STATUS_TIMEOUT;
}
/* Reset state machine for retry */
state = I2C_STATE_START;
timeout = 0;
data_index = 0;
/* Small delay before retry */
delay_10us(10);
break;
default:
state = I2C_STATE_ERROR;
break;
}
}
return I2C_END;
return I2C_STATUS_TIMEOUT;
}
uint8_t i2c_read_16bits(uint8_t slave_addr, uint8_t reg_addr, uint8_t *data) {
uint8_t state = I2C_START;
uint8_t read_cycle = 0;
/*!
\brief read 16-bit data from I2C device with improved state machine
\param[in] slave_addr: 7-bit slave address
\param[in] reg_addr: register address
\param[out] data: pointer to 2-byte data buffer
\retval i2c_status_t
*/
i2c_status_t i2c_read_16bits(uint8_t slave_addr, uint8_t reg_addr, uint8_t *data) {
i2c_state_t state = I2C_STATE_START;
uint16_t timeout = 0;
uint8_t i2c_timeout_flag = 0;
uint8_t number_of_byte = 2;
uint8_t data_index = 0;
uint8_t retry_count = 0;
bool write_phase = true; /* First phase: write register address */
/* enable acknowledge */
/* Parameter validation */
if (data == NULL || slave_addr > 0x7F) {
return I2C_STATUS_INVALID_PARAM;
}
/* Enable acknowledge */
i2c_ack_config(I2C0, I2C_ACK_ENABLE);
while (!(i2c_timeout_flag)) {
while (retry_count < I2C_MAX_RETRY) {
switch (state) {
case I2C_START:
if (RESET == read_cycle) {
/* i2c master sends start signal only when the bus is idle */
while (i2c_flag_get(I2C0, I2C_FLAG_I2CBSY) && (timeout < I2C_TIME_OUT)) {
timeout++;
}
if (timeout < I2C_TIME_OUT) {
/* whether to send ACK or not for the next byte */
i2c_ackpos_config(I2C0, I2C_ACKPOS_NEXT);
} else {
// i2c_bus_reset();
timeout = 0;
state = I2C_START;
#ifdef DEBUG_VERBOES
printf("i2c bus is busy in READ!\n");
#endif
}
}
/* send the start signal */
i2c_start_on_bus(I2C0);
case I2C_STATE_START:
timeout = 0;
/* Wait for bus to be idle */
while (i2c_flag_get(I2C0, I2C_FLAG_I2CBSY) && (timeout < I2C_TIME_OUT)) {
timeout++;
}
if (timeout >= I2C_TIME_OUT) {
state = I2C_STATE_ERROR;
break;
}
/* Configure ACK position for 2-byte read */
if (!write_phase) {
i2c_ackpos_config(I2C0, I2C_ACKPOS_NEXT);
}
/* Send start condition */
i2c_start_on_bus(I2C0);
state = I2C_STATE_SEND_ADDRESS;
timeout = 0;
state = I2C_SEND_ADDRESS;
break;
case I2C_SEND_ADDRESS:
/* i2c master sends START signal successfully */
case I2C_STATE_SEND_ADDRESS:
/* Wait for start condition to be sent */
while ((!i2c_flag_get(I2C0, I2C_FLAG_SBSEND)) && (timeout < I2C_TIME_OUT)) {
timeout++;
}
if (timeout < I2C_TIME_OUT) {
if (RESET == read_cycle) {
i2c_master_addressing(I2C0, slave_addr, I2C_TRANSMITTER);
state = I2C_CLEAR_ADDRESS_FLAG;
} else {
i2c_master_addressing(I2C0, slave_addr, I2C_RECEIVER);
i2c_ack_config(I2C0, I2C_ACK_DISABLE);
state = I2C_CLEAR_ADDRESS_FLAG;
}
timeout = 0;
} else {
timeout = 0;
state = I2C_START;
read_cycle = RESET;
#ifdef DEBUG_VERBOES
printf("i2c master sends start signal timeout in READ!\n");
#endif
if (timeout >= I2C_TIME_OUT) {
state = I2C_STATE_ERROR;
break;
}
/* Send slave address */
if (write_phase) {
/* Write phase: send address with write bit */
i2c_master_addressing(I2C0, (slave_addr << 1), I2C_TRANSMITTER);
} else {
/* Read phase: send address with read bit */
i2c_master_addressing(I2C0, (slave_addr << 1) | 0x01, I2C_RECEIVER);
/* Disable ACK for last byte */
i2c_ack_config(I2C0, I2C_ACK_DISABLE);
}
state = I2C_STATE_CLEAR_ADDRESS;
timeout = 0;
break;
case I2C_CLEAR_ADDRESS_FLAG:
/* address flag set means i2c slave sends ACK */
case I2C_STATE_CLEAR_ADDRESS:
/* Wait for address to be acknowledged */
while ((!i2c_flag_get(I2C0, I2C_FLAG_ADDSEND)) && (timeout < I2C_TIME_OUT)) {
timeout++;
}
if (timeout < I2C_TIME_OUT) {
i2c_flag_clear(I2C0, I2C_FLAG_ADDSEND);
if ((SET == read_cycle) && (1 == number_of_byte)) {
/* send a stop condition to I2C bus */
if (timeout >= I2C_TIME_OUT) {
state = I2C_STATE_ERROR;
break;
}
/* Clear address flag */
i2c_flag_clear(I2C0, I2C_FLAG_ADDSEND);
if (write_phase) {
state = I2C_STATE_TRANSMIT_REG;
} else {
/* For single byte read, send stop after clearing address */
if (data_index == 1) {
i2c_stop_on_bus(I2C0);
}
timeout = 0;
state = I2C_TRANSMIT_DATA;
} else {
timeout = 0;
state = I2C_START;
read_cycle = RESET;
#ifdef DEBUG_VERBOES
printf("i2c master clears address flag timeout in READ!\n");
#endif
state = I2C_STATE_RECEIVE_DATA;
data_index = 0;
}
timeout = 0;
break;
case I2C_TRANSMIT_DATA:
if (RESET == read_cycle) {
/* wait until the transmit data buffer is empty */
while ((!i2c_flag_get(I2C0, I2C_FLAG_TBE)) && (timeout < I2C_TIME_OUT)) {
case I2C_STATE_TRANSMIT_REG:
/* Wait for transmit buffer to be empty */
while ((!i2c_flag_get(I2C0, I2C_FLAG_TBE)) && (timeout < I2C_TIME_OUT)) {
timeout++;
}
if (timeout >= I2C_TIME_OUT) {
state = I2C_STATE_ERROR;
break;
}
/* Send register address */
i2c_data_transmit(I2C0, reg_addr);
state = I2C_STATE_RESTART;
timeout = 0;
break;
case I2C_STATE_RESTART:
/* Wait for byte transfer complete */
while ((!i2c_flag_get(I2C0, I2C_FLAG_BTC)) && (timeout < I2C_TIME_OUT)) {
timeout++;
}
if (timeout >= I2C_TIME_OUT) {
state = I2C_STATE_ERROR;
break;
}
/* Switch to read phase */
write_phase = false;
state = I2C_STATE_START;
timeout = 0;
break;
case I2C_STATE_RECEIVE_DATA:
if (data_index < 2) {
if (data_index == 1) {
/* Wait for BTC before sending stop for last byte */
while ((!i2c_flag_get(I2C0, I2C_FLAG_BTC)) && (timeout < I2C_TIME_OUT)) {
timeout++;
}
if (timeout >= I2C_TIME_OUT) {
state = I2C_STATE_ERROR;
break;
}
/* Send stop condition before reading last byte */
i2c_stop_on_bus(I2C0);
}
/* Wait for receive buffer not empty */
while ((!i2c_flag_get(I2C0, I2C_FLAG_RBNE)) && (timeout < I2C_TIME_OUT)) {
timeout++;
}
if (timeout < I2C_TIME_OUT) {
/* send the EEPROM's internal address to write to : only one byte address */
i2c_data_transmit(I2C0, reg_addr);
timeout = 0;
} else {
timeout = 0;
state = I2C_START;
read_cycle = RESET;
#ifdef DEBUG_VERBOES
printf("i2c master wait data buffer is empty timeout in READ!\n");
#endif
if (timeout >= I2C_TIME_OUT) {
state = I2C_STATE_ERROR;
break;
}
/* wait until BTC bit is set */
while ((!i2c_flag_get(I2C0, I2C_FLAG_BTC)) && (timeout < I2C_TIME_OUT)) {
timeout++;
}
if (timeout < I2C_TIME_OUT) {
timeout = 0;
state = I2C_START;
read_cycle = SET;
} else {
timeout = 0;
state = I2C_START;
read_cycle = RESET;
#ifdef DEBUG_VERBOES
printf("i2c master sends register address timeout in READ!\n");
#endif
/* Read data byte */
data[data_index] = i2c_data_receive(I2C0);
data_index++;
timeout = 0;
if (data_index >= 2) {
state = I2C_STATE_STOP;
}
} else {
while (number_of_byte) {
timeout++;
if (2 == number_of_byte) {
/* wait until BTC bit is set */
while (!i2c_flag_get(I2C0, I2C_FLAG_BTC));
/* send a stop condition to I2C bus */
i2c_stop_on_bus(I2C0);
}
/* wait until RBNE bit is set */
if (i2c_flag_get(I2C0, I2C_FLAG_RBNE)) {
/* read a byte from the EEPROM */
*data = i2c_data_receive(I2C0);
/* point to the next location where the byte read will be saved */
data++;
/* decrement the read bytes counter */
number_of_byte--;
timeout = 0;
}
if (timeout > I2C_TIME_OUT) {
timeout = 0;
state = I2C_START;
read_cycle = 0;
#ifdef DEBUG_VERBOES
printf("i2c master sends data timeout in READ!\n");
#endif
}
}
timeout = 0;
state = I2C_STOP;
state = I2C_STATE_STOP;
}
break;
case I2C_STOP:
/* i2c master sends STOP signal successfully */
case I2C_STATE_STOP:
/* Wait for stop condition to complete */
while ((I2C_CTL0(I2C0) & I2C_CTL0_STOP) && (timeout < I2C_TIME_OUT)) {
timeout++;
}
if (timeout < I2C_TIME_OUT) {
timeout = 0;
state = I2C_END;
i2c_timeout_flag = I2C_OK;
} else {
timeout = 0;
state = I2C_START;
read_cycle = 0;
#ifdef DEBUG_VERBOES
printf("i2c master sends stop signal timeout in READ!\n");
#endif
if (timeout >= I2C_TIME_OUT) {
state = I2C_STATE_ERROR;
break;
}
break;
default:
state = I2C_START;
read_cycle = 0;
i2c_timeout_flag = I2C_OK;
timeout = 0;
#ifdef DEBUG_VERBOES
printf("i2c master sends start signal in READ.\n");
/* Success */
return I2C_STATUS_SUCCESS;
case I2C_STATE_ERROR:
/* Send stop condition to release bus */
i2c_stop_on_bus(I2C0);
/* Increment retry counter */
retry_count++;
if (retry_count >= I2C_MAX_RETRY) {
#ifdef DEBUG_VERBOSE
// printf("I2C read failed after %d retries\r\n", I2C_MAX_RETRY);
const char* msg6_prefix = "I2C read failed after ";
for (uint8_t i = 0; msg6_prefix[i] != '\0'; i++) {
while (usart_flag_get(I2C_DEBUG_UART, USART_FLAG_TBE) == RESET) {}
usart_data_transmit(I2C_DEBUG_UART, msg6_prefix[i]);
}
while (usart_flag_get(I2C_DEBUG_UART, USART_FLAG_TBE) == RESET) {}
usart_data_transmit(I2C_DEBUG_UART, '0' + I2C_MAX_RETRY);
const char* msg6_suffix = " retries\r\n";
for (uint8_t i = 0; msg6_suffix[i] != '\0'; i++) {
while (usart_flag_get(I2C_DEBUG_UART, USART_FLAG_TBE) == RESET) {}
usart_data_transmit(I2C_DEBUG_UART, msg6_suffix[i]);
}
while (usart_flag_get(I2C_DEBUG_UART, USART_FLAG_TC) == RESET) {}
#endif
return I2C_STATUS_TIMEOUT;
}
/* Reset state machine for retry */
state = I2C_STATE_START;
write_phase = true;
timeout = 0;
data_index = 0;
/* Small delay before retry */
delay_10us(10);
break;
default:
state = I2C_STATE_ERROR;
break;
}
}
return I2C_END;
return I2C_STATUS_TIMEOUT;
}
/*!
\brief get status string for debugging
\param[in] status: i2c_status_t value
\param[out] none
\retval const char* status string
*/
const char* i2c_get_status_string(i2c_status_t status) {
switch (status) {
case I2C_STATUS_SUCCESS:
return "SUCCESS";
case I2C_STATUS_TIMEOUT:
return "TIMEOUT";
case I2C_STATUS_NACK:
return "NACK";
case I2C_STATUS_BUS_BUSY:
return "BUS_BUSY";
case I2C_STATUS_ERROR:
return "ERROR";
case I2C_STATUS_INVALID_PARAM:
return "INVALID_PARAM";
default:
return "UNKNOWN";
}
}

View File

@@ -38,6 +38,8 @@ OF SUCH DAMAGE.
#include "led.h"
#include "command.h"
#include <stdio.h>
#include "i2c.h"
#include "board_config.h"
bool g_status_switch = false;
@@ -56,6 +58,7 @@ int main(void)
led_init();
#ifdef DEBUG_VERBOSE
char hello_world[] = {"Hello World!"};
for (uint8_t i = 0; i < sizeof(hello_world); i++)
@@ -65,6 +68,18 @@ int main(void)
}
while (usart_flag_get(RS485_PHY, USART_FLAG_TC) == RESET) {}
#endif
i2c_config();
// i2c_bus_reset();
#ifdef DEBUG_VERBOSE
i2c_scan();
#endif
while(1){
command_process();

View File

@@ -11,7 +11,7 @@
\retval none
*/
void soft_i2c_delay(void) {
delay_us(20); // Adjust delay as needed
delay_10us(2); // Adjust delay as needed
/* delay to freq
* 15KHz: delay_us(20);
* 65KHz: delay_us(1);