import machine
import utime
import dht
import ustruct
# === Sensor Setup ===
dht_pin = machine.Pin(15)
dht_sensor = dht.DHT22(dht_pin)
pir = machine.Pin(16, machine.Pin.IN)
light_adc = machine.ADC(26)  # AO pin ke GP26 (ADC0)
# === SPI Setup (Transmitter) ===
spi = machine.SPI(0, baudrate=1000000, polarity=0, phase=0)
cs = machine.Pin(17, machine.Pin.OUT)
cs.value(1)
def read_sensors():
    dht_sensor.measure()
    suhu = dht_sensor.temperature()
    rh = dht_sensor.humidity()
    light_raw = light_adc.read_u16()  # 0–65535
    lux_percent = (light_raw / 65535) * 100
    gerak = pir.value()
    return suhu, rh, lux_percent, gerak
while True:
    suhu, rh, lux, gerak = read_sensors()
    # Kirim sebagai 4 float (4x4 byte = 16 byte)
    data = ustruct.pack('ffff', suhu, rh, lux, float(gerak))
    cs.value(0)
    spi.write(data)
    cs.value(1)
    print("TX -> Suhu: {:.1f} C | RH: {:.1f}% | Lux: {:.1f} | Gerak: {}".format(
        suhu, rh, lux, "Ya" if gerak else "Tidak"))
    utime.sleep(2)