Files
esp32c3-smart-scale/components/sgm8031_use/sgm8031_use.c

86 lines
2.7 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include <stdio.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "sgm8031_use.h"
#include "sgm58031.h"
static const char *TAG = "sgm8031_use";
static i2c_dev_t s_device;
static bool s_initialized = false;
esp_err_t sgm8031_use_init(int i2c_port, int sda_pin, int scl_pin)
{
// Initialize I2C driver if not already done. (i2cdev_init doesn't hurt to call multiple times)
ESP_ERROR_CHECK_WITHOUT_ABORT(i2cdev_init());
memset(&s_device, 0, sizeof(i2c_dev_t));
// 使用 GND 地址针脚
esp_err_t err = sgm58031_init_desc(&s_device, SGM58031_ADDR_GND, i2c_port, sda_pin, scl_pin);
if (err != ESP_OK) {
ESP_LOGE(TAG, "SGM58031 init desc failed");
return err;
}
uint8_t id, version;
if (sgm58031_get_chip_id(&s_device, &id, &version) == ESP_OK) {
ESP_LOGI(TAG, "SGM58031 Found! ID: %d, Version: %d", id, version);
} else {
ESP_LOGW(TAG, "Failed to get SGM58031 Chip ID");
}
// 设置为单次转换模式,以便我们在不同通道间切换
ESP_ERROR_CHECK_WITHOUT_ABORT(sgm58031_set_conv_mode(&s_device, SGM58031_CONV_MODE_SINGLE_SHOT));
ESP_ERROR_CHECK_WITHOUT_ABORT(sgm58031_set_data_rate(&s_device, SGM58031_DATA_RATE_100)); // 适当的速度 100SPS
s_initialized = true;
return ESP_OK;
}
// 内部函数读取指定通道和增益下的ADC值
static esp_err_t read_channel(sgm58031_mux_t mux, sgm58031_gain_t gain, int16_t *out_val)
{
if (!s_initialized) return ESP_ERR_INVALID_STATE;
// 配置 MUX 和 增益
esp_err_t err = sgm58031_set_input_mux(&s_device, mux);
if (err != ESP_OK) return err;
err = sgm58031_set_gain(&s_device, gain);
if (err != ESP_OK) return err;
// 启动单次转换
err = sgm58031_start_conversion(&s_device);
if (err != ESP_OK) return err;
// 直接延时足够的时间跳过 busy 检查 (8 SPS 时大约 125ms100SPS只需 10ms我们延时 50ms 保底)
vTaskDelay(pdMS_TO_TICKS(50));
// 读取值
return sgm58031_get_value(&s_device, out_val);
}
esp_err_t sgm8031_use_read_data(scale_data_t *out_data)
{
if (out_data == NULL) return ESP_ERR_INVALID_ARG;
int16_t weight_raw = 0;
esp_err_t err = read_channel(SGM58031_MUX_AIN0_AIN1, SGM58031_GAIN_0V256, &weight_raw);
if (err != ESP_OK) return err;
out_data->weight = (float)weight_raw; // 现在直接输出原始值供外部处理
return ESP_OK;
}
esp_err_t sgm8031_use_tare(void)
{
// 该函数已被外部 controller 取代,仅作为兼容占位或直接废弃
return ESP_OK;
}
void sgm8031_use_set_calibration_factor(float factor)
{
// 该函数已被外部 controller 取代
}