Posts: 1
Joined: Tue Oct 17, 2017 8:20 pm

Python Script to trigger GPIO pin

Tue Oct 17, 2017 8:28 pm


I am looking for direction with the following scenario:

I have an external temperature sensor. I need a script that will read the temperature of the sensor every 10 seconds, and if the temperature is over a certain degree F, will trigger a GPIO pin, which will in turn trigger my relay to run cooling fans. When the temperature drops below this threshold, I would like the GPIO pin to return to normal to deactivate my trigger. Seems easy enough, but all the tutorials I have found either deal with the internal CPU or is not complete. Would someone be so kind to help me with this code?

Hopfully this is a start:

import os, glob, time

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'

def read_temp_raw():
f = open(device_file, 'r')

Posts: 4272
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: Python Script to trigger GPIO pin

Tue Oct 17, 2017 10:26 pm

Here you go modified some code I fixed for another thread.

Code: Select all


import os
import glob
import time
import RPi.GPIO as GPIO


#relay connected to gpio13
relay = 13
GPIO.setup(relay, GPIO.OUT)
#temp limit in c
limit = 20

def read_temp_raw():
    base_dir = '/sys/bus/w1/devices/'
    device_folder = glob.glob(base_dir + '28*')[i]
    device_file = device_folder + '/w1_slave'
    f = open(device_file, 'r')
    lines = f.readlines()
    return lines

def read_temp():
    lines = read_temp_raw()
    while   lines[0].strip()[-3:] != 'YES':
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0   
    return temp_c

    while True:
        temp = read_temp()
        print (temp)

        if temp > limit:
the code is untested.

make sure you have enabled 1-wire interface using raspi-config
Remember we want information.......................no information no help
The use of crystal balls & mind reading is not supported

Return to “Python”

Who is online

Users browsing this forum: pcmanbob and 14 guests