Skip to content

Instantly share code, notes, and snippets.

@NotBobTheBuilder
Last active September 28, 2024 11:40
Show Gist options
  • Save NotBobTheBuilder/085330fb0f0fffcb35e2a551a83e3ee0 to your computer and use it in GitHub Desktop.
Save NotBobTheBuilder/085330fb0f0fffcb35e2a551a83e3ee0 to your computer and use it in GitHub Desktop.
Take a temperature reading from a TEMPer Gold USB thermometer/temperature sensor
#!/usr/bin/env python3
import os
import select
import struct
DEV = '/dev/hidraw1'
def read_temperature(device_path=DEV):
# Credit to https://github.com/urwen/temper for this byte sequence
QUERY = struct.pack('8B', 0x01, 0x80, 0x33, 0x01, 0x00, 0x00, 0x00, 0x00)
# Open the device and return a file descriptor (needed for poll later)
f = os.open(device_path, os.O_RDWR)
# Write the "fetch temperature" query to the device
os.write(f, QUERY)
# Wait for the device to have data to read by polling the file descriptor
poll = select.poll()
poll.register(f, select.POLLIN)
# This call blocks until data is ready
poll.poll()
poll.unregister(f)
# Tempergold sends 16 bytes of data, read it and close the file
data = os.read(f, 16)
os.close(f)
# Temperature is encoded as a big-endian (>) 2 byte integer (h)
# https://docs.python.org/3/library/struct.html#format-characters
# The encoded value represents degrees in c * 100
return struct.unpack_from('>h', data, 2)[0] / 100
if __name__ == "__main__":
print(read_temperature())

tempergold.py

(Linux only)

Take a temperature reading from a TEMPer Gold USB device:

https://thepihut.com/products/temper-gold-original-usb-temperature-sensor

Usage:

Run from the shell with python3 tempergold.py

Use in your own scripts by placing your own script in a folder with this file:

import tempergold
# Read from the default device
print(read_temperature())
# Read from a specific device, useful if you have multiple
print(read_temperature('/path/to/your/device')

Note:

This script was written for Python 3, but should be compatible with Python 2. You may notice only whole integer temperatures are available for Python 2, where 2 decimal places are reported in Python 3. This is due to the differences in division between python 2 and 3

@NotBobTheBuilder
Copy link
Author

Of course - very happy you can make use of it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment