import board
from time import sleep
import adafruit_dht
from adafruit_onewire.bus import OneWireBus
from adafruit_ds18x20 import DS18X20
import busio
import adafruit_bme680
from analogio import AnalogIn

# BME680
i2c = busio.I2C(board.SCL, board.SDA)
sensor = adafruit_bme680.Adafruit_BME680_I2C(i2c)
x = sensor.temperature  # Throw away

# TMP36
A2_in = AnalogIn(board.A2)
y = A2_in.value  # Throw away the first analog reading

# DHT22
dht = adafruit_dht.DHT22(board.D2)

# DS18B20
ow_bus = OneWireBus(board.D7)
ds18 = DS18X20(ow_bus, ow_bus.scan()[0])

def get_TMP36():
    x = A2_in.value
    # Calculate temperature
    millivolts = x * (3.275 * 1000 / 65535)
    tempC = (millivolts - 500) / 10
    return tempC

def get_TMP36B():
    list = []
    readings = 15
    for i in range(readings):
        C = get_TMP36()  # Get temp in deg C
        list.append(C) # append to growing list
        sleep(0.05)
    list.sort()  # Sorts low to high
    # Average of "low-middle"
    t = 0
    for i in range(5,10):
        t = t + list[i]
    mean = t/5
    return mean

def get_BME680():
    return sensor.temperature


def get_dht22():
    try:
        dhtC = dht.temperature

    except RuntimeError as e:
        # Print reading error
        print("DHT read error: ", e.args)
    return dhtC

while True:
    tmp = int(get_TMP36B() * 10) /10.0
    bme = int(get_BME680() * 10) /10.0
    dht22 = int(get_dht22() * 10) /10.0
    ds18B20 = int(ds18.temperature * 10) /10.0
    print(tmp, ",", ds18B20, ",", dht22, ",", bme)
    sleep(19)