Temperature Sensing with the TMP36 and Pycom

Updated 13 April 2022

Note: With the rollout of TTNv3, the "Setup" section of this guide no longer works - but we're keeping it here for posterity. Let us know on our forums if you need help getting started with the new method.

The TMP36 is a low cost, easy to use sensor that fits well with any project. With the TMP36, adding temperature sensing to your Pycom project is easy! In this tutorial, we will use the Pycom Lopy4, and send our measured data to The Things Network via the LoRa Network!

The Circuit

Here is a schematic for wiring up the TMP36. Keep in mind that the flat face of the sensor is facing TOWARD you in this schematic. In this example, we will be using the Pycom Expansion Board 3.0 and the Pycom Lopy4, but any Pycom board will work! If you are connecting to your Pycom board directly refer to the relevant pinout diagram.


The Code

In this example, we have provided the bare minimum needed to interface with a TMP36. Get out there an integrate one into your project!

# Measuring temperature by TMP36
import time
import machine

adc = machine.ADC()               # create an ADC object
apin = adc.channel(pin='P16')   # create an analog pin on P16 & connect TMP36
while True:
    print("Reading TMP36 Sensor...")
    value = apin()
    print("ADC count = %d" %(value))

    # LoPy  has 1.1 V input range for ADC
    temp = ((value * 1100 ) / 4096 - 500) / 10
    print("Temperature = %5.1f C" % (temp))


Sending Your Readings to The Things Network

Now that you have a stable reading from the TMP36, we can package our data into bytes and send it to The Things Network. If you want to learn more about connecting your Lopy4 to The Things Network, then check out our TTN Tutorials and our Getting Started with The Things Network Tutorial. Remember to add in your own App EUI and App Key!

# Measuring temperature by TMP36
from network import LoRa
import socket
import utime
import binascii
import pycom
import ustruct
import machine
from machine import Pin

adc = machine.ADC()               # create an ADC object
apin = adc.channel(pin=Pin.exp_board.G3)   # Lopy4 specific: (pin = 'P16')   create an analog pin on P16 & connect TMP36

# Temp measurment
def temp_measure():
    print("Reading TMP36 Sensor...")
    value = apin()
    print("ADC count = %d" %(value))

    # LoPy  has 1.1 V input range for ADC
    temp = ((value * 1100 ) / 4096 - 500) / 10
    print("Temperature = %5.1f C" % (temp))

    return temp

# disable LED heartbeat (so we can control the LED)
# set LED to red

# lora config
lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.AS923)
# access info
app_eui = binascii.unhexlify('XXXXXXXXXXXXXXX')
app_key = binascii.unhexlify('XXXXXXXXXXXXXXXXXXXXXXXXXXXX')

# attempt join - continues attempts background
lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0)

# wait for a connection
print('Waiting for LoRaWAN network connection...')
while not lora.has_joined():
	# if no connection in a few seconds, then reboot
	if utime.time() > 15:
		print("possible timeout")

# we're online, set LED to green and notify via print
print('Network joined!')

# setup the socket
s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5)

count = 0
# limit to 200 packets; just in case power is left on
while count < 200:

	# take temp measurment, turn the temp blue when measuring
	temp = temp_measure()

	# encode the packet, so that it's in BYTES (TTN friendly)
	# could be extended like this struct.pack('f', temp)   struct.pack('c',"example text")
    # 'h' packs it into a short, 'f' packs it into a float, must be decoded in TTN
	packet = ustruct.pack('f', temp)

	# send the prepared packet via LoRa

	# example of unpacking a payload - unpack returns a sequence of
	#immutable objects (a list) and in this case the first object is the only object
	print ("Unpacked value is:", ustruct.unpack('f',packet)[0])

	# check for a downlink payload, up to 64 bytes
	rx_pkt = s.recv(64)

	# check if a downlink was received
	if len(rx_pkt) > 0:
		print("Downlink data on port 200:", rx_pkt)
		input("Downlink recieved, press Enter to continue")

	count  = 1

Decoding on TTN

The above code will have you sending payloads to TTN in no time at all. To decode the payload from bytes back into user-readable data we need to enter some javascript into our Payload Formats. You can download the code for easy copy and pasting.


Going Further

If you want to learn more about Pycom check out our Pycom Tutorials. If you want to learn more about connecting to The Things Network and using LoRaWAN check out our The Things Network Tutorials. There are many more sensors and devices that can be used with the Pycom Lopy4, get out there and experiment!

Attachment - TTN-Decode-Float-Javascript.txt

Have a question? Ask the Author of this guide today!

Please enter minimum 20 characters

Your comment will be posted (automatically) on our Support Forum which is publicly accessible. Don't enter private information, such as your phone number.

Expect a quick reply during business hours, many of us check-in over the weekend as well.



Please continue if you would like to leave feedback for any of these topics:

  • Website features/issues
  • Content errors/improvements
  • Missing products/categories
  • Product assignments to categories
  • Search results relevance

For all other inquiries (orders status, stock levels, etc), please contact our support team for quick assistance.

Note: click continue and a draft email will be opened to edit. If you don't have an email client on your device, then send a message via the chat icon on the bottom left of our website.

Makers love reviews as much as you do, please follow this link to review the products you have purchased.