Solenoid Water Valve

Hey Andrew,
They are available from a few places in various sizes.
I purchased two from Core-Electronics in the 1/2 inch and 3/4 inch sizes and having the devices in hand found the 3/4 inch to be the easiest to test as I already have the standard 12mm hose connectors here.
I paid $16.70 and the unit came complete and ready to use - no mucking around.

ROB-10456 (x2) - 12V Solenoid Valve - 3/4" BSP

I now think I will use the 1/2 inch as a return valve to depressurise the system at the end of each water zone operation. I can also use this mechanism to both flush the water source and mix any liquid fertiliser I put into the one tonne of water I keep in the IBC water supply that I am going to house inside the glasshouse.

2 Likes

Thanks Liam,

Timing is a programmable ability and on the Pi 4 I can use environmental sensors to return values in Python ( providing I can call subprocesses ).

I asked this question up front before I bought ANY hardware and everyone said Pi was the way to go, so I invested there. With tomorrow’s delivery of bits, I should have enough hardware to make a functional POC ( Proof of Concept ) setup on the dining table. This will then allow me a little creative red wine to programme the Pi in a non-standard way with an infinite loop checking on various factors such as time = 6am do this, and humidity < 60% in zone x do that, and when light < 300 lumins close all the vents …

You got the idea. Then the plan is to build each separately and then run them under the over-arching infinite loop with the last condition being to pause for 300 seconds. I am thinking of counting the loop so I can QA reliability so the loop may be initially declared as i = 0 as a good starting point. the script says i = i + 1 as the first line with a condition of do until i = 0 . This way the condition is never met and I have a counter as well.

I also need some logging of the environmental sensors to check on efficiency and water (humidity) loss. I intend to just append the [ time, sensor and reading ] to a file. Well that is the pseudo code for it anyway at this early stage.

Any ideas, working code or links welcome.

2 Likes

I am unsure what you mean by subprocesses; the link provided by @Liam to threading is quite complex and I don’t think it’s necessary for what you want to do. I used threading for a Mini Robot Cart that played a tune at a random times, acted as a WiFi hot spot, video from the cart was displayed on a tablet and control via icons on the tablet screen. The main routine saved the path the cart followed and then tried to copy it. These were all different functions and threading worked best in that case.

Also, I am unsure of your level of understanding of Python, so if the following is already known, apologies.

Based on the above I thought of throwing together an example Python program but it is not as easy as I thought. Programming Python using Thonny on a PC can only go so far. It should be on a Raspberry Pi.

So this post is to say there will be another one, soon.

Cheers
Jim

2 Likes

Hey Jim,

I have simple requirement to get one python.py script to call another. It is as basic as, but not mentioned anywhere on google. For example in PowerShell, to call another PowerShell script, the syntax is to place on a new line ’ & other_name.ps1 ’

I have read up on doing this in python, but no answer thus far. Threading is my task to understand today ( for a Wednesday ).

I am a python newbie with a more than average PowerShell understanding, I am getting there too with Php. I have a reasonable ability to destructively learn code such as vBa for Microsoft Excel & Word.

I guessed what I wanted was complex at the start, thus the chunking it down and my approach. An example would be awesome & a great start.

Thanks in advance Jim.

3 Likes

Hey Liam,

Just touching base to get pointers on other google search terms for this.

2 Likes

Hi Andre, I’d check out Cores tutorial on Python.
If you’re just looking to call another .py file you would do so by creating your own module: Python Modules

When you mentioned running them in parallel then it would be a thread - more of a subprocess and not a subroutine. Just the semantics of programming. if you’re just logging data threading shouldn’t be necessary.

2 Likes

This is an example of using Python script. Not great, there are a few problems but might help in understanding. The GPIO lines are commented out due to running on PC. (no GPIO pins)

The main loop executes until a ctrl-c is pressed on the keyboard, allowing for program exit when testing. Most likely there will be no keyboard when in operation and no need for print statements.

It shows how to get system time, get seconds and minutes values since midnight, and how to use it to trigger events.

Note the use of time.sleep(300) means the Python script basically halts until the time is up. A better way is read the time at the start and save it. Use a small delay time.sleep(0.2) in the main loop. Read the time every loop and do something when 300 seconds have elapsed. Then reset the saved time to what it is now and do it all again. That way other things can happen in the main loop or sensors be checked.

Next post will contain stuff on threads and subprocesses.

Regards
Jim

#!/usr/bin/env python
import time
from datetime import datetime
#import RPi.GPIO as GPIO

#########################################################################
#########################################################################
#########################################################################
# Setup GPIO input pins
#GPIO.setmode(GPIO.BCM)

#GPIO.setup(6, GPIO.OUT)
#GPIO.setup(5, GPIO.IN, pull_up_down=GPIO.PUD_UP)

#########################################################################
def activate_solenoid(state):
    if state:
#        GPIO.output(6, GPIO.HIGH)
        print("Solenoid ON")
    else:
#        GPIO.output(6, GPIO.LOW)
        print("Solenoid OFF")
    return
#########################################################################
#########################################################################
# Main Run Loop
try:
    while True:

        now = datetime.now()
        midnight = now.replace(hour=0, minute=0, second=0, microsecond=0)
        seconds = (now - midnight).seconds
        minutes = int(seconds / 60)
#        if minutes > (6 * 60) and minutes < ((6 * 60) + 30):
        if minutes > (9 * 60) and minutes < ((9 * 60) + 5):
            activate_solenoid(True)
        else:
           activate_solenoid(False)

        Hour_Min=time.strftime("%H:%M")
        print(Hour_Min)
        print(minutes)

        time.sleep(300)                   # nothing happens while in sleep mode

#########################################################################
# End run Loop
except KeyboardInterrupt:           #crtl-C pressed on stdin
    print("Exit")
    
#########################################################################

Output from script

>>> %Run test01.py
Solenoid OFF
08:59
539
Solenoid ON
09:04
544
Solenoid OFF
09:09
549
2 Likes

@Andre191880
This is the code I used to create the threads. It is all contained within the one Python file. So it is not an example of running a second python script. I have removed all the excess code that is not related to threading.

I found this link which shows 3 ways to run another python script. It may or may not help. I have only used the method below. Happy to explore the others if you like and could post results here.

Regards
Jim

#!/usr/bin/env python
import os
import time
import datetime
import base64
import RPi.GPIO as GPIO
import multiprocessing
from random import seed
from random import random
from random import randint
from subprocess import call
from importlib import import_module
from flask import Flask, render_template, request, Response


#########################################################################
# Run as seperate process
#########################################################################
def server_Run():
  app.run(host='0.0.0.0', port=5000, threaded=True, debug=False)
  return

#########################################################################
# Run as seperate process
#########################################################################
def play_sounds():
  time.sleep(30)                # wait 30 secs before playing at startup
  while True:
    Sound_File = randint(1,29)
    play_file(Sound_File)
    audio_gap = randint(1,6) * 10
    time.sleep(audio_gap)
  return

#########################################################################
if __name__ == "__main__":

# Setup Global variables to indicate state of cart, Changed in web process, accessed in main
  manager = multiprocessing.Manager()
  move = manager.Value('c_char_p','Stop')        # c_char_p is type code for string
  button = manager.Value('c_char_p','StopRec')
  frameSave = manager.Value('c_char_p','takepic')

# Start web server and audio play as seperate processes
  p = multiprocessing.Process(target=server_Run)
  s = multiprocessing.Process(target=play_sounds)
  p.start()
  s.start()

#########################################################################
# Main Run Loop
  try:
    while True:

      if button.value == "Record":

      if button.value == "Play":

      if button.value == "StopRec":

      if button.value == "TakePic":

      if button.value == "Shutdown":
        p.terminate()
        s.terminate()
        GPIO.cleanup()                     # reset GPIO pins at end of program
        play_file(2)                       # play shutdown sound
        time.sleep(0.5)
        os.system("sudo poweroff")

      time.sleep(0.05)

#########################################################################
# End run Loop
  except KeyboardInterrupt:           #crtl-C pressed on stdin
    p.terminate()
    s.terminate()
    GPIO.cleanup()                         # reset GPIO pins at end of program
    play_file(2)                          # play shutdown sound

#########################################################################
2 Likes

Liam,

Sorry been offline with a mains power outage.
This sounds both challenging and hellishly scary. I shall read on and see how I go.
Tks.

Sorry, Not running two scripts at the same time other than the infinite loop waiting for the subprocess to finish & pass numbers back. Not really “in parallel” per say, & thanks for checking.

2 Likes

Jim,

Both these are GREAT and then some. SOO helpful. On the first skim I can see corrections to errors I have already made.
That link is perfect.
The answer to running another python script is also relatively easy thanks to the above information.
Run:
"
#!/bin/python
import subprocess
subprocess.run([‘python’, ‘08_subprocess_ver.py’])
print(f’Finished …')
"

It is not a big secret. Awesome Jim.

3 Likes

Update:
I now have fully functional code that runs a 4 valve Proof of Concept System on the kitchen table. Water pressure is needed to open the solenoid, but previous outside testing has been successful.
A master code running other snippets works a treat. Time to open another Forum Topic for control of the environmental sensors.
Thanks again to all contributors, suggestions and encouragers.

4 Likes