I will be getting my Raspberry pi pico here in a few days and want to connect a DS18B20 and use MicroPython. I have a project the uses RPi zero w and Python3.9. Since obviously, the pico does not use an os, is there a way to read a 1-wire device? Or do I need to switch to a different method for reading temperature? I know that the ESP32 port has a class for it. Any help would be appreciated. Thank you in advance.
-
1You could use adafruit mycropython fork called circuitpython - circuitpython.org/board/raspberry_pi_pico and then you can use circuitpython onewire and ds18b20 libraries learn.adafruit.com/…– Jaromanda XJan 28, 2021 at 23:01
-
1Actually, ignore that ... pico micropython has libraries you need github.com/raspberrypi/micropython/tree/pico/drivers/onewire– Jaromanda XJan 29, 2021 at 0:03
-
@JaromandaX, I try Steve Robillard's answer using JaromandaX's link and see what happens. Thank you and will update after this weekend and upvote both if it works.– Kelby CriswellFeb 3, 2021 at 18:05
2 Answers
Yes, you can use a DS18B20 with MicrPython on the Pico. All the required modules are included. The following is based on this MicroPython tutorial from Random Nerd Tutorials.
Hardware
To wire the sensor to your Pico:
- Connect the sensor's ground to one of the ground pins on the Pico.
- Connect the sensor's VCC pin to the Pico's 3.3V(out) pin.
- Connect the Sensor's data pin to the Pico's GPIO4
Software
- Create a new file in Thonny.
- Paste the following code into your new file:
import machine, onewire, ds18x20, time
ds_pin = machine.Pin(4)
ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))
roms = ds_sensor.scan()
print('Found DS devices: ', roms)
while True:
ds_sensor.convert_temp()
time.sleep_ms(750)
for rom in roms:
print(rom)
print(ds_sensor.read_temp(rom))
time.sleep(5)
- Save the file to your pico as ds18b20.py.
- Click the run button in Thonny and you should see temperature readings appear in Thonny's shell every 5 seconds.
-
I will try this when my pico arrives at the end of this week. The tutorial says that the onewire library is from the esp32 port of micropython though Feb 3, 2021 at 17:57
-
1onewire is onewire @KelbyCriswell - most code for microcontrollers comes from other code :p Feb 3, 2021 at 21:57
-
Ok, thank you. I just want sure if the pico supports I swore communication. I will find out this weekend. Feb 4, 2021 at 20:13
-
-
1
It does work, but there's no error checking. Remove the sensor lead ( or put it in the wrong GPIO slot ) and you get a python error in convert temp. I'd rather print a warning like "Plug in the sensor, dummy!" and then stop before it gets to that point.