pimoroni-pico/micropython/examples/pico_explorer/thermometer.py

64 lines
2.0 KiB
Python
Raw Normal View History

2021-02-14 18:24:01 +00:00
# This example takes the temperature from the Pico's onboard temperature sensor, and displays it on Pico Explorer, along with a little pixelly graph.
# It's based on the thermometer example in the "Getting Started with MicroPython on the Raspberry Pi Pico" book, which is a great read if you're a beginner!
import st7789
2021-04-15 09:21:27 +01:00
import machine
import utime
2021-02-14 18:24:01 +00:00
# Pico Explorer boilerplate
display = st7789.ST7789(st7789.DISPLAY_PICO_EXPLORER, rotate=0)
display.set_palette_mode(st7789.PALETTE_USER)
display.set_backlight(1.0)
WIDTH, HEIGHT = display.get_bounds()
2021-02-14 18:24:01 +00:00
# reads from Pico's temp sensor and converts it into a more manageable number
2021-04-15 09:21:27 +01:00
sensor_temp = machine.ADC(4)
conversion_factor = 3.3 / (65535)
2021-02-14 18:24:01 +00:00
BLACK = display.create_pen(0, 0, 0)
WHITE = display.create_pen(255, 255, 255)
RED = display.create_pen(255, 0, 0)
GREEN = display.create_pen(0, 255, 0)
BLUE = display.create_pen(0, 0, 255)
2021-02-14 18:24:01 +00:00
i = 0
while True:
# the following two lines do some maths to convert the number from the temp sensor into celsius
reading = sensor_temp.read_u16() * conversion_factor
2021-04-15 09:21:27 +01:00
temperature = round(27 - (reading - 0.706) / 0.001721)
2021-02-14 18:24:01 +00:00
# this if statement clears the display once the graph reaches the right hand side of the display
if i >= WIDTH + 1:
2021-02-14 18:24:01 +00:00
i = 0
display.set_pen(BLACK)
2021-02-14 18:24:01 +00:00
display.clear()
# chooses a pen colour based on the temperature
display.set_pen(GREEN)
2021-02-14 18:24:01 +00:00
if temperature > 20:
display.set_pen(RED)
2021-02-14 18:24:01 +00:00
if temperature < 13:
display.set_pen(BLUE)
2021-04-15 09:21:27 +01:00
2021-02-14 18:24:01 +00:00
# draws the reading as a tall, thin rectangle
display.rectangle(i, HEIGHT - (temperature * 6), 6, HEIGHT)
2021-04-15 09:21:27 +01:00
2021-02-14 18:24:01 +00:00
# draws a white background for the text
display.set_pen(WHITE)
2021-02-14 18:24:01 +00:00
display.rectangle(1, 1, 65, 33)
2021-04-15 09:21:27 +01:00
2021-02-14 18:24:01 +00:00
# writes the reading as text in the white rectangle
display.set_pen(BLACK)
2021-04-15 09:21:27 +01:00
display.text("{:.0f}".format(temperature) + "c", 3, 3, 0, 4)
2021-02-14 18:24:01 +00:00
# time to update the display
display.update()
2021-04-15 09:21:27 +01:00
2021-02-14 18:24:01 +00:00
# waits for 5 seconds
2021-04-15 09:21:27 +01:00
utime.sleep(5)
2021-02-14 18:24:01 +00:00
# the next tall thin rectangle needs to be drawn 6 pixels to the right of the last one
2021-04-15 09:21:27 +01:00
i += 6