Created
January 21, 2025 02:36
-
-
Save schappim/272faa15ce83150993186bc3afa1a963 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import os | |
import time | |
device_id = None | |
temperature = None | |
i = 0 | |
delay = 3 | |
def get_device_id(): | |
print("Fetching device ID...") | |
try: | |
devices = os.listdir("/sys/bus/w1/devices") | |
found_device = [dev for dev in devices if '-' in dev] | |
if found_device: | |
return found_device[0] | |
else: | |
return None | |
except FileNotFoundError: | |
return None | |
def get_temperature(device): | |
device_path = f"/sys/bus/w1/devices/{device}/w1_slave" | |
print(f"Device Path is {device_path}") | |
with open(device_path, 'r') as f: | |
lines = f.readlines() | |
# The temperature reading is on the second line after 't=' | |
temp_str = lines[-1].split("t=")[-1].strip() | |
temp_c = float(temp_str) / 1000 | |
return temp_c | |
def main(): | |
global device_id, temperature, i | |
# Attempt to get a device ID at the start | |
if device_id is None: | |
device_id = get_device_id() | |
if device_id is None: | |
print("No 1-Wire sensor found.") | |
return | |
while True: | |
i += 1 | |
# Fetch temperature from the sensor | |
temperature = get_temperature(device_id) | |
# If we're within the initial delay period, we could optionally | |
# show a "splash" equivalent here. For now, we'll just note it: | |
if i < delay: | |
print("Showing splash screen...") | |
# Once we've passed the delay, print the current temperature | |
if i >= delay: | |
print(f"{temperature:.2f}º Celsius - {time.strftime('%c')}") | |
# Sleep for a second to avoid excessive reads | |
time.sleep(1) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment