Using a TMP36 sensor with micro:bit
Every maker has their favourite sensor, board, component.
|
|
|
But recently I stumbled upon the TMP36, another temperature sensor, but this is an analogue sensor. Meaning that the output of the sensor is a voltage, rather than a string of data, in the case of the DS18B20.
After having used the sensor with a Raspberry Pi, via an MCP3008 ADC. I wondered if I could use it with micro:bit and the micro Python language.
So here goes.
Hardware
The circuit for the project is really simple. We just connect the 3V and GND from the micro:bit to the sensor. Then we connect the middle output pin of the TMP36 to pin0 of the micro:bit.
Connecting the TMP36 with croc clips is possible, but be careful that the pins/clips don't touch each other.
I'm lucky enough to have a Proto-Pic exhi:bit provided by CPC for a future micro:bit expansion board mega test that I am working on.
Now plug in the micro USB lead to your micro:bit, and then connect it to your computer, where it should appear as a USB flash drive.
Software
Everyone who knows me, knows that I love Python so I coded this project using the mu editor
Code
To start, I imported all of the microbit library.
from microbit import *
Then I created a while True loop which will continuously run the code inside of the loop. Remember the code inside the loop is now indented.
while True:
Now we read the raw analog voltage which the output pin of our TMP36 is sending to pin0 of the micro:bit. Then we multiply that value by the output of 3300 (milivolts) divided by the number of analog steps that our micro:bit can read (0 to 1023).
raw = pin0.read_analog() * (3000 / 1023.0)
To convert the values into something human readable, in this case the temperature in Celsius. We have to do a little more maths. We take 100 from the raw value, then divide it by 10, finally we subtract 40.
temp_C = ((raw - 100.0) / 10) - 40.
Now in order to see the value, we print it to the Repl. But to keep the temperature values neat, we restrict them to 3 decimal places using round()
print(round(temp_C,3))
Lastly we sleep for 1 second, before the loop repeats.
sleep(1000)
Complete code listing
from microbit import *
while True:
raw = pin0.read_analog() * (3000 / 1023.0)
temp_C = ((raw - 100.0) / 10) - 40.0
print(round(temp_C,3))
sleep(1000)
Flash the code to your micro:bit!
Click on Flash, to send the code to your attached micro:bit. When ready click on Repl to see the temperature data scroll across the screen.
So what can I do with this?
If you have a few micro:bits then you could use the radio
functionality to send temperature data to a central micro:bit which can then collate and act upon the data it receives.
Accuracy
The TMP36 can be around ±2°C so for any mission critical / scientific projects, this sensor is not highly accurate.