thank you in advance for reading and taking the time to troubleshoot this with me!
Let me first start off with the important stuff:
Target Device:
Raspberry Pi 4B
Electronic-Salon Relay Hat
Development Environment:
macOS Catalina
PyCharm
Python 2.7.10
At my home I have a spring that serves my home with water. The solution I came up with to prevent dirty water caused by bad rainy weather loosening up the ground soil from entering my cistern is closing a valve and waiting for about 12 hours for the water to clear back up. Then I open the valve and clear water flows into my cistern providing my home with water, and that solution works really well.
I recently came up with the conclusion that I want to automate this process with a normally open solenoid. I purchased a Raspberry Pi, a Relay Hat, and an Ambient Weather weather station.
What I'm looking to do with Python 2.7.10 is check the same variable against itself after an allotted time. In this example, I'm checking the relative barometric pressure against itself and I'm wanting to look for a significant negative change in that variable.
i.e "What does variable A have? Okay, now wait 3 seconds. What does A have now? How much has it changed?"
This is what I've bodged together so far, how can I improve? Thank you.
At first I was thinking maybe I should plot a chart with the data and compare the difference between the two plot points, but I wasn't sure how to use Matplotlib.
# This is the executing script for the Smart Valve.
# This project is powered by raspberry pi and 120 angry pixies.
import time,imp
from ambient_api.ambientapi import AmbientAPI
# This code will pull the data from the weather computer
api = AmbientAPI()
devices = api.get_devices()
device = devices[0]
time.sleep(1) #pause for a second to avoid API limits
# The code below is meant for telling the python interpreter to behave normally whether or not it's in a RPi env or a
# developer env
try:
imp.find_module('RPi.GPIO')
import RPi.GPIO as GPIO
except ImportError:
"""
import FakeRPi.GPIO as GPIO
OR
import FakeRPi.RPiO as RPiO
"""
import FakeRPi.GPIO as GPIO
# this code compares the rate of change for the barometric pressure over time and checks if rate is negative
a1 = None
a2 = None
while True:
weatherData = device.get_data()
data = dict(weatherData[0])
pressure = data[u'baromrelin']
wind = data[u'windspeedmph']
rain = data[u'hourlyrainin']
a1 = pressure
time.sleep(30)
a2 = pressure
print("A1 is equal to " + str(a1))
print("A2 is equal to " + str(a2))
if a1 > a2:
print("we should close the valve, it'll rain soon")
continue
elif a1 == a2:
print("It's all hunky dory up here!")
break
Firstly i would avoid Python 2. 2020 was the last year to it. Now Python 3 all the way. Also you won't need u'text' as everything is unicode.
The problem with your code is that you reference the same pressure variable twice.
Here's why. You do nothing to change it after the wait. Its effectively:
pressure = 123.4
first = pressure # 123.4
thread.sleep(30)
second = pressure # 123.4
second == first
# True
I would avoid setting two measurements in a single. And I'm going to use previous and current as names as it makes more sense than a1 or first.
Without a loop.
prev = None
# Pass 1
weatherData = device.get_data()
data = dict(weatherData[0])
pressure = data[u'baromrelin']
curr = pressure # e.g. 123.4
if prev is None or curr > prev:
print("Pressure is rising!")
# Current iteration's current pressure will become the next iteration's previous pressure. You could even then see curr = None because we about to overwrite on next iteration.
prev = curr # 123.4
time.sleep(30)
# Pass 2
weatherData = device.get_data()
data = dict(weatherData[0])
pressure = data[u'baromrelin']
curr = pressure # e.g. 234.5
if prev is None or curr > prev:
print("Pressure is rising!")
# 234.5 > 123.4
time.sleep(30)
With a loop:
WAIT = 30
prev = None
while True:
weatherData = device.get_data()
data = dict(weatherData[0])
pressure = data[u'baromrelin']
curr = pressure
if prev is None or curr > prev:
print("Pressure is rising!")
break
print(f"Nothing usual. Waiting {WAIT} seconds...")
time.sleep(WAIT)
The general design pattern for this is:
oldval = 0
while 1:
newval = read_the_value()
if oldval != newval:
take_action()
oldval = newval
sleep(xxx)
I think that will work for you.
Related
Example:
If the Photovoltaik Number is constant over a certain period, there is something wrong, because Solar Power Irradation fluctuats alot. So One should want to recognize this bevarioul pattern to e.g. restart the system.
old_pv = []
while True:
try:
count = 1
sunny_scraper.driver.current_url
new_pv = sunny_scraper.scrape()
old_pv.append(new_pv)
count += 1
if count in [19, 20]:
if len(list(set(old_pv))) == 1:
sunny_scraper.start_browser()
sunny_scraper.accept_cookies()
sunny_scraper.enter_email_password()
new_pv = sunny_scraper.scrape()
time.sleep(5)
old_pv = []
old_pv.append(new_pv)
else:
time.sleep(10)
except:
time.sleep(120)
sunny_scraper.start_browser()
sunny_scraper.accept_cookies()
sunny_scraper.enter_email_password()
sunny_scraper.scrape()
time.sleep(10)
pv - Photovoltaic (solar power)
the pv value is scraped in high resolution (~ 10s), I work in Solar Industrie for Power Prediction using All Sky Imager. Sometimes the value freezes (reason unclear), so restarting the script is the current idea.
What other implementation options would be conceivable and useful? I would be happy for inspiration.
I have a python program running a clock and thermometer (raspberry pi + fourletterphat), see program below. I change between showing time or temperature by clicking a single button (gpio16).
What I need help with:
I want to pause the program during night, 21:00 - 06:00, and clear the display because the light is annoying. With the current code I get the display to clear at time for night to start but it does not start again.
If, during above period, the button is clicked I want the program to run for 10 seconds and then stop/clear display. I simply have no idea how to do this, Not even where start.
Is there an elegant way to do this, preferably by just adding something to the existing program. See below.
I have tried various ways of either clearing the display during night time and/or pausing the program until button is hit (but only during the night time, i want the program running during day to show temperature or time).
I have found many versions on finding it time.now is within my range for night but they seem not to be compatible with starting the program as described in point 2 above. (e.g. if time.now < night_end or time.now >= night_start:)
in code below function bright() sets the brightness AND turns off the display at night start 20:00.
Function night() is my feeble start on the restart display at night time but I have not gotten further.
#! /usr/bin/env python3
#Tempclock working with fourletterphat from pimoroni. One switch to change between temp and clock.
#sets brightness at startup but not continuously.
import glob
import time
import datetime
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_DOWN )
input_state = GPIO.input(16)
import fourletterphat as flp
# Find 1s temp sensor
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'
# times for setting brightness of display:
# d2 and d3 time dim and brighten display
d2 = 18
d3 = 7
# d4 and d5 time to turn off display for nigh
d4 = 20
d5 = 6
butt = 1
# Set brightness
def bright():
todays_date = datetime.datetime.now()
hn = (todays_date.hour)
if hn < d5 and hn > d4:
flp.clear()
flp.show()
elif hn < d2 and hn > d3:
flp.set_brightness(12)
else:
flp.set_brightness(0)
# Define nighttime display off
def night():
todays_date = datetime.datetime.now()
hn = (todays_date.hour)
if hn < d5 or hn => d4:
flp.set_brightness(5)
# define temp and time reading
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_c, temp_f
def display_temp():
# temp = read_temp()[1] # F
temp = read_temp()[0] # C
flp.print_float(temp, decimal_digits=1, justify_right=True)
flp.show()
def display_time():
now = datetime.datetime.now()
str_time = time.strftime("%H%M")
flp.print_number_str(str_time)
flp.show()
# Display time or temp button on gpio pin 16 push button counter "butt" and set
# brightness bright() according to time of day. Function night() turns on display for 10sec if at night, then turns it off.
while True:
bright()
if GPIO.input(16) == 0:
butt = butt + 1
night()
if butt > 2:
butt = 1
if butt == 1:
display_time()
flp.show()
elif butt == 2:
display_temp()
flp.show()
time.sleep(0.2)
I'll start by assuming that your code to display time and read temperature is working correctly. Also, since I don't have a RaspberryPi with me, I'm focusing on how to organise your logic on the parts that I think you are having difficulty. My code to specifically turn the display on or off may be wrong, but I guess you figured that part out already. Since your question is about an elegant way to do this, the solution is obviously opinion-based. What I am proposing here is a simple but sound way to do it.
The first thing to notice is that you want two modes of operation. I'll call them day_mode and night_mode. The behaviour you expect is quite different for each mode:
day_mode: display is always on, when button 16 is pressed, the display should change from temperature to time. It should be active from 6:00 until 21:00
night_mode: display is normally off. When button 16 is pressed, the display should turn on and display something (you didn't specify, but I'll assume it is the temperature). It should be active when day_mode is not active.
When thinking about modes, it usually helps to separate three things:
What you need to do when you enter that mode of operation (for example, when you enter day_mode you should turn on the display and show the clock, when you enter night_mode you should turn off the display)
What is the behaviour you want during the mode. In your case, it is what we discussed above.
Any clean-up action needed when you exit the mode. Here none is needed, so we will skip this part.
So, let's begin! From your original code, I'll keep everything but the functions night, bright and the final loop. The first thing to do is create a function that tells in which mode we should be:
import datetime as dt
def which_mode():
current_hour = dt.datetime.now().time().hour
# In your code you seemed to need special behaviour between 6 and 7 and 18 and 21,
# but since it was not in your question, I'm not including it here
if 6 <= current_hour <= 21:
return 'day_mode'
else:
return 'night_mode'
To represent the modes, I'll use functions. If your problem were more complex, classes with specific enter, exit and during methods and a full blown state machine implementation would be needed. Since your problem is small, let's use a small solution. Each mode is a function, and the fact that you are entering the mode is informed by a parameter is_entering. The function will also receive a signal indicating that the button was pressed (a rising edge, but change according to your implementation). Before that, we will create a function that displays time or temperature based on a parameter:
def display_what(what):
if what == 0: # Time
display_time()
else: # Temperature
display_temp()
display_info = 0 # 0 means time, 1 means temperature
def day_mode(is_entering=False, button_pressed=False):
global display_info # Not very elegant, but gets the job done
if is_entering:
# Here the display is turned on. I got the values from your `bright` function
flp.set_brightness(12)
flp.clear()
# This is the `during` logic. Note that it will be run right after `entering` the first time
if button_pressed:
display_info = (display_info + 1) % 2 # Cycles between 0 and 1
display_what(display_info) # Update the display accordingly
For the night_mode function, we will need to keep a global variable to record when the button was last pressed. By convention, when it is smaller than 0, it means we are not counting the time (so we do not keep "clearing the display" all the time).
time_of_last_press = -1.0
def night_mode(is_entering=False, button_pressed=False):
if is_entering:
# Setup the dark display
flp.clear()
flp.set_brightness(0)
if button_pressed:
# Record when the button was pressed and display something
time_of_last_press = time.time()
flp.set_brightness(4) # I understood from your code that at night the display is less bright
display_what(1) # Temperature? You can use a similar logic from day_mode to toogle the displays
elif ((time.time() - time_of_last_press) > 10.0) and (time_of_last_press >= 0):
flp.clear()
flp.set_brightness(0)
time_of_last_press = -1.0
Finally, the main loop becomes relatively simple: check what should be the next mode. If it is different from the current one, set is_entering as True. Then call the function for the current mode.
# Setup the GPIO to detect rising edges.
GPIO.add_event_detect(16, GPIO.RISING)
current_mode = None # In the first run, this forces the `entering` code of the correct mode to run
while True:
button_pressed = GPIO.event_detected(16)
next_mode = which_mode()
changed = next_mode != current_mode
current_mode = next_mode
if current_mode == 'day_mode':
day_mode(changed, button_pressed)
else: # There are only two modes, but could be an elif if there were more modes
night_mode(changed, button_pressed)
time.sleep(0.2)
You may have noticed that there is some repetition: for example, in night_mode, the code to clear the display is the same code used when entering it, so you could actually call night_mode(True) to run that code again. Most importantly, there are two ifs that are similar: the one in which_mode and the one in the main loop. This can be fixed (and the code made more generic) if we change which_mode to return the function representing the mode, instead of a string. This may be a little more difficult to read if you are not used to functions returning functions, but it is a very flexible way of doing this sort of state machine:
# Must be defined after the functions `day_mode` and `night_mode` are defined
def which_mode():
current_hour = dt.datetime.now().time().hour
# In your code you seemed to need special behaviour between 6 and 7 and 18 and 21,
# but since it was not in your question, I'm not including it here
if 6 <= current_hour <= 21:
return day_mode # Note that this is not a string. It is a function!
else:
return night_mode
# Setup the GPIO to detect rising edges.
GPIO.add_event_detect(16, GPIO.RISING)
current_mode = None # In the first run, this forces the `entering` code of the correct mode to run
while True:
button_pressed = GPIO.event_detected(16)
next_mode = which_mode()
changed = next_mode != current_mode
current_mode = next_mode
current_mode(changed, button_pressed) # Now current_mode is a reference to one of the two mode functions, so we just need to call it.
time.sleep(0.2)
I am developing an application on a raspberry pi with an HC-SR01 sensor. For now I have a python script that checks the water level every second.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO_TRIGGER = 16
GPIO_ECHO = 18
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)
def distance():
# set Trigger High
GPIO.output(GPIO_TRIGGER, True)
# set Trigger after 0.1ms low
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
startTime = time.time()
endTime = time.time()
# store start time
while GPIO.input(GPIO_ECHO) == 0:
startTime = time.time()
# store arrival
while GPIO.input(GPIO_ECHO) == 1:
endTime = time.time()
# elapsed time
TimeElapsed = endTime - startTime
# multiply with speed of sound (34300 cm/s)
# and division by two
distance = (TimeElapsed * 34300) / 2
return distance
while True:
dist = distance()
print ("Entfernung = %.1f cm" % dist)
time.sleep(1)
This is working fine and now I want to send an E-Mail to myself then the water level is above a certain limit. The sending of the E-Mail is not the problem but the logic when to send it.
If I put a sendEmail() function in the while loop I would get an E-Mail every second when the water level is reached. So the following wouldn't do it:
#global varaible
alarm_waterlevel = 170
#in while loop
if dist > alarm_waterlevel
sendMail()
So I'm looking for a clever solution to only send the mail once the water level is reached.
I was thinking about a global variable and check if the water level has dropped below a certain point before triggering the mail again. Something like this:
#global varaible
alarm_waterlevel = 170
mail_sent = false
#in while loop
if dist >= alarm_waterlevel && mail_sent == false
sendMail()
mail_sent = true
if dist <= alarm_waterlevel - 10
mail_sent = false
Do you think this is a fault tolerant solution? Any good advices out there to help me get around with this?
Your approach looks reasonable to me, for a Raspberry Pi solution ;)
Another thing that you could think of is adding maybe three different warning levels or states that your system can be in.
L1: send once, 80% full
L2: send every 5 minutes, 90 % full
L3: send every minute, > 100 %
And you have to think of when to change the states. You could add something like a hysteresis. That could be elegant so you don't have to use three different height levels.
If the water level increases you could switch the state, e.g. at 80 % but only switch back to a lower warning state when it is below 70 %. The idea is that your system is not constantly changing states when the water level is between 78 % and 82 %.
Another thing that you could think of is like a projection by looking at the derivative (first or maybe additionally second) of the water level. Then you could warn even earlier when the water level is rising quickly but it is still below a critical threshold.
I think you have a general logic problem in your if statement.
You want to send an e-mail when the distance is greater than or equal to your alert level.
I think your ultrasonic sensor measures from top to bottom, so your if statement should be:
size_water_container = 200 #Just a estimadet value
if dist < (size_water_container - alarm_waterlevel) and waterlevel_before > (size_water_container - alarm_waterlevel):
sendMail()
If i am wrong, than ignore it :)
But now to your Question.
If you permanently query the distance, than you have to permanently save your waterlevel_before, but not in the if statement. Just do it afterwards
alarm_waterlevel = 170
size_water_container = 200
waterlevel_before = 0
while True:
dist = distance()
if dist < (size_water_container - alarm_waterlevel) and waterlevel_before > (size_water_container - alarm_waterlevel):
sendMail()
waterlevel_before = dist
time.sleep(1)
I'm trying to create a simulation where there are two printers and I find the average wait time for each. I'm using a class for the printer and task in my program. Basically, I'm adding the wait time to each of each simulation to a list and calculating the average time. My issue is that I'm getting a division by 0 error so nothing is being appended. When I try it with 1 printer (Which is the same thing essentially) I have no issues. Here is the code I have for the second printer. I'm using a queue for this.
if printers == 2:
for currentSecond in range(numSeconds):
if newPrintTask():
task = Task(currentSecond,minSize,maxSize)
printQueue.enqueue(task)
if (not labPrinter1.busy()) and (not labPrinter2.busy()) and \
(not printQueue.is_empty()):
nexttask = printQueue.dequeue()
waitingtimes.append(nexttask.waitTime(currentSecond))
labPrinter1.startNext(nexttask)
elif (not labPrinter1.busy()) and (labPrinter2.busy()) and \
(not printQueue.is_empty()):
nexttask = printQueue.dequeue()
waitingtimes.append(nexttask.waitTime(currentSecond))
labPrinter1.startNext(nexttask)
elif (not labPrinter2.busy()) and (labPrinter1.busy()) and \
(not printQueue.is_empty()):
nexttask = printQueue.dequeue()
waitingtimes.append(nexttask.waitTime(currentSecond))
labPrinter2.startNext(nexttask)
labPrinter1.tick()
labPrinter2.tick()
averageWait = sum(waitingtimes)/len(waitingtimes)
outfile.write("Average Wait %6.2f secs %3d tasks remaining." \
%(averageWait,printQueue.size()))
Any assistance would be great!
Edit: I should mention that this happens no matter the values. I could have a page range of 99-100 and a PPM of 1 yet I still get divided by 0.
I think your problem stems from an empty waitingtimes on the first iteration or so. If there is no print job in the queue, and there has never been a waiting time inserted, you are going to reach the bottom of the loop with waitingtimes==[] (empty), and then do:
sum(waitingtimes) / len(waitingtimes)
Which will be
sum([]) / len([])
Which is
0 / 0
The easiest way to deal with this would just be to check for it, or catch it:
if not waitingtimes:
averageWait = 0
else:
averageWait = sum(waitingtimes)/len(waitingtimes)
Or:
try:
averageWait = sum(waitingtimes)/len(waitingtimes)
except ZeroDivisionError:
averageWait = 0
enter image description here
I am making serial port communication device from a genious guy's work instructables.com.
It will measure the distance of the hamster's running in a day or month.
Using 4, 6 pin of the serial port cable, if the hamster runs, the device can count the numbers how many time did she run.
When I run the py file with Python27 like below, some errors occure.
"python hamster-serial.py progress.txt"
I cannot understand what's going on.
I am using windows8 and Python2.7 version.
Could you check my source, please?
import datetime
import serial
import sys
# Check for commandline argument. The first argument is the the name of the program.
if len(sys.argv) < 2:
print "Usage: python %s [Out File]" % sys.argv[0]
exit()
# Open the serial port we'll use the pins on and the file we'll write to.
ser = serial.Serial("/dev/ttyS1")
# Open the file we're going to write the results to.
f = open(sys.argv[1], 'a')
# Bring DTR to 1. This will be shorted to DSR when the switch is activated as the wheel turns.
ser.setDTR(1)
# The circumferance of the wheel.
circ = 0.000396 # miles
# Total distance traveled in this run of the program.
distance = 0.0
print "%s] Starting logging." % datetime.datetime.now()
start = datetime.datetime.now()
# This function a period of the wheel to a speed of the hamster.
def toSpeed(period):
global circ
seconds = period.days * 24 * 60 * 60 + period.seconds + period.microseconds / 1000000.
return circ / (seconds / 60. / 60.)
# Waits for the DSR pin on the serial port to turn off. This indicates that the
# switch has turned off and the magnet is no longer over the switch.
def waitForPinOff():
while ser.getDSR() == 1:
1 # Don't do anything while we wait.
# Waits for the DSR pin on the serial port to turn on. This indicates that the
# switch has turned on and the magnet is current over the switch.
def waitForPinOn():
while ser.getDSR() == 0:
1 # Don't do anything while we wait.
# The main loop of the program.
while 1:
waitForPinOn()
# Calculate the speed.
end = datetime.datetime.now()
period = end - start
start = end
speed = toSpeed(period)
# Increment the distance.
distance = distance + circ
waitForPinOff()
# We'll calculate the time the switch was held on too so but this isn't too useful.
hold = datetime.datetime.now() - start
# If the switch bounces or the hamster doesn't make a full revolution then
# it might seem like the hamster is running really fast. If the speed is
# more than 4 mph then ignore it, because the hamster can't run that fast.
if speed < 4.0:
# Print out our speed and distance for this session.
print "%s] Distance: %.4f miles Speed: %.2f mph" % (datetime.datetime.now(), distance, speed)
# Log it to and flush the file so it actually gets written.
f.write("%s\t%.2f\n" % (datetime.datetime.now().strftime("%D %T"), speed))
f.flush()
Well, ser = serial.Serial("/dev/ttyS1") is for a linux machine, on windows you'll need something like ser = serial.Serial("COM1") (you can check what COM do you need in the device manager).
As a side note,
def waitForPinOff():
while ser.getDSR() == 1:
1 # Don't do anything while we wait.
Will eat you CPU. You are better of with:
def waitForPinOff():
while ser.getDSR() == 1:
time.sleep(1) # Don't do anything while we wait.