light-sensor.py 933 B

1234567891011121314151617181920212223242526272829303132
  1. from sys import stdout
  2. from machine import ADC,Pin
  3. import uasyncio
  4. def led_s():
  5. cn1 = Pin(18, Pin.OUT)
  6. init_value = -1
  7. pin_value = 0
  8. def ctrl_led(current_value):
  9. nonlocal init_value,pin_value
  10. if init_value == -1:
  11. init_value = current_value
  12. print('led init_value:', init_value)
  13. elif current_value > init_value + 3000:
  14. cn1.off()
  15. else:
  16. cn1.on()
  17. return ctrl_led
  18. async def sensor():
  19. adc = ADC(Pin(34), atten=ADC.ATTN_11DB) # create an ADC object acting on a pin
  20. ctrl_led = led_s()
  21. while True:
  22. val = adc.read_u16() # read a raw analog value in the range 0-65535
  23. ctrl_led(val)
  24. wdat = 'val:{}'.format(val)
  25. print(wdat, end='\x08' * len(wdat))
  26. await uasyncio.sleep_ms(50)
  27. print(' ' * len(wdat), end='\x08' * len(wdat))
  28. if __name__ == '__main__':
  29. uasyncio.run(sensor())