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

Python Script to trigger GPIO pin

Tue Oct 17, 2017 8:28 pm

Greetings,

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')

pcmanbob
Posts: 2055
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

#!/usr/bin/python3

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

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

#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()
    f.close()
    return lines

def read_temp():
    lines = read_temp_raw()
    while   lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        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

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

        if temp > limit:
            GPIO.output(relay,GPIO.HIGH)
        else:
            GPIO.output(relay,GPIO.LOW)
        time.sleep(3)        
                    
except:
    GPIO.cleanup
the code is untested.

make sure you have enabled 1-wire interface using raspi-config
Please only ask questions in the forum I will not answer questions sent to me directly via PM
Remember we want information.......................no information no help

Return to “Python”

Who is online

Users browsing this forum: KyluAce and 22 guests