import time
import board
import analogio
import digitalio
import math

#Configuración de hardware

pot = analogio.AnalogIn(board.GP26)
NTC = analogio.AnalogIn(board.GP28)
ldr = analogio.AnalogIn(board.GP27)
rele = digitalio.DigitalInOut(board.GP18)
rele.direction = digitalio.Direction.OUTPUT

#Funciones

def potenciometro():
 raw = pot.value
 volts = (raw * 3.30) / 65536
 return volts, raw

def imprimir_potenciometro():
 for i in range(20):
  volts, raw = potenciometro()
  print("Dec = {:5d} V = {:5.2f}V".format(raw, volts))
  time.sleep(0.2)

imprimir_potenciometro()

"""
def fotoresistencia():
 raw = ldr.value
 volts = (raw * 3.30) / 65536
 porcentaje_luz = (volts / 3.3) * 100
 return porcentaje_luz, raw, volts

def rele_control(volts):
 if volts > 1.65: 
   rele.value = True
   estado_rele = "On"
 else:
   rele.value = False
   estado_rele = "Off"
 return estado_rele

def imprimir_fotoresistencia():
 for i in range(20):
  porcentaje_luz, raw, volts = fotoresistencia()
  estado_rele = rele_control(volts)
  print("Dec = {:5d}  % Luz = {:5.2f}%  Relé = {}".format(raw, porcentaje_luz, estado_rele))
  time.sleep(0.2)

imprimir_fotoresistencia()


def temperatura():
 Vin = 3.30
 Ro = 10000  # Resistencia de 10k
 # Constantes de Steinhart
 A = 0.001129148
 B = 0.00023415
 C = 0.0000000876741

 Vout = (3.30 / 65535) * NTC.value

 # Calcular Resistencia Rt
 Rt = (Vout * Ro) / (Vin - Vout)  # Rt = 10k dado TempC = 25

 # Ecuación de Steinhart
 TempK = 1 / (A + (B * math.log(Rt)) + C * math.pow(math.log(Rt), 3))

 # Convertir de Kelvin a Celsius
 TempC = TempK - 273.15
 return TempC, Vout

def imprimir_temperatura():
 for i in range(20):
  tempC, Vout = temperatura()
  print("Vout = {:5.2f}V  Temp = {:5.2f}°C".format(Vout, tempC))
  time.sleep(0.2)

imprimir_temperatura()

def imprimir_sensores():
 for i in range(20):
 # Potenciómetro
  volts_pot, _ = potenciometro()  
 # Fotoresistencia
  porcentaje_luz, _, _ = fotoresistencia()  
 # Termistor 
  tempC, _ = temperatura()  
  print("V = {:5.2f}V, Luz = {:5.2f}%, Temp = {:5.2f}°C".format(volts_pot, porcentaje_luz, tempC))
  time.sleep(0.2)  

imprimir_sensores()
"""
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT
pico:GP0
pico:GP1
pico:GND.1
pico:GP2
pico:GP3
pico:GP4
pico:GP5
pico:GND.2
pico:GP6
pico:GP7
pico:GP8
pico:GP9
pico:GND.3
pico:GP10
pico:GP11
pico:GP12
pico:GP13
pico:GND.4
pico:GP14
pico:GP15
pico:GP16
pico:GP17
pico:GND.5
pico:GP18
pico:GP19
pico:GP20
pico:GP21
pico:GND.6
pico:GP22
pico:RUN
pico:GP26
pico:GP27
pico:GND.7
pico:GP28
pico:ADC_VREF
pico:3V3
pico:3V3_EN
pico:GND.8
pico:VSYS
pico:VBUS
ldr1:VCC
ldr1:GND
ldr1:DO
ldr1:AO
pot1:GND
pot1:SIG
pot1:VCC
ntc1:GND
ntc1:VCC
ntc1:OUT
NOCOMNCVCCGNDINLED1PWRRelay Module
relay1:VCC
relay1:GND
relay1:IN
relay1:NC
relay1:COM
relay1:NO
led1:A
led1:C
r1:1
r1:2