Getting Started with MicroPython and the SparkFun Inventor's Kit for micro:bit
Experiment 7: Reading the Temperature Sensor
A temperature sensor is exactly what it sounds like --- a sensor used to measure ambient temperature. In this experiment you will read the raw 0--1023 value from the temperature sensor, calculate the actual temperature and then print it out over the LED array on your micro:bit.
You will need the following parts:
- 1x Breadboard
- 1x micro:bit
- 1x micro:bit Breakout with Headers
- 3x Jumper Wires
- 1x TMP36 Temperature Sensor
Didn't Get the SIK for micro:bit?
If you are conducting this experiment and didn't get the Inventor's Kit, we suggest using these parts:
Introducing the TMP36 Temperature Sensor
The TMP36 is a low-voltage precision centigrade temperature sensor. It provides a voltage output that is linearly proportional to the Celsius temperature. It also doesn’t require any external calibration to provide typical accuracies of ±1°C at +25°C and ±2°C over the −40°C to +125°C temperature range. The output voltage can easily convert to temperature using the scale factor of 10 mV/°C.
If you are looking at the flat face with text on it, the center pin is your signal pin, the left-hand pin is supply voltage (3.3V in this tutorial), and the right-hand pin connects to ground.
Ready to start hooking everything up? Check out the wiring diagram below to see how everything is connected.
|Polarized Components||Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.|
Please note: The temperature sensor can only be connected to a circuit in one direction. See below for the pin outs of the temperature sensor --- TMP36.
Wiring Diagram for the Experiment
Run Your Script
language:python # SparkFun Electronics # Experiment 7.0 # Reading a Temp Sensor from microbit import * while True: rawTemp = pin2.read_analog() degC = (((rawTemp*3.3)/(1023))-0.5)*100 display.show(str(degC)) sleep(1000)
Code to Note
We have already covered
display.show() but we need to convert our number (temperature) to a string (type) before displaying it to the micro:bit 5x5 LED array. Type conversion in MicroPython is a snap with a simple
str placed in front of the variable holding the temperature of type number.
What You Should See
When your micro:bit turns on, the temperature reading from the TMP36 temperature sensor will be displayed and scrolled across the LED array.
Temperature Value is Unchanging
Try pinching the sensor with your fingers to heat it up or pressing a bag of ice against it to cool it down.
Temperature Sensor is Really Hot!
You have wired it backward! Unplug your micro:bit immediately, let the sensor cool down and double check your wiring. If you catch it soon enough, your sensor may not have been damaged and may still work.