88 lines
3.0 KiB
C
88 lines
3.0 KiB
C
#include "ads8864.h"
|
||
#include "gpio.h"
|
||
#include "bsp/spi.h"
|
||
#include <string.h>
|
||
#include "component/user_math.h"
|
||
/* Private variables --------------------------------------------------------- */
|
||
// static Ads8864_t ads8864 = {0}; // 全局的ADC数据结构体
|
||
|
||
/* Private function prototypes ----------------------------------------------- */
|
||
static uint16_t Ads8864_Read_Internal(void);
|
||
static void Ads8864_Update_Filtered_Data(void);
|
||
|
||
/* Exported functions ------------------------------------------------------- */
|
||
/**
|
||
* @brief ADS8864初始化函数
|
||
* @note 初始化ADC相关引脚
|
||
* @retval None
|
||
*/
|
||
// void ads8864_Init(void) {
|
||
// HAL_GPIO_WritePin(GPIOB, DIN_Pin, GPIO_PIN_SET); // 设置DIN引脚为高电平
|
||
// HAL_GPIO_WritePin(GPIOB, CONVST_Pin, GPIO_PIN_RESET); // 设置CS引脚为低电平
|
||
// }
|
||
int8_t ads8864_Init(Ads8864_t *ads8864) {
|
||
HAL_GPIO_WritePin(GPIOB, DIN_Pin, GPIO_PIN_SET); // 设置DIN引脚为高电平
|
||
HAL_GPIO_WritePin(GPIOB, CONVST_Pin, GPIO_PIN_RESET); // 设置CS引脚为低电平
|
||
memset(ads8864, 0, sizeof(Ads8864_t)); // 初始化结构体
|
||
return 0; // 初始化成功
|
||
}
|
||
/**
|
||
* @brief 读取ADS8864 ADC数据
|
||
* @note 通过SPI接口读取ADC转换结果,并更新滤波数据
|
||
* @retval uint16_t 返回滤波后的ADC数据
|
||
*/
|
||
int8_t Ads8864_Read(Ads8864_t *ads8864) {
|
||
// 读取原始数据
|
||
uint16_t raw_data = Ads8864_Read_Internal();
|
||
|
||
// 更新原始数据缓冲区
|
||
for (int i = 9; i > 0; i--) {
|
||
ads8864->raw.adc_data[i] = ads8864->raw.adc_data[i - 1];
|
||
}
|
||
ads8864->raw.adc_data[0] = raw_data;
|
||
|
||
// 更新滤波数据
|
||
Ads8864_Update_Filtered_Data();
|
||
// 计算距离
|
||
ads8864->filtered.distance = Adc_to_Distance(ads8864->filtered.adc_data); // 计算距离
|
||
|
||
return 0;
|
||
}
|
||
|
||
/* Private functions --------------------------------------------------------- */
|
||
/**
|
||
* @brief 内部函数:读取ADS8864数据
|
||
* @note 通过SPI通信获取ADC数据
|
||
* @retval uint16_t 返回读取的ADC数据
|
||
*/
|
||
static uint16_t Ads8864_Read_Internal(void) {
|
||
uint8_t rx_data[2] = {0}; // 接收数据缓冲区
|
||
|
||
// 获取 SPI 句柄
|
||
SPI_HandleTypeDef *hspi = BSP_SPI_GetHandle(BSP_SPI_ADC);
|
||
if (hspi == NULL) {
|
||
return 0; // 如果句柄为空,返回 0
|
||
}
|
||
|
||
HAL_GPIO_WritePin(GPIOB, CONVST_Pin, GPIO_PIN_RESET); // 设置CS引脚为低电平
|
||
HAL_Delay(1); // 延时 1 毫秒
|
||
HAL_SPI_Receive(hspi, rx_data, sizeof(rx_data), HAL_MAX_DELAY); // SPI接收数据
|
||
HAL_GPIO_WritePin(GPIOB, CONVST_Pin, GPIO_PIN_SET); // 设置CS引脚为高电平
|
||
|
||
return (rx_data[0] << 8) | rx_data[1]; // 合并接收数据并返回
|
||
}
|
||
|
||
/**
|
||
* @brief 更新滤波后的ADC数据
|
||
* @note 使用简单的平均滤波算法
|
||
* @retval None
|
||
*/
|
||
static void Ads8864_Update_Filtered_Data(void) {
|
||
uint32_t sum = 0;
|
||
|
||
// 计算原始数据的平均值
|
||
for (int i = 0; i < 10; i++) {
|
||
sum += ads8864.raw.adc_data[i];
|
||
}
|
||
ads8864.filtered.adc_data = (uint16_t)(sum / 10);
|
||
} |