class DHT11_PIO: def __init__(self, data_pin): pin = Pin(data_pin, Pin.IN, Pin.PULL_UP) self.sm = StateMachine(0) self.sm.init(DHT11, freq=500000, set_base=pin, in_base=pin) self.start = SmAddr(0) def read(self): # Reset the state machine to start a fresh transaction SmRestart(0) SmExec(0, self.start) # Activate the state machine and then sleep until it should be complete self.sm.active(1) utime.sleep_ms(20) self.sm.active(0) # Exception if the amount of data is wrong if SmRxLevel(0) != 2: while SmRxLevel(0): self.sm.get() raise Timeout() # Read back the data from the Rx FIFO as data = self.sm.get() data = (data << 20) + self.sm.get() # Calculate and check checksum if (sum(data >> i * 8 for i in range(1, 5)) - data) & 255: raise BadChecksum() return self.decode(data) def decode(self, data): humidity = (data >> 32 ) & 255 #DHT11 provides integer humidity (no decimal part) temperature = ( data >> 16 ) & 255 #DHT11 provides signed integer temperature (no decimal part) return humidity, temperature
# Function for core1 to execute to write to the given UART. def core1_task(uart, text): uart.write(text) # Set up the hard UART we're going to use to print characters. uart = UART(1, UART_BAUD, tx=HARD_UART_TX_PIN) for pio_prog in ("uart_rx_mini", "uart_rx"): # Set up the state machine we're going to use to receive the characters. sm = StateMachine( 0, globals()[pio_prog], freq=8 * UART_BAUD, in_base=PIO_RX_PIN, # For WAIT, IN jmp_pin=PIO_RX_PIN, # For JMP ) sm.irq(handler) sm.active(1) # Tell core 1 to print some text to UART 1 text = "Hello, world from PIO, using {}!".format(pio_prog) _thread.start_new_thread(core1_task, (uart, text)) # Echo characters received from PIO to the console. for i in range(len(text)): print(chr(sm.get() >> 24), end="") print()