Eliminem les pauses bloquejants (sleep) utilitzant ticks_ms y ticks_diff
Proposta de Copilot:
from machine import Pin, ADC
from time import ticks_us, ticks_diff
led = Pin(23, Pin.OUT)
sensor = ADC(Pin(34))
sensor.atten(ADC.ATTN_11DB) # per llegir en tot el rang de 0 a 3.3 V
sensor.width(ADC.WIDTH_12BIT) # per ajustar la comversió AD a 12 bits (valors fins a 4095)
pols = 0
missatge = ""
start_time = ticks_us()
step = 0
def recupera():
global pols, missatge, start_time, step
if step == 0:
led.off()
start_time = ticks_us()
step = 1
elif step == 1 and ticks_diff(ticks_us(), start_time) >= 280:
mesura = sensor.read()
start_time = ticks_us()
step = 2
elif step == 2 and ticks_diff(ticks_us(), start_time) >= 40:
led.on()
start_time = ticks_us()
step = 3
elif step == 3 and ticks_diff(ticks_us(), start_time) >= 9680:
tensio = mesura * (3.3 / 4095) # V
pols = (tensio - 0.9) / 5 # mg/m3
pols = pols * 1000 # ug/m3
if pols < 35:
missatge = 'QUALITAT EXCEL·LENT'
elif pols < 75:
missatge = 'QUALITAT BONA'
elif pols < 115:
missatge = 'CONTAMINACIO LLEU'
elif pols < 150:
missatge = 'CONTAMINACIO MODERADA'
elif pols < 250:
missatge = 'CONTAMINACIO FORTA'
else:
missatge = 'CONTAMINACIO GREU'
step = 0
while True:
recupera()
print('Concentració de partícules:', pols, 'ug/m3')
print('Missatge:', missatge)
while ticks_diff(ticks_us(), start_time) < 1000000: # Esperar 1 segundo de manera no bloqueante
pass
start_time = ticks_us()