I am a totally new comer for MicroPython.
Recently I connected successfully a MH-Z19B sensor to my PICO via UART. The CO2 level as result will then be displayed on a SSD1306 screen. The codes work fine. So I decided to save the it as main.py to have it running automatically once it is connected to external power source (USB).
Then the strange thing happened. I got no sensor reading. The led in MH-Z19B blinks, no value can be read. I tried everything: change all wires, change pins, use additional 5V power supply for MH-Z19B and also tried it on a ESP32, same results... But once I connect the board via USB to a computer and run main.py in Thonny (IDE which I use) there, it works again....
In order understand what happened to sensor reading, I added a command to print what was read and found out that:
if the program (main.py) was triggered in Thonny manually, I got such reading:
b'\xff\x86\x01\xf4;\x00\x00\x00J', wich is according to MH-Z19B data sheet correct.
If I connected to PICO board to external USB power supply (cell phone charger) and main.py runs automatically by itself, the reading looks so: b'\x00\x00F\xff\x86\x01\xf4?\x00'.
For any hints or suggestions I'd really appreciate!
Below my codes:
Code: Select all
import machine import time import ssd1306 tx_pin=machine.Pin(4) rx_pin=machine.Pin(5) sensor=machine.UART(1, baudrate=9600, bits=8, parity=None,stop=1,tx=tx_pin, rx=rx_pin) i2c = machine.I2C(1,scl=machine.Pin(19), sda=machine.Pin(18)) oled_width = 128 oled_height = 64 oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c) def is_valid(buf): if buf is None or buf != 0xFF or buf != 0x86: return False i = 1 checksum = 0x00 while i < 8: checksum += buf[i] % 256 i += 1 checksum = ~checksum & 0xFF checksum += 1 while True: sensor.write(b'\xff\x01\x86\x00\x00\x00\x00\x00\x79') time.sleep(2) buf = sensor.read(9) if is_valid(buf) == False: oled.text("Wrong sensor value!", 0, 10) oled.show() break else: co2 = buf * 256 + buf text1="CO2 level:" text2=str(co2) + " PPM" oled.text(text1, 0, 20) oled.text(text2, 0, 40) oled.show() time.sleep(5) oled.fill(0) oled.show()