#include "ads1115.h"
#include "common.h"
#include "softiic.h"

#define ADS1115_ADDR 0x48

// I2C写寄存器
static void ads1115_write_register(uint8_t reg, uint16_t val) {
    i2c_start();
    i2c_write_byte((ADS1115_ADDR << 1) | 0);
    i2c_write_byte(reg);
    i2c_write_byte((val >> 8) & 0xFF);
    i2c_write_byte(val & 0xFF);
    i2c_stop();
}

// 读取转换寄存器
static uint16_t ads1115_read_conversion() {
    uint16_t result = 0;
    i2c_start();
    i2c_write_byte((ADS1115_ADDR << 1) | 0);
    i2c_write_byte(0x00);
    i2c_start();
    i2c_write_byte((ADS1115_ADDR << 1) | 1);
    uint8_t msb = i2c_read_byte(1);
    uint8_t lsb = i2c_read_byte(0);
    i2c_stop();
    result = (msb << 8) | lsb;
    return result;
}

// 读取某个单端通道电压，channel = 0~3
float ads1115_read_channel(int channel) {
    if (channel < 0 || channel > 3)
        return -1.0f;

    uint16_t config = 0x8000; // OS=1，启动转换
    config |= ((4 + channel) << 12); // 单端MUX
    config |= (0x00 << 9);   // PGA ±6.144V
    config |= (1 << 8);      // 单次模式
    config |= (0x04 << 5);   // 128SPS
    config |= 0x03;          // 禁用比较器

    ads1115_write_register(0x01, config);
    delay(10); // 等待转换

    int16_t val = (int16_t)ads1115_read_conversion();
    float voltage = val * 6.144f / 32768.0f;
    return voltage;
 
}
