Two GPIO buttons calling the same object - python

I am working with a Pi3, a bread board, a temp sensor and a 4-channel relay. Right now, I have two buttons on my bread board, which, when pushed are supposed to display the temperature and turn on a relay and turn of another. I am working towards building a smart thermostat so think of the buttons representing air-conditioning and heating, they cannot be on at the same time.
My issue is that, when displaying the temperature, it references the object (read_temp()), which displays the temperature correctly for one button and not the other. It will only display the very last part of equation which converts Celsius to Fahrenheit. For example, I will hit both buttons, one will display 75 degrees and the other will always display 32.
I have tried declaring the buttons differently as GPIO.inputs, I have moved to different GPIO pins thinking it is a hardware issue, I have switched the position of the buttons and I have tried returning both temp_c and temp_f in (read_temp()) object and nothing seems to do the trick.
Currently, it is the AC button that is not working properly but as I mentioned, I have switched the buttons and the pins around and it still only displays properly for one.
Thanks!
import RPi.GPIO as GPIO
import time
import os
import glob
import time
import sys
from gpiozero import Button
import pdb
# init list with pin numbers
GPIO.setmode(GPIO.BCM)
pinList = [2, 3, 27, 17]
AC = Button(12)
Heat = Button(21)
# loop through pins and set mode and state to 'high'
for i in pinList:
GPIO.setup(i, GPIO.OUT)
GPIO.output(i, GPIO.HIGH)
# time to sleep between operations in the main loop
##SleepTimeL = 5
# Setting up temperarture sensor
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')
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
temp_f = temp_c * 9.0 / 5.0 + 32.0
return temp_f
# main loop
try:
while True:
if AC.is_pressed:
GPIO.output(2, GPIO.LOW)
GPIO.output(3, GPIO.HIGH)
print(read_temp()), "degrees farenheit"
if Heat.is_pressed:
GPIO.output(3, GPIO.LOW)
GPIO.output(2, GPIO.HIGH)
print(read_temp()), "degrees farenheit"
except KeyboardInterrupt:
print " Quit"
GPIO.cleanup()

Related

python counting funktion for text output in a loop

I have a working code which tells me, when a laser and a photoresistor will be interrupted.
It would be great, when I can write the information of time into a file and also a counting (i=i+1). So this will be done normally every 2 seconds. A writing after e.g. 500 breaks would be great, because it is running at a rasyperry pi. Less writing would be great.
My output file should be something like this with unix time stamp. So I do not know where do I have to put my counter i = i + 1 at which position and the second question is about the caching issue.
12341234.12341234 1
123478.234789 2
12342134.12341234 3
78989123.12341234 4
Code
import os, time
from time import strftime,localtime
RECEIVER_PIN = 23
def callback_func(channel):
if GPIO.input(channel):
print("Sensor1: Lichtschranke wurde unterbrochen")
date_local = strftime("%Y-%m-%d %H:%M:%S", localtime())
ticks = time.time()
print(date_local)
print(ticks)
with open("/home/pi/Documents/sensors/sensor01_tageswert.txt","a+") as sensor01:
# sensor01.write(date_local)
sensor01.write(str(ticks))
sensor01.write("\n")
# alternativ kann ein Script / Shell Befehl gestartet werden
# os.system("ls")
if __name__ == '__main__':
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(RECEIVER_PIN, GPIO.IN)
GPIO.add_event_detect(RECEIVER_PIN, GPIO.RISING, callback=callback_func, bouncetime=200)
try:
while True:
time.sleep(0.25)
except:
# Event wieder entfernen mittels:
GPIO.remove_event_detect(RECEIVER_PIN)

How to write to a file and save it to another machine on same network using python?

In this script I am taking the temperature from a DHT11 sensor and parsing the data that another script can read. Everything works except for writing the file to another pc using the path I placed in the f = open part of the script below. Everything works great except that the file doesn't get written or saved.
Any Help?
#!/usr/bin/env python
# encoding: utf-8
import sys
import time
import dht11
import RPi.GPIO as GPIO
#define GPIO 14 as DHT11 data pin
Temp_sensor=14
def main():
# Main program block
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM) # Use BCM GPIO numbers
instance = dht11.DHT11(pin = Temp_sensor)
while True:
#get DHT11 sensor value
result = instance.read()
temp = '{:.0f}'.format(result.temperature * 1.8 + 32)+"°"
# The path to send the txt file to and save is /10.1.1.28/c$/Temperature_RETR/kvoa_temp.txt
if result.is_valid():
print temp
f = open('\\10.1.1.28\c$\Temperature_RETR\new_temp.txt','w')
#f = open('/home/pi/Desktop/new_temp.txt','w')
y = temp
z = str(y)
f.write(z)
f.close()
time.sleep(60) # 60 second delay
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
pass

Send commands to Openhab depending on Light Sensor Values Python Raspberry Pi

I have Photoresistor connected to my Raspberry PI through 1uF capacitor, and running simple program to check values. It's mostly merged scripts from other programms i have, so it's might by buggy. I'm new in this stuff. I set 2 variables. If value of photoresistor is below 1000 then it's True, otherwise it's False. I Wan't to controll my LED's trough JSON command to Openhab server. When photoresistor gives True, it's sending command "ON" to Openhab, otherwise it's sending command "OFF". Everything's fine, except one thing. Script sending commands to Openhab with every measure of photoresistor value. I want it to send command "ON" only first time when value below 1000 is detected (True) then stay there, not sending commands to Openhab to moment when photoresistor give output above 1000 (False) and so on in other way. Main goal here is to Change LED's color when main lighting is ON, and change it back when main lighting is OFF. I hope i explained it good. Please help.
My current program:
#!/usr/local/bin/python
import RPi.GPIO as GPIO, time
import urllib
import urllib2
import requests
GPIO.setmode(GPIO.BCM)
def RCtime (PiPin):
measurement = 0
# Discharge capacitor
GPIO.setup(PiPin, GPIO.OUT)
GPIO.output(PiPin, GPIO.LOW)
time.sleep(0.1)
GPIO.setup(PiPin, GPIO.IN)
# Count loops until voltage across
# capacitor reads high on GPIO
while (GPIO.input(PiPin) == GPIO.LOW):
measurement += 1
return measurement
def LIGHTcheck():
if RCtime(27)<1000:
LIGHT = True
print LIGHT
return LIGHT
if RCtime(27)>1000:
LIGHT = False
print LIGHT
return LIGHT
def LightON():
url = 'http://openhab-server:8080/CMD?switch2=ON'
postdata = {"ON"}
print(postdata)
resp = requests.get(url=url)
def LightOFF():
url = 'http://openhab-server:8080/CMD?switch2=OFF'
postdata = {"OFF"}
print(postdata)
resp = requests.get(url=url)
while True:
if LIGHTcheck() == True:
LightON()
elif LIGHTcheck() == False:
LightOFF()
Ok. I figured it out in some way. If anyone ever need solution like this, here's a running programm. It's not professional craft, so it's probably buggy, still testing. I did not found something like that elsewhere, so better this than nothing.
IN SHORT: When Main light is off, if photoresistor detects that Main lighting changed to ON, then script saves current color and brightness states to files, then changing color to predefinied with Openhab script/rules through REST API. Then if photoresistor detects that main lighting is off, script reads content of files saved before and restores previous color and brightness of LED's. That script handling photoresistor and sending commands but most of action happening on Openhab.
If anyone have some sugestions, i would be pleased to here them.
#!/usr/local/bin/python
import RPi.GPIO as GPIO, time
from subprocess import call
import smbus
import time
import urllib
import urllib2
import json
import requests
from ctypes import c_short
GPIO.setmode(GPIO.BCM)
def RCtime (PiPin):
measurement = 0
# Discharge capacitor
GPIO.setup(PiPin, GPIO.OUT)
GPIO.output(PiPin, GPIO.LOW)
time.sleep(0.1)
GPIO.setup(PiPin, GPIO.IN)
while (GPIO.input(PiPin) == GPIO.LOW):
measurement += 1
return measurement
def LIGHTcheck(): # Checking photoresistor Values, and defining Variables as True/False:
if RCtime(27)<150:
LIGHT = True
return LIGHT
if RCtime(27)>150:
LIGHT = False
return LIGHT
def LIGHTstatusSaveColor(): # Saving Color State to file:
urllib.urlretrieve('http://openhab-server:8080/rest/items/Light_scene/state', 'color.log')
def LIGHTstatusSaveDimmer(): # Saving Brightness State to file:
urllib.urlretrieve('http://openhab-server:8080/rest/items/Brightness_switch/state', 'dimmer.log')
def LightON():
url = 'http://openhab-server:8080/CMD?Light_scene=43' # Openhab Command to switch color to predefined, in my case "Light_scene" with predefined responses trough Openhab scripts/rules:
resp = requests.get(url=url)
def LightOFFcolor(): # Reading state of color from previously saved file and sending command to Openhab to change color to Value from before Turning Main Lighting on:
f = open("color.log", "r")
content1 = f.read()
# print(content1)
url = 'http://openhab-server:8080/CMD?'
postdata = {"Light_scene":content1}
# print(postdata)
resp = requests.get(url=url, params=postdata)
f.close()
def LightOFFdimmer(): # Reading state of brightness from previously saved file and sending command to Openhab to change brightness to Value from before Turning Main Lighting on:
f = open("dimmer.log", "r")
content2 = f.read()
# print(content2)
url = 'http://openhab-server:8080/CMD?'
postdata = {"Brightness_switch":content2}
# print(postdata)
resp = requests.get(url=url, params=postdata)
f.close()
waiting_for_high_value = True
while True: # Loop Waiting for value change, then executing suitable Function:
if waiting_for_high_value:
if LIGHTcheck() == True:
print LIGHTcheck()
LIGHTstatusSaveColor()
LIGHTstatusSaveDimmer()
LightON()
waiting_for_high_value = False
else:
if LIGHTcheck() == False:
print LIGHTcheck()
LightOFFcolor()
time.sleep(2.0)
LightOFFdimmer()
waiting_for_high_value = True

Python - static interface for hardware IO

This a somewhat general question so forgive me if I'm breaking any guidelines.
I'm writing a JQuery / websocket / Flask application that uses a Raspberry Pi to monitor some sensors as well as manage some active hardware. Multiple classes and objects spawned by my Flask-implemented server need to be able to access my hardware.
Based off my programming background (relatively new to Python) I would gravitate to a static class with class methods that operate without instantiation.
I've found documentation on how to do that in Python but I'm not sure it's the best approach. Is it more Pythonic to instantiate an object and pass it around or ... ?
Here is the non-static object oriented code I'm using now (I'm thinking a static version of the following will suite my needs but I want to do what is most appropriate for the language):
import os
import glob
import time
import RPi.GPIO as GPIO
#class to manage hardware -- sensors, pumps, etc
class Hardware:
#system params for sensor
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
#global vars for sensor
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'
#global var for program
temp_unit = 'F' #temperature unit, choose C for Celcius or F for F for Farenheit
temp_target = 69 #target temperature to cool to in chosen unit
temp_log_loc = '/var/www/hw-log.csv' #location of temp log, by default Raspberry Pi Apache server
gpio_pin = 17
#function to enable GPIO
def gpio_active(self,active):
if active is True:
GPIO.setmode(GPIO.BCM)
GPIO.setup(self.gpio_pin, GPIO.OUT)
else:
GPIO.cleanup()
#def __init__(self): Not used
#reads raw temp from sensor
def read_temp_raw(self):
f = open(self.device_file, 'r')
lines = f.readlines()
f.close()
return lines
#cleans up raw sensor data, returns temp in unit of choice
def read_temp(self):
lines = self.read_temp_raw()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = self.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
temp_f = temp_c * 9.0 / 5.0 + 32.0
if self.temp_unit == 'F':
return temp_f
else:
return temp_c
#**********sensors**********
#mashtun sensor
##staticmethod
def mashtun_temp(self):
return self.read_temp()
#hot liquor tank sensor
def htl_temp(self):
return 200
#fermentor sensor
def fermentor_temp(self):
return 65
#**********pumps**********
def herms_pump_active(self,active):
self.gpio_active(True)
if active is True:
print('***Hardware report: Setting HERMS pump on***')
GPIO.output(self.gpio_pin,GPIO.LOW)
else:
print('Setting HERMS pump off')
GPIO.output(self.gpio_pin,GPIO.HIGH)
self.gpio_active(False)

Python write GPIO values

I am a complete noob using a Raspberry Pi trying to make a program that would track instances of movement with a PIR sensor set on GPIO 4, now the program works without any issues until I try to export the data, long story short, I try gspread, and ubidots and both won't work, even just with a test file. So my next attempt is a simple txt file that will capture time and date, and would write a 1.
this is what I have:
import time
import datetime
import RPi.GPIO as GPIO
sensor = 4
GPIO.setmode(GPIO.BCM)
GPIO.setup(sensor, GPIO.IN, GPIO.PUD_DOWN)
prevstate = False
currState = False
while True:
time.sleep(0.1)
prevState = currState
currState = GPIO.input(sensor)
if currState != prevState:
newState = "1" if currState else "0"
print("GPIO pin %s is %s" % (sensor, newState))
try:
values = [datetime.datetime.now(), newState]
with open("test.txt", "a") as text_file:
text_file.write("values")
time.sleep(1.5)
So i don't really don't now why but everything works until I hit the value section, and then I get a unindent error, if I remove from try down i get nothing
I did had before:
except:
print: "cannot open file"
but that really wasn't any issue there. the unindent still comes up.
You have indentation issues. It looks like you started allowing Idle to tab - 8 for indentation then switched to 4. You need to unindent and re-indent everything.
The way you are handling your file, you will overwrite it every time through. You will end up with only one entry in the file. Try opening the file before your main loop:
import time
import datetime
import RPi.GPIO as GPIO
sensor = 4
GPIO.setmode(GPIO.BCM)
GPIO.setup(sensor, GPIO.IN, GPIO.PUD_DOWN)
prevstate = False
currState = False
with open("test.txt", "a") as text_file:
while True:
time.sleep(0.1)
prevState = currState
currState = GPIO.input(sensor)
if currState != prevState:
newState = "1" if currState else "0"
print("GPIO pin %s is %s" % (sensor, newState))
try:
values = [datetime.datetime.now(), newState]
text_file.write("values")
except:
print "cannot open file"
get rid of the colon ":" after print, and that sleep after your main loop was not doing anything.
You must always follow the try statement with an except or finally statement, but you mentioned that you also got the error with the try statement? Did that also include the : after print (it shouldn't)? This should work:
try:
values = [datetime.datetime.now(), newState]
with open("test.txt", "a") as text_file:
text_file.write(values)
except:
print: "cannot open file"
Notice that I also removed the quotes around values in text_file.write(values).

Categories