BudBennett
Posts: 89
Joined: Fri May 17, 2013 2:45 pm
Location: Westcliffe, Colorado, USA

Detecting 250VAC voltage/current of deep well pump motor

Tue Aug 27, 2013 8:32 pm

My Project Rationale:

I have a home automation project that I am just beginning. A 600 foot deep well provides water to my house. The well only produces 8 gallons/hour. Therefore I also have a 1700 gallon cistern to store the water before it is pumped into the house for use. There is a float valve that turns on the deep well pump when the cistern level drops to a certain level below full and turns off the deep well pump when it is full again. The pump is a 1hp 250VAC induction motor.

My project is to monitor the status of the cistern to make sure that it doesn't run dry. I thought that the easiest way to do this would be to monitor how often, and for how long, the deep well pump is running. I assumed (assume = ass of u and me, more on that later) that simply detecting a voltage applied to the motor would be a good indicator of this, so I proceeded to design a circuit for detecting a 250VAC signal and presenting to the Raspberry Pi as a GPIO logic level.

Design Requirements:

1. Safety: 2500-3500V galvanic isolation between motor circuit and RPi circuit.
2. Cool Operation: low power dissipation…
3. Simple, two-wire interface: GND and GPIO signal to the RPi. No power supply signal required.
4. Small size - it has to fit inside the well "pump-saver" box that is mounted on the garage wall, and it won't be the only circuit in the box.

Some Background:

There is another forum thread that covers a lot of this: http://www.raspberrypi.org/phpBB3/viewt ... 01#p237701. Here is the circuit that I came up with after reading this posting and the associated links (and digging a bit deeper in other areas):
optoCapDetector.png
Fully populated OptoDetector
optoCapDetector.png (48.17 KiB) Viewed 14539 times
I think that this is IMHO probably the simplest and most straightforward approach. Design requirements #1-3 are met quite easily. Power dissipation is below 10mW.

Note that there are a few extra components and some values have changed. R1 and R2 are optional - they are only there if you don't want to be zapped by any residual charge on C1 if you happen to remove the circuit and put any of your body parts across the input terminals. Note that you need two of them if you use carbon or metal film resistors that are rated for working voltage between 125V and 200V. Most of us don't even know what the maximum working voltage of the small (i.e 1/4W) resistors that we have around the shop.

D1 can be removed if you use an opto-isolator that includes a reverse clamping diode, such as the H11AA1. The requirements for D1 are so relaxed in terms of reverse voltage and forward current that almost anything will work. The 1N4148 is cheap and ubiquitous.

R3 is there to protect the opto-isolator LED against transients, such as surges or spikes, that can happen on 250VAC wiring. Alternatively it can act as a fuse, but I think that a real fuse should be employed (more on that later).

C1 controls the amount of current flowing in the opto-LED. I've sized C1 to produce 5mA peak:

XC1 = reactance of C1 = 1/(2*Pi*F*C1) , where F = 60Hz and Pi = 3.1415926…

Ipeak = Vpeak/XC1 = sqrt(2)*250V*2*Pi*60*0.039uF = 5.2mA peak

Note that the sqrt(2)*VAC converts from RMS (root-mean-squared) voltage to peak voltage (for a sinusoid waveform).

Why 5mA instead of 10mA? There is an aging factor in opto-isolator LEDs. The LED output decreases over time, but the aging process is directly proportional to the LED current, so the aging process is half as fast with 5mA as 10mA. 5mA is plenty of LED current, even with a 20% CTR (Current Transfer Ratio) and considering temperature and aging, given that the load is only 3.3V/50k = 66uA. Also, according to data sheets that I've seen on common opto-isolators the 5mA CTR peaks about 20-30% above the 10mA CTR.

Why 5mA instead of 1mA? The opto CTR tends to fall off rapidly when you get below about 2mA. You can go there, but you will have to use a 4N35 or 4N36 or 4N37 or similar opto-isolator with a higher CTR (near 100% min).

C1 must be a safety rated (type X1 or X2) capacitor if it is going to be connected to the mains power. If you go to Digikey and plug in X2 and 0.039uF and 250V you only get one capacitor: http://www.digikey.com/product-search/e ... geSize=500 Note the size of this component: 0.689" L x 0.217" W x 0.512" H (17.50mm x 5.50mm x 13.00mm) This thing is huge! The fuse will not be small either, so this circuit won't work for me. But it could work for applications with more relaxed space requirements.

R4 prevents the opto NPN from turning on from Collector-base leakage current at high temperature. It degrades the CTR slightly. If you aren't worried about high temperature operation (even in a fault mode) then you can probably delete it.

The opto-isolator is acting as a switch to GND that closes every 1/60 seconds. C2 filters out the 60 Hz information and turns the output voltage into a steady state voltage that is either high when there's no AC voltage, or low when there is. The value of C2 is found by asking how much ripple you can tolerate on the output voltage. I thought 100mV would be acceptable - the VCEsat of the opto NPN when added to the ripple voltage must be less than the logic low level (VIL) of the GPIO input. When AC input voltage is present the opto NPN transistor will drive the output voltage to near GND every cycle and then turn off and let the GPIO pull-up resistor (50k min.) try to pull the capacitor toward 3.3V. You can treat the pull-up resistor as a constant current source since the voltage variation across it is small:

dV/dt = I/C gives:

C2 = 3.3V/50k * 1/(60Hz*100mV) = 11uF => 10uF is close enough

When the AC voltage turns off the rise time of the output voltage will be 65k * 10uF = 0.65 second. That should not be a problem for my application.

Effect of Component Failures:

These circuit should be evaluated for failure effects to see what bad things happen when components fail. I did some investigating of how and why electronic components fail. Here's some of what I found:
ResistorFailureModes.png
ResistorFailureModes.png (32.01 KiB) Viewed 14539 times
CapacitorFailureModes.png
CapacitorFailureModes.png (32.34 KiB) Viewed 14539 times
[1] Failure mode data was taken from a combination of resistor manufacturer's recommendations, MIL-HDBK-978, "NASA Parts Application Handbook," 1991; MIL-HDBK-338, "Electronic Reliability Design Handbook," 1994; "Reliability Toolkit: Commercial Practices Edition," Reliability Analysis Center (RAC), 1998; and "Failure Mode, Effects, and Criticality Analysis (FMECA)," RAC, 1993.

[2]Failure mode data was taken from a combination of MIL-HDBK-978, “NASA Parts Application Handbook”, 1991; MIL-HDBK-338, “Electronic Reliability Design Handbook”, 1994; “Reliability Toolkit: Commercial Practices Edition”, Reliability Analysis Center (RAC), 1998; and “Failure Mode, Effects, and Criticality Analysis (FMECA)”, RAC, 1993.


Capacitors normally fail with a short circuit. Film resistors most likely fail with an open circuit, but can fail just as often with a parameter change, and only fail shorted 5% of the time.

If R3, D1, F1, or the opto LED shorts or opens there is no harm done - the circuit continues operating or fails without further consequences. If C1 short circuits in the above circuit then R3 and the opto-LED get hit with all of the mains voltage. This causes the dissipation in R3 to increase from 2.7mW to 31W! Yes, it would be nice if it blew up and put itself out of it's misery. But can you count on it? And what happens to the shrapnel? The fuse is nicely contained in a glass tube.

Component Ratings:

Only use components rated to withstand the electrical environment to which they are subjected. Design for Reliability guidelines suggest that resistors be derated to 60% of maximum operating limits for voltage and power dissipation. This was an eye-opener for me. This is serious stuff and a failure could cause a fire or other serious issue that places the occupants of the house in danger. It gives credence to the people who say "Don't play with the mains."

Still Searching:

While this circuit is very attractive, and will satisfy the vast majority of applications out there, I'm working on a couple of other approaches that are probably not as general purpose, but will satisfy my objectives. I will post more info on that soon.

BudBennett
Posts: 89
Joined: Fri May 17, 2013 2:45 pm
Location: Westcliffe, Colorado, USA

Re: Detecting 250VAC voltage/current of deep well pump motor

Tue Aug 27, 2013 8:39 pm

Opto-Isolator 250VAC detector:

This is the circuit that I initially implemented:
optoDetector.png
optoDetector.png (26.98 KiB) Viewed 14536 times
Fairchild Semiconductor has a handy data sheet that covers multiple general purpose transistor output optos - you can find it here: http://www.mbari.org/mars/images/4N37.pdf. The data sheet specifies the transfer characteristics of the coupler with a forward current, IF, through the input LED @ 10mA. This is a problem. If the input resistors must generate 10mA with 125VAC across them then they will need to be rated for 2 Watts!

In order to make R1 and R2 larger the opto-isolator has to be operated at lower currents. I selected the 4N37 because its minimum Current Transfer Ratio (CTR) is 100%. There is not a load resistor in the circuit - it is provided by the RPi. The GPIO pull-up resistor is 50K minimum. Therefore the 4N37 must sink 3.3V/50k = 66uA max. And we'll increase that by 50% to make sure that the 4N37's output NPN is fully saturated (producing a low output voltage). So we now know that the output current is 100uA. The CTR of the 4N37 is estimated, using Figures 3 and 5 and iterating a bit, to find IF produces a CTR of about 0.15. (Operating on this part of the CTR curve is a bit scary due to the steep slope at IF = 1mA.) Therefore the input resistor must produce 100uA/0.15 = 667uA peak:

2R = 250VAC * sqrt(2)/667uA = 530 kOhm => 2 * 270kOhm

The power dissipation in each input resistor is:

P = V^2/R = 125VAC^2/270k = 58mW, which is about 25% of the rating for a 1/4W resistor.

How hot will the resistors get? Find a 1/4W wire wound resistor data sheet (try Digikey.com) and find that the dissipation factor is about 320-350C/W. Therefore these two resistors will have a steady state temperature of:

T = 0.058W * 320C/W + 25C = 44C (50C is too hot to touch for very long, so this is probably OK)

These Stackpole RNV14 resistors have a working voltage of 1150VRMS, 1600VDC, and can handle surges to 7kV. They are available from http://www.digikey.com.

Effects of component failure:

If either R1 or R2 short circuits (a 5% failure mechanism) then the power dissipation of the other resistor will quadruple to 0.212W, which is still below its rating. The circuit will continue to operate, but the temperature of the non-shorted resistor will increase to around 90C. This might cause the circuit to fail due to high operational temperatures, but at least it won't be catastrophic. So a fuse is not required. It might be a good idea to vent the enclosure though.

R1 and R2 have an operating voltage rating of 1150VRMS so they will probably survive surges and transients from the main power lines without issues and don't require any additional protection.

The opto LED aging factor is reduced by a factor of 15 compared to running the LED current at 10mA.

Breadboard Results:

It works without issue. I just cut a piece of perfboard and mounted the components, giving wide spacing to the input terminals and R1, R2. Here's a photo of the board mounted in a small plastic case that was used to store SMD components:
P1020541-s1.jpg
P1020541-s1.jpg (36.11 KiB) Viewed 14536 times
This particular piece of perfboard does not have any copper traces along the underside of the left edge of the board which would defeat the spacing effect. Sharp eyes will notice that the date code on the 4N37 is 1982...

Still not satisfied:

Though I like the simplicity of this circuit am concerned about its stability over time. I did an internet search for other opto-isolator circuits and found this article written by Peter Demchenko: http://m.eet.com/media/1133289/6512151.pdf which claimed to overcome excessive power consumption, uncertain switching and LED aging. I was able to simplify his approach down to this circuit:
optoDetector2.png
optoDetector2.png (46.71 KiB) Viewed 14536 times
Theory of operation:

During the AC cycle when VAC1>VAC2, C2 is charged to about 30V by R1,R2 and D2, and Q1 is off. When VAC1-VAC2 drops below 30V Q1 turns on, saturates, and forces about 5mA through the opto LED for about 600-800us while discharging C2. C2 remains discharged until VAC1 - VAC2 is positive again. So basically C2 stores energy and then releases it in a relatively short burst.

Now the LED current is back up in the sweet spot of the CTR curves for all of the generic opto-isolators. Power dissipation is about the same, perhaps a bit less. The added components are cheap and can be surface mount so don't require much additional space.

There is one concern - the on-time of the opto NPN is relatively short so it must be able to drive the output capacitor to a low voltage in that time period. Therefore I'm still using the optos with higher CTR specs (4N35/4N36/4N37).

Effects of component failure:

The above analysis still holds for R1 and R2, so a fuse is not necessary. If R1 or R2 short circuits then C2 will be charged to about 60V, hence the 100V rating. Q1 has a LVCBO = 80 V so there is no problem. D2 will withstand 100V reverse so it will not be affected.

The LED aging is unchanged from the earlier circuit since the average LED current has not changed.

Breadboard Results:

LTSPICE was used to verify circuit operation. I am very confident that the circuit will work, so I just created a PCB at OSH Park and am waiting for them to come in the mail.

masterdrain
Posts: 36
Joined: Fri Jun 07, 2013 7:44 pm
Location: Isle of Wight
Contact: Website

Re: Detecting 250VAC voltage/current of deep well pump motor

Tue Aug 27, 2013 8:55 pm

Why not use a small double-wound transformer? I have a very small example (approx 15x20x25mm) that gives 12V from the mains at 0.35VA which I bought from CPC-Farnell and there are various secondary voltages available. Rectify the output (one diode as half wave is enough) a series resistor and a 3.3V zener diode with a small electrolytic across it will drive the GPIO pins. A bit of spike suppression across the input may also be in order.

Iain Johnstone

masterdrain
Posts: 36
Joined: Fri Jun 07, 2013 7:44 pm
Location: Isle of Wight
Contact: Website

Re: Detecting 250VAC voltage/current of deep well pump motor

Tue Aug 27, 2013 9:02 pm

Sorry BudBennett, I jumped in halfway through your post as I followed a link and thus had not seen that there was a lot more to the problem and that you lived in the US, so CPC-Farnell is probably not a good idea.

Thank you for filling in your location as it is interesting to know where the 'posters' live - if only everybody would do this!

BudBennett
Posts: 89
Joined: Fri May 17, 2013 2:45 pm
Location: Westcliffe, Colorado, USA

Re: Detecting 250VAC voltage/current of deep well pump motor

Wed Sep 18, 2013 2:06 pm

Well, I received my PCBs and rated components and built the board. It works well - measured Vout ~ 200mV when 250VAC is present. End of story.
VmonPCB1-s.jpg
final voltage sensing PCB
VmonPCB1-s.jpg (48.8 KiB) Viewed 14302 times
The only problem is that it only reports half of the information that I need to determine the status of the well and cistern. It turns out that the guy who installed the pump and cistern wired the float switch to the output of the pumpsaver module. If the float switch is open then the pumpsaver output is constant 250VAC. If the float switch is closed, the pump runs until the float switch opens or the pump runs dry - in which case the pump saver output switches off for a set interval and then switches on the 250VAC. This cycle repeats until the cistern is full and the float switch is open.

So to find out when the pump is running it is required to sense the 8-9 Amps of current from the output of the pumpsaver. This is most easily done (at least for me) by using a current transformer (CT) and the following circuit.
currentSense.jpg
Current sense circuit
currentSense.jpg (54.93 KiB) Viewed 14302 times
The CT just slips over one of the pumpsaver output leads. No muss no fuss. You will have to disconnect the lead and reconnect it.

Don't even think about winding your own CT. CR Magnetics makes a nifty 10A rated CT with 1000 turns - so 9A to the pump equals 9mA out of the CT. The best deal that I found for this part was from Amazon.com (http://www.amazon.com/gp/product/B005CW ... UTF8&psc=1) for $8 USD and free shipping if you're an Amazon Prime member. The max continuous primary current is four times the rated current, so this component has some range to it. Insulation voltage is 3500VAC - similar to an opto-isolator.

A NOTE OF CAUTION: A CT WILL PRODUCE HIGH OPEN CIRCUIT VOLTAGES DUE TO THE HIGH TURNS RATIO. ALWAYS TERMINATE THE CT WITH AN APPROPRIATE LOAD BEFORE INTRODUCING IT INTO THE CIRCUIT AND APPLICATION OF POWER.

This is so much easier than messing with high voltage. The circuit above is all low voltage and component ratings don't mater much (except that you want to use a low current Schottky diode because the reverse leakage current of a high current diode - e.g. 1N5818 - will degrade your output voltage with no current applied to the point of making it look like a logic low.) You don't really need the resistor - I just put it in to provide a 2A threshold for a bit of noise rejection.

With 9Amps AC applied the output to the GPIO is roughly 0.4VDC. The CT voltage is clamped to about 1Vpeak, which is good since the input impedance is reflected back to the pump motor by the inverse square of the turns ratio (1000:1). The transistor Q1 looks like a 4 Ohm resistance to the CT therefore the equivalent resistance in series with the pump load is about 4 milli-Ohm, which is negligible.

The Code:

I generally suck at coding. But here is what I'm currently using to monitor the well and cistern. Emails are sent at boot, if the pump has run too long, if the pump hasn't run for a long time, and daily at 7:00am. If things are running normally I will get a status email once/day. With the cistern full, the pump runs at 18-24 hour intervals so sometimes the emails have nothing to report. I've still got a couple of fault modes to implement and I think that I'll add another sensor to monitor the outflow of the cistern…eventually.

Code: Select all

#!/usr/bin/env python3

# voltage sensor is on GPIO25
# current sensor is on GPIO24

"""
Well/Cistern Conditions:
Voltage Current
   Y      Y     Pump is running. Capture run time and run interval. Fault if run time > 1 hour.
   Y      N     Pump is not running, but cistern is full. Fault if pump inactive interval > 48 hours.
   N      Y     Condition can't happen if circuits are working properly - send email with fault info.
   N      N     Well has run dry. Cistern is not full. Pump will cycle at PumpSaver interval. Fault if cycle time > TBD.
"""

import RPi.GPIO as GPIO
import time
from datetime import datetime, timedelta
import smtplib, _thread #for email thread
from email.mime.text import MIMEText #for email

# define global variables
bootTime = lastRun = datetime.now()
runNumber = runtimeTotal= maxPumpInterval= maxRuntime = 0
minRuntime = None
minPumpInterval = None
email_flag = True
run_flag = False
gallonsTotal = 0
dryWell = 0
wellStatus = ""

class emailer:

    def __init__(self, user, userPW, emailServer='smtp.gmail.com') :
        ''' initiallize parameters '''
        self.__user = user
        self.__userPW = userPW
        self.__emailServer = emailServer        
        self.system_name = 'Well Monitor: '
        # Get boot time
        now = datetime.now()
        self.boot_time = ' %s' % now.strftime('%Y %b %d  %H:%M:%S')       
        print('Send Boot Email')
        self.send_status_email('Starting Up Bennett Well Monitor','Well monitor is booting up - may have been a power outage.')
            
    def sendemail(self, subject, message):
        # use thread to send email    
        _thread.start_new_thread(self.send_through_secure_smtp,(subject,message))
 
    def send_through_secure_smtp(self, subject, message):
        msg = MIMEText(message)
        msg['Subject'] = subject
        msg['From'] = self.__user
        msg.add_header('To', self.__user)
        msg.add_header('Cc', "")
        try:
            server = smtplib.SMTP(self.__emailServer, 587)
            server.ehlo()
            server.starttls()
            server.ehlo
            server.login(self.__user, self.__userPW)
            server.sendmail(self.__user, msg.get_all('To') + msg.get_all('Cc'), msg.as_string())
            server.quit()
            print("Successfully sent email.")
        except SMTPException:
            print("Error: Unable to send email.")   

    def send_status_email(self,message,status_text):
        now = datetime.now()
        time_now = ' %s' % now.strftime('%Y %b %d  %H:%M:%S')
        self.sendemail(self.system_name+message, '\n Message: '+message+ '\n'+status_text+'\n Boot time:'+self.boot_time+ '\n Time Now:'+time_now) 

class watchdog:
    ''' The watchdog is reset every time the pump runs. It is incremented every 60 seconds - the tick. If its
    timer exceeds the timeout number then it sends an email. '''
    
    def __init__(self,timeout = 120*60):
        self.timer = 0
        self.timeout = timeout
        print("Initializing the Watchdog")
        
    def petDog(self):
        self.timer = 0
        print("The dog was petted")
    
    def checkDog(self, tick):
        self.timer += tick
        #debug: print("dog timer incremented to {0}".format(self.timer))
        if (self.timer > self.timeout):
            mail.send_status_email("Watchdog Timer","Pump inactivity has exceeded the watchdog timer period.")
            self.petDog()
    
def calculateGallons(runTime, dry_well):
    """Pump:STA-RITE 1hp/5GPM. The pump runs at a higher rate when its head is lower: i.e. when the well is full.
    It is assumed that the float valve will let in a relatively constant amount of water.
    Therefore, if the pump runs longer, the well is not full (not at it's static level). So
    the gallons are constant until the well runs dry and then we assume that it can pump
    about 3 gallons/minute in that condition. """
    global wellStatus
    if(dry_well):
        gallons = runTime.seconds * 3/60 # assume 3 gallons/minute for head = 600 feet
        wellStatus = "Well is Dry and Cistern level is unknown"
    else:
        if ( runTime.seconds < 900 ):
            gallons = runTime.seconds *8/60 # assume 8 gallons/minute at head = 110 feet
            wellStatus = "Cistern is full and Well is full"
        elif (950 >= runTime.seconds < 1000 ):
            gallons = runTime.seconds *7.5/60 # assume 7.5 gallons/minute at head = 210 feet
            wellStatus = "Cistern is full and Well is less than 3/4 full"
        elif (1000 >= runTime.seconds < 1200):
            gallons = runTime.seconds *7/60 # assume 7 gallons/minute at head = 350 feet
            wellStatus = "Cistern is full and well is less than 1/2 full"
        else:
            gallons = runTime.seconds *5/60 # assume 5 gallons/minute at head = 500 feet
            wellStatus = "Cistern is full and well is less than 1/4 full"
    
    return gallons

def timeDelta2Str(seconds):
    """ takes seconds and formats it into a string of "hrs:minutes:seconds" """
    hrs,remainder = divmod(seconds,3600)
    minutes,seconds = divmod(remainder,60)
    timestr = "{0}:{1}:{2}".format(hrs,minutes,seconds)
    return timestr


def pumpRunning(channel):
    global runNumber,runtimeTotal, email_flag, lastRun, minPumpInterval, maxPumpInterval, minRuntime, maxRuntime, run_flag, gallonsTotal, dryWell, wellStatus
    # set the run_flag to True while the pump runs
    run_flag = True
    pumpStart = datetime.now()

    while (not GPIO.input(24)):
        time.sleep(1)
        runtime = datetime.now() - pumpStart
        if(runtime.seconds == 5):
            print("The pump is running.")
        # send email if pump runs too long
        if ( runtime.seconds == 60*60):
            mail.send_status_email("Pump Running Too Long", "Pump has been running for over 1 hour.")
    pumpStop = datetime.now()
    runtime = pumpStop - pumpStart
    pumpInterval = pumpStart - lastRun
    if (runtime.seconds > 5):
        dog.petDog()
        runNumber += 1
        # collect pump data
        if (runtime.seconds > maxRuntime):
            maxRuntime = runtime.seconds
        if (runNumber == 1):
            minRuntime = runtime.seconds
        elif (runtime.seconds < minRuntime):
            minRuntime = runtime.seconds
        if(pumpInterval.seconds > maxPumpInterval or runNumber == 1):
            maxPumpInterval = pumpInterval.seconds
        if (runNumber == 1):
            minPumpInterval = pumpInterval.seconds            
        elif (pumpInterval.seconds < minPumpInterval):
            minPumpInterval = pumpInterval.seconds
            
        #real time data:
        print ("Well pump started at ",pumpStart)
        print ("The pump ran for {0:.1f} minutes".format(runtime.seconds/60))
        print("Pump Data:")
        print("    Number of pump runs: ", runNumber )
        print("    Max runtime: {0:.1f} minutes".format(maxRuntime/60))
        print("    Min runtime: {0:.1f} minutes".format(minRuntime/60))
        print("    Max pump interval (hrs:min:sec): {0} ".format(timeDelta2Str(maxPumpInterval)))
        print("    Min pump interval (hrs:min:sec): {0}".format(timeDelta2Str(minPumpInterval)))
        
        lastRun = pumpStart

        # wait 10 seconds then check pump voltage to see if well ran dry
        # well ran dry if pump saver switched off voltage to pump (GPIO 25 is High) after run 
        time.sleep(10)
        dryWell = GPIO.input(25)
        gallonsTotal += calculateGallons(runtime, dryWell)
        print(" ")

        runtimeTotal += runtime.seconds
        print("Pump total runtime since last email = {0:.1f} minutes".format(runtimeTotal/60))
        print("Total gallons produced since last email = {0:.1f}".format(gallonsTotal))
        print("Well Status: "+wellStatus)
        print("")
        
        
    # turn off the pump_flag
    run_flag = False        

# set up GPIO pullups and interrupt on GPIO24
GPIO.setmode(GPIO.BCM)
GPIO.setup(24, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.setup(25, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.add_event_detect(24,GPIO.FALLING, callback=pumpRunning)

mail = emailer(user='your email address', userPW='your password', emailServer='your email server i.e. smtp.gmail.com')
# set the watchdog timeout for 48 hours - eventually make this dependent upon outflow activity of cistern which requires another sensor.
dog = watchdog(timeout=60*60*48)

try:
    print ("Waiting for falling edge on GPIO24")
    print ("email flag is", email_flag)
    while True:
        timeNow = datetime.now()
        if (timeNow.hour < 7):
            email_flag = False
        # send status email after 7:00 am, but only send one
        if (timeNow.hour > 6 and not email_flag):
            # if pump is running - wait
            while(run_flag):
                time.sleep(1)
            # send status email
            try:
                lastRun_time = ' %s' % lastRun.strftime('%Y %b %d  %H:%M:%S')
                # debug: print("Last Run Time:", lastRun_time)
                if (runNumber == 0):
                    statusText = "There is no pump data since it hasn't run since "
                    if (bootTime != lastRun):
                        statusText = statusText+"the last email.\nThe last time that the pump ran was {0}\n".format(lastRun_time)
                    else:
                        statusText = statusText+"boot.\n"
                else:
                    statusText = wellStatus+"\nNumber of pump runs: {0}\nGallons produced since yesterday = {1:.1f}\nMaximum Pump Interval (hrs:min:sec) = {2}\nMinimum Pump Interval (hrs:min:sec) = {3}\nMaximum Pump Run Time = {4:.1f} minutes\nMinimum Pump Run Time = {5:.1f} minutes\nThe last time that the pump ran was {6}".format(runNumber, gallonsTotal, timeDelta2Str(maxPumpInterval), timeDelta2Str(minPumpInterval), maxRuntime/60, minRuntime/60 , lastRun_time)
            except:
                statusText = "There was a problem with the data. Unable to update."
            mail.send_status_email("Daily Status Update",statusText)
            # print("Debug Status Text:",statusText)
            # set email flag and reset pump data
            email_flag = True
            # reset totals for another day
            if (runNumber > 0):
                minRuntime = maxRuntime
                minPumpInterval = maxPumpInterval
                maxPumpInterval = 0
            runNumber = runtimeTotal = maxRuntime = 0
            
            
        time.sleep(160)
        dog.checkDog(60)
            
except:
    GPIO.cleanup()  # clean up GPIO on CTRL+C exit

GPIO.cleanup()
This a typical status email when the well and cistern are full:

Message: Daily Status Update
Cistern is full and Well is full
Number of pump runs: 1
Gallons produced since yesterday = 118.3
Maximum Pump Interval (hrs:min:sec) = 17:49:50
Minimum Pump Interval (hrs:min:sec) = 17:49:50
Maximum Pump Run Time = 14.8 minutes
Minimum Pump Run Time = 14.8 minutes
The last time that the pump ran was 2013 Sep 17 10:50:12
Boot time: 2013 Sep 16 17:00:22
Time Now: 2013 Sep 18 07:01:25

Pi_G33K
Posts: 1
Joined: Thu Nov 28, 2013 9:27 pm

Re: Detecting 250VAC voltage/current of deep well pump motor

Thu Nov 28, 2013 9:34 pm

What a great post!*****

im a total n00b and i've been trolling the internet trying to find out how to detect 240VAC

what circuit design application did you uses?

BudBennett
Posts: 89
Joined: Fri May 17, 2013 2:45 pm
Location: Westcliffe, Colorado, USA

Re: Detecting 250VAC voltage/current of deep well pump motor

Fri Nov 29, 2013 12:02 am

I use Diptrace. It is free for non-commercial use under 300 pins. For simulation I'm using LTSpice - like everybody else. It is a bit of a pain to interface between the two because Diptrace just spits out a net list that must be imported into LTSpice, but it is workable.

Diptrace has schematic capture, auto-place/auto-route PCB layout software that works fine (on a Mac). It will generate error-free gerber files that OSH Park uses to fabricate PCB boards.

Bud.

s445203
Posts: 3
Joined: Fri Oct 24, 2014 1:50 pm

Re: Detecting 250VAC voltage/current of deep well pump motor

Fri Oct 24, 2014 6:03 pm

Bud, this is simply an amazing post! Thanks so much for taking the time to explain it in such detail.

I'm basically after exactly the same board to help me make a coffee machine project I'm tinkering a bit safer (I don't trust my heating circuit and want to detect mains voltage shorts). To do so I need to detect mains voltage detection from the Pi, and after a bit of looking (and asking) around it seems an opto-isolated circuit design is the right and proper way of doing it. Would you by any chance be amenable to sharing the OSH Park files you used? Completely understand if not.

BudBennett
Posts: 89
Joined: Fri May 17, 2013 2:45 pm
Location: Westcliffe, Colorado, USA

Re: Detecting 250VAC voltage/current of deep well pump motor

Fri Oct 24, 2014 10:59 pm

I shared the OSH Park project. Here is the permalink: https://oshpark.com/shared_projects/xWF5tbrv

Regards,

Bud

johndough
Posts: 254
Joined: Sun Jan 13, 2013 2:00 pm

Re: Detecting 250VAC voltage/current of deep well pump motor

Sat Oct 25, 2014 9:00 am

Hi

This topic reminded me of how water towers were monitored.

Large water tank 50 feet up, provided reserve for fire sprinklers etc, with a pulley wheel (gin wheel) on the edge of the tank.

A float was connected via a swr (steel wire rope) and the wire passed through the gin wheel and down to eye level (a drop of about 46 feet). An indicator board was put behind it for a visual check. The weight of the rope on the long side needs to balanced out with the short side, and the the float then moves up and down quite freely.

This layout provides several areas/points that could be monitored quite simply and independently of electricity if needed.

rsiedl
Posts: 1
Joined: Mon May 04, 2015 2:10 pm

Re: Detecting 250VAC voltage/current of deep well pump motor

Mon May 04, 2015 2:45 pm

Hey Bud, thanks for all the info you provide in this post. I'm trying to work out a way to monitor if a light is on or off.

I am still very new to electronics and the pi and am a bit confused about how you are reading the state of 250V. If the circuit only produces 200mV wont the pi always read that as off?
"A voltage near 3.3 V is interpreted as a logic one while a voltage near zero volts is a logic zero."

I've breadboarded your circuit, confirmed a 200mV output and query the state of pin 25 with: pwrstate = GPIO.input(25), but it always returns pwrstate = 0 no matter if the light is on or off. It does register the switch toggle event.

Any help you could provide would be greatly appreciated.

Cheers
Reagen

BudBennett
Posts: 89
Joined: Fri May 17, 2013 2:45 pm
Location: Westcliffe, Colorado, USA

Re: Detecting 250VAC voltage/current of deep well pump motor

Mon May 04, 2015 8:56 pm

Reagen,

The GPIO must be configured with an internal pullup or it will always have a low voltage when read by a voltmeter.

You must set the GPIO to be a pullup with the following python code:

Code: Select all

# set up GPIO pullups and interrupt on GPIO24
GPIO.setmode(GPIO.BCM)
GPIO.setup(25, GPIO.IN, pull_up_down = GPIO.PUD_UP)
You could also just put a 47k resistor to 3.3V to test the circuit as well.

Then the circuit output should read about 3.3Vdc with no AC voltage applied, and around 200-400mV with the 250VAC applied to it's inputs.

Bud

plugwash
Forum Moderator
Forum Moderator
Posts: 3439
Joined: Wed Dec 28, 2011 11:45 pm

Re: Detecting 250VAC voltage/current of deep well pump motor

Wed May 06, 2015 12:37 am

BudBennett wrote:R1 and R2 are optional - they are only there if you don't want to be zapped by any residual charge on C1 if you happen to remove the circuit and put any of your body parts across the input terminals. Note that you need two of them if you use carbon or metal film resistors that are rated for working voltage between 125V and 200V. Most of us don't even know what the maximum working voltage of the small (i.e 1/4W) resistors that we have around the shop.
Thanks for pointing this out, it seems resistors are marketed in a somewhat misleading way. Nievely you would expect a resistor to be rated to take the voltage required to drive it's rated power into it (e.g 500V for a 1 megohm 0.25W resistor) but it seems that many resistor ranges also have seperate voltage limits.

Still when I looked up some basic 0.25W carbon film resistors at one of my regular suppliers they specified a "maximum working voltage" of 250V and a "maximum overload voltage" of 500V so I wouldn't be too worried about using them in a mains application.

BudBennett
Posts: 89
Joined: Fri May 17, 2013 2:45 pm
Location: Westcliffe, Colorado, USA

Re: Detecting 250VAC voltage/current of deep well pump motor

Wed May 06, 2015 1:25 am

Reading down a bit further you'll find the following:

"Design for Reliability guidelines suggest that resistors be derated to 60% of maximum operating limits for voltage and power dissipation."

A working voltage of 250V doesn't cut it.

Bud.

ame
Posts: 3172
Joined: Sat Aug 18, 2012 1:21 am
Location: Korea

Re: Detecting 250VAC voltage/current of deep well pump motor

Wed May 06, 2015 1:40 am

I used a clip-on current transformer (CT) to detect my 250V 10A load. There is enough current induced in the CT to generate 3V across a small resistor. A half-wave rectifier and a cap. filter gives me a dc voltage that can be detected by the Pi.

You do have to clip the CT around only one lead going to the load, but the advantage is that it's completely non-contact so it's far safer than wiring into the mains circuit directly.

BudBennett
Posts: 89
Joined: Fri May 17, 2013 2:45 pm
Location: Westcliffe, Colorado, USA

Re: Detecting 250VAC voltage/current of deep well pump motor

Wed May 06, 2015 3:42 pm

Yes, I cover the CT interface in my rather longish post above. The half-wave rectifier will work, but I'm a bit paranoid about the stuff that you don't plan for - like a large transient spike that blows up the Pi. I'd rather replace a circuit that costs $0.25 than the entire PI, which is doing many other things for me as well. Alternatively, you could put a resistor to limit any current injected into the GPIO during a transient, but IC latch-up is a touchy thing and I'd rather not have to even think about it.

Bud.

jarrah31
Posts: 125
Joined: Wed Oct 10, 2012 10:16 am

Re: Detecting 250VAC voltage/current of deep well pump motor

Tue Oct 20, 2015 7:25 pm

Great thread, it's just what I'm after to monitor when my central heating / hot water relays are being turned on/off!

However I'm struggling to find the components in the UK. Based on your component list, I can't find the items in online electronics shops like CPC or Farnell. Is there a more descriptive way of identifying the parts by any chance please?

For example, a Google search for the opto-isolator "v02 4n37n" gives only 4 results. Also looking for a "Stackpole RNV14" doesn't find much either.

Thanks.

jarrah31
Posts: 125
Joined: Wed Oct 10, 2012 10:16 am

Re: Detecting 250VAC voltage/current of deep well pump motor

Tue Oct 20, 2015 7:36 pm

Also, I know it's not quite the spirit of this thread, but are there any off-the-shelf boards that do the same 240V ON/OFF detection that can be monitored by a Raspberry Pi?

BudBennett
Posts: 89
Joined: Fri May 17, 2013 2:45 pm
Location: Westcliffe, Colorado, USA

Re: Detecting 250VAC voltage/current of deep well pump motor

Tue Oct 20, 2015 11:48 pm

Jarrah31,

The Stackpole resistors have a working voltage of 1150vrms. Try searching for "resistor working voltage 1000V" or such to see what comes up. If you aren't going to use my custom PCB then you can probably get away with using 2 resistors in series instead of the Stackpole resistors.

As far as the opto isolators...any 4n35, 4n36, 4n37 should work in this application.

Hope this helps.

Bud.

jarrah31
Posts: 125
Joined: Wed Oct 10, 2012 10:16 am

Re: Detecting 250VAC voltage/current of deep well pump motor

Wed Oct 21, 2015 10:20 am

Hi Bud,

Thanks for your help, you pointed me in the right direction and I was able to find most of the components. However I've had difficulty with Q1 and C1 as described below, so would you mind helping find the right components for these two on the Farnell site please?

Q1 - BC865B SOT23, LVCBO 80V
http://uk.farnell.com/webapp/wcs/stores ... ,110191750
I've filtered the following options so far:
- Transistor Case Style: SOT-23
- Collector Emitter Voltage: 80V

I can't find the Manufacturer Part No BC865B within the above link, but if I search for BC865B it doesn't give me an 80V option:
http://uk.farnell.com/webapp/wcs/stores ... =110191750
The first link where I can filter by 80V seems most suitable, so should I choose one of the remaining 29 products?

C1 - Tantalum SMD 0805, 6.3VDC, 10u
http://uk.farnell.com/webapp/wcs/stores ... ,111854887
I've filtered by the following options:
- Tantalum SMD
- Capacitor Case: 0805
- Voltage Rating: 6.3V
- Capacitance: 10uF
I'm left with 16 options of varying Product Range. Can you advise which one please?

I've found the other items - they look ok to me but would you mind double checking please?

R1, R2 - http://uk.farnell.com/vishay-bc-compone ... dp/2056494
This has 1.6kV with a power rating of 250mW if this is ok?

D1, D2 - http://uk.farnell.com/multicomp/1n4148/ ... dp/9565124
This was a good match.

C2 - http://uk.farnell.com/avx/08051c104k4t2 ... dp/1833888
Good match as well

Opto Isolator - http://uk.farnell.com/vishay-semiconduc ... dp/1612456

I will be buying your PCB design too as it's a nice little solution to what I'm after. I plan to 3D print a case for it too.

Thanks!

BudBennett
Posts: 89
Joined: Fri May 17, 2013 2:45 pm
Location: Westcliffe, Colorado, USA

Re: Detecting 250VAC voltage/current of deep well pump motor

Wed Oct 21, 2015 1:55 pm

Jarrah31,

Both of your BC856B options are rated 80V for LVCBO (check the data sheet), so you can go either way.

The working voltages of the 1/4W resistors you found is 1600V, so they should work as well.

The tantalum capacitors you found vary in price according to tolerance and series resistance. In this application I used a 20% tolerance capacitor (and series resistance doesn't matter since it is not used for power filtering). As long as the leakage current is less than a few uA any of the 0805 sizes should work in the application.

Bud.

jarrah31
Posts: 125
Joined: Wed Oct 10, 2012 10:16 am

Re: Detecting 250VAC voltage/current of deep well pump motor

Wed Oct 21, 2015 2:47 pm

BudBennett wrote:Jarrah31,
Both of your BC856B options are rated 80V for LVCBO (check the data sheet), so you can go either way.
Hi Bud,

Thanks again for taking the time to help. Unfortunately I'm still not fully clear on the BC856B side of things for Q1.

The link that mentioned BC856B (http://uk.farnell.com/webapp/wcs/stores ... =110191750) in the Manufacturer Part No returns 18 items, all of which are rated -65 or -45V. I looked at the data sheet (http://www.farnell.com/datasheets/490737.pdf) for the top item but could only see a reference to VCBO of -80V. Is this what you refer to, even though it misses the L from LVCBO?

This link has 29 products (http://uk.farnell.com/webapp/wcs/stores ... ,110191750) but the Manufacturer Part No has no relation to BC856B.

Sorry about this, it's just not as clear cut as the others for what I should be choosing. :)

BudBennett
Posts: 89
Joined: Fri May 17, 2013 2:45 pm
Location: Westcliffe, Colorado, USA

Re: Detecting 250VAC voltage/current of deep well pump motor

Wed Oct 21, 2015 3:32 pm

I picked the BC856B because the min beta (current gain) is 220 and the CBO breakdown is 80V (and it's cheap - $0.04 at TaydaElectronics.com). Yes LVCBO is the same as BVCBO - it is the voltage that the device is able to withstand across the collector-base with the emitter open circuit. The CEO breakdown is not as important since the device is never operated in this mode. I would stick to the BC856B, but really any PNP BJT with at least 80V CBO breakdown and beta > 200 should work.

Bud.

jarrah31
Posts: 125
Joined: Wed Oct 10, 2012 10:16 am

Re: Detecting 250VAC voltage/current of deep well pump motor

Fri Oct 30, 2015 2:08 pm

Hi Bud,

My PCB's will be arriving soon so I hope to finalise my component list.

Still not fully sure on Q1, so can you confirm if the following item is ok please? The only thing that puzzles me is the VCBO in the data sheet gives a negative -80V whereas you suggest it should be 80V which is positive?

Link: http://uk.farnell.com/nxp/bc856b-215/tr ... dp/1081243
Manufacturer Part No: BC856B,215
Transistor Polarity: PNP
Collector Emitter Voltage V(br)cedo: -65V
Transition Frequency ft: 100MHz
Power Dissipation Pd: 250mW
DC Collector Current: -100mA
DC Current Gain hFE: 220
Transistor Case Style: SOT-23
No. of Pins: 3
Operating Temperature Max: 150c
MSL: MSL 1 - Unlimited
SVHC: No SVHC (15-Jun-2015)

Thanks again!

BudBennett
Posts: 89
Joined: Fri May 17, 2013 2:45 pm
Location: Westcliffe, Colorado, USA

Re: Detecting 250VAC voltage/current of deep well pump motor

Sat Oct 31, 2015 6:11 am

Hi Jarrah31,

Yes, the device you spec'd is good for Q1. The -80V CBO breakdown is because it is a PNP transistor instead of an NPN. Let me know how it turns out.

Bud.

Return to “Automation, sensing and robotics”