Skip to content

Instantly share code, notes, and snippets.

@NotBobTheBuilder
Last active August 14, 2023 22:57
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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

@fly2high1
Copy link

It is great, but I divided by 256 isted of 100 in order to show correct temperature.

@eode
Copy link

eode commented Jun 28, 2022

@NotBobTheBuilder I like your means of data retrieval -- can I use it in temper.py? This is for ccweink/temper, which is a fork and continuation of urwen/temper. It's not very active, but it's more active than urwen/temper.

@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