from machine import ADC, Pin
import time

class COSensor:
    def __init__(self, pin_no=26):
        self.adc = ADC(Pin(pin_no))
        self.ro = 10.0 # Baseline resistance

    def calibrate(self):
        print("Calibrating CO Sensor (Fresh Air)...")
        total = 0
        for _ in range(50):
            total += self.adc.read_u16()
            time.sleep(0.05)
        avg_raw = total / 50
        v_out = (avg_raw * 3.3) / 65535
        if v_out > 0:
            # Calculate RO based on fresh air ratio
            self.ro = ((3.3 / v_out) - 1) * 10 / 27.0
        print(f"Calibration finished. RO: {self.ro:.2f}")

    def read_ppm(self):
        raw = self.adc.read_u16()
        v_out = (raw * 3.3) / 65535
        if v_out < 0.1: return 0.0
        rs = ((3.3 / v_out) - 1) * 10
        ratio = rs / self.ro
        # MQ-7 curve formula
        ppm = 100 * pow(ratio, -1.5)
        return ppm