User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Sun Sep 02, 2018 4:22 am

tlfong01 wrote:
Sat Sep 01, 2018 7:53 am
Update 2 - 2018sep01hkt2126
1. I only studied Example 1 which is for a different application to Example 2. So of course I did not have the big picture and might have misunderstood something somewhere. ... it is very likely that my understanding is wrong.
3. I also read Example 3 and found that in an earlier post I was wrong in saying that two A3700s must be used to set two thresholds precisely.
4. My conclusion is that I have not gained enough knowledge to understand the problem, and I need to read the app notes again and think harder.

A3700 Studying Notes 1 - Checking out Vth+ and Vth-

I guess I misunderstood many things about A3700. So I am doing some basic experiments to find out which of my understanding is right, which is wrong.

My first experiment to measure the real values of Vh+ and Vth-. What I am going to do is similar to finding V+ and V- using different values of Rx, but this time without using any Rx, ie Rx = 0.

For easy reference, I have summarized the relevant values in the appendix below.

Appendix

HCPL3700M AC/DC to Logic Interface Octocoupler Datasheet Rev1.1 2015 Electrical Characteristics - Summary tlfong01 v1.0

1. Input Threshold Current

Test Condition - Vin = Vth+, Vcc = 4.5V, Vo = 0.4V, Io >= 4.2mA
Ith+ = 1.96mA min, 2.40mA typ, 3.11mA max
Ith- = 1.00mA min, 1.20mA typ, 1.62mA max


2. Input Threshold Voltage DC (Pins 2, 3)

2.1 Vth+
Test Condition - Vin = V2 - V3 (Pins 1 & 4 Open), Vcc = 4.5V, Vo = 0.4V, Io >= 4.2mA
DC Vth+ = 3.35V min, 3.80V typ, 4.05V max

2.2 Vth-
Test Condition - Vin = V2 - V3 (Pins 1 & 4 Open), Vcc = 4.5V, Vo = 2.4V, Io >= 100uA
DC Vth- = 2.01V min, 2.50V typ, 2.86V max

3. Input Threshold Voltage AC (Pins 1, 4)

3.1 Vth+
Test Condition - Vin = V1 - V4 (Pins 2 & 3 Open), Vcc = 4.5V, Vo = 0.4V, Io >= 4.2mA
AC Vth+ = 4.23V min, 5.00V typ, 5.50V max

3.2 Vth-
Test Condition - Vin = V1 - V4 (Pins 2 & 3 Open), Vcc = 4.5V, Vo = 2.4V, Io <= 100uA
AC Vth- = 2.87V min, 3.70V typ, 4.20V max

4. Hysteresis
4.1 Ihys = Ith+ - Ith- = 1.2mA typ
4.2 Vhys = Vth+ - Vth- = 1.3V typ
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Sun Sep 02, 2018 4:53 am

tlfong01 wrote:
Sun Sep 02, 2018 4:22 am
A3700 Studying Notes 1 - Checking out Vth+ and Vth-
My first experiment to measure the real values of Vh+ and Vth-. What I am going to do is similar to finding V+ and V- using different values of Rx, but this time without using any Rx, ie Rx = 0.
DC Vth+ = 3.35V min, 3.80V typ, 4.05V max
DC Vth- = 2.01V min, 2.50V typ, 2.86V max

Finding Real DC Vth+ and Vth- Values

It is easy to find the real Vth+ and Vth- values. I just vary the DC input to pins 2, 3, and note the Vth+ value when LED turns on, and Vth- when LED turns off. The results are listed below.

--------------------------
Num Vth+ Vth-
--------------------------
1. 3.78V 2.54V

2. 3.75V 2.52V

3. 3.75V 2.52V

4. 3.75V 2.54V
-------------------------

It took only 3 minutes to check one chip. I was casual and placed number 3 chip wrong side up, and found it not working. I replaced it and found it not working either. So I thought it was dead. But then I found I bent one pin the second time. I straightened the pint and tried again. The chip is working. My quick conclusion is that these cheap 2 yuan chips are strong guys.
Attachments
vth_test_2018sep0201.jpg
vth_test_2018sep0201.jpg (75.1 KiB) Viewed 5133 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Sun Sep 02, 2018 5:21 am

tlfong01 wrote:
Sat Sep 01, 2018 7:53 am
Using A3700 to detect DC12V power supply overloading or short circuit
For my home automation and control project, I am using a switching power supply with the following spec:
Input = AC220V
Output = 12VDC 5A
I know if the power supply is overloaded, over 5A (or short circuit), the output voltage will drop below 10V. So I set the lower threshold voltage a little bit below to
V-
= 9V
Then I can calculate
Rx
= (V- - Vth-) / Ith-
= (9V - 2.6V) / 1.3mA
= 4.92K
I don't need any uppper threshold V+, but just for completeness's sake, I can calculate
V+
= (Ith+ * Rx) + Vth+
= (2.5mA * 4.92k) + 3.8V
= 16.1V
I found that my chosen V- of 9V and calculated Rx = 4.92k, V+ of 16.1V matches the values in my experiment results of
V- = 8.6V, Rx = 4.7K , V+ = 15.6V
RE: GPIO.INPUT VOLTAGE LEVELS VS EDGE DETECTION Post by tlfong01 » 2018-Aug-27 Mon 4:06 pm
https://www.raspberrypi.org/forums/view ... 5#p1358137

Using A3700 to detect DC12V power supply overloading or short circuit

Now I am coming back to check if my Rx for detecting overloaded DC12V dropping to 9V is OK.

Since in last post I checked that the real average values of Vth+ and Vth- values of 3.75V and 2.54V are very close to the 3.8V and 2.6V I used from the App Note 1004 (I forgot to check the Ith+ and Ith- values, but I think they should be as close, so I am too lazy to return and check.

Now I am using a adjustable DC voltage 0V to 18V to check if using the calculated Rx = 4.92K, overloaded drop to 9V can be detected.
Last edited by tlfong01 on Sun Sep 02, 2018 7:20 am, edited 1 time in total.
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Sun Sep 02, 2018 7:07 am

tlfong01 wrote:
Sun Sep 02, 2018 5:21 am
Now I am using a adjustable DC voltage 0V to 18V to check if using the calculated Rx = 4.92K, overloaded drop to 9V can be detected.

A3700 to detect 12V DC PSU overloaded to 9V

So I took out my 30V psu, set to 12V, to simulate the initial work condition. My test plan was as below:

1. Start with 12V, normal power without loading, check green LED on.

2. Decrease psu to 9V, to pretend psu overloaded, LED should go off.

3. Increase psu to 16V, LED should go on again.

4. Switch off psu, restart psu at 12V, LED on, ...

Test results

So I started with 12V as planned, but no LED on, I lowered to 8V, no LED off or on. No smoke, no explosion. Strange. I was losing confidence.

The lightning fast kung fu fighter suddenly realized that he had forgotten to move back the Rx = 5K!

It was too late.

The A3700 was dead.

No postmortem is necessary - just arrogantly carelessness.

RIP Sunday 2018sep02

Gloomy Sunday - Billie Holiday 6,822,634 views
https://www.youtube.com/watch?v=KUCyjDOlnPU
Attachments
a3700_test_2018sep0201.jpg
a3700_test_2018sep0201.jpg (147.98 KiB) Viewed 5101 times
Last edited by tlfong01 on Mon Sep 03, 2018 12:56 am, edited 1 time in total.
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Sun Sep 02, 2018 1:59 pm

tlfong01 wrote:
Sun Sep 02, 2018 7:07 am
A3700 to detect 12V DC PSU overloaded to 9V
So I started with 12V as planned, but no LED on, I lowered to 8V, no LED off or on. No smoke, no explosion. Strange. ...
It was too late.
The A3700 was dead.

A3700 found not very good for 12V DC/AC applications

I looked back what I have been doing.

1. I used an adjustable psu as input signal to 4 samples of A3700, with Rx = 0, to find the real values of Vth+ and Vth-. I surprising found the fourth samples have consistent values around 3.75V, and 2.52V, very close to the typical values (3.8V, 2.6V) specified in the Fairchild data sheet.

2. I then calculated Rx = 4k9 for detecting a 12VDC psu overloaded power drop to 9V (V-). The cannot-be-set-by-designer V+ is 16V.

3. I started with adjustable 12V to test the A3700 with Rx = 4k7. I found that this won't work, because V+ = 16V is too high for the A3700 to start working with initial value of 12V, though I did find it works for the range 8V to 16V. The exact results are 15.8V/8.6V, 15.0V/8.3V, 15.0V/8.6V, 15.2V/8.4V, closely matching to my calculation.

4. I checked my earlier charts of Rx vs V+/V- (see appendix below) and found that the lowest V+ to make sure the A3700 works is Rx = 2k4, and V+ = 9,8V.

But then the corresponding unsettable V- is only 5.6V, not a good value for detecting overloading voltage drop.


Quick and dirty conclusion

A3700 is not very suitable for lower power 12V DC or AC applications.

Minimal, Complete, Verifiable, NoProblem Example (MCVNE) A3700 setup

I have attached a picture of the minimal setup for future reference and troubleshooting. This A3700 setup uses only the 555 timer based 4Hz signal to switch KY019 relay controlled 24VAC power, using Rx = 4k7, input filtering by 4.7uF x 2, Vcc by pass cap = 0.1uF, pull down = 4k7 + green LED.

This is the end of tests using 555 based signal to test A3700. Next time I will start using Rpi to detect the A3700 Vo output.

Appendix

RE: GPIO.INPUT VOLTAGE LEVELS VS EDGE DETECTION Post by tlfong01 » 2018-Aug-27 Mon 1:24 pm
https://www.raspberrypi.org/forums/view ... 5#p1358102
Attachments
a3700_stage1_2018sep0302.jpg
a3700_stage1_2018sep0302.jpg (176.58 KiB) Viewed 5043 times
Last edited by tlfong01 on Mon Sep 03, 2018 5:24 am, edited 2 times in total.
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Mon Sep 03, 2018 4:13 am

petermeigs wrote:
Sat Sep 01, 2018 5:57 pm
1. The problem I see in what you are doing is that the power supply can never reach V+. And if you set V+ to say 90% of the output rating of the power supply, V- will be too low.

2. We can then calculate the max voltage we will tolerate across resistor and a voltage where we consider the current ok. Here voltages above V+ are bad news and voltages below V- are good news.

3. After thinking about this for a while, I realized putting a resistor in series will not be practical, at least not directly with a A3700 dealing with 12vdc and 5amps.

4. The reason is that we would need a resistor capable of causing a voltage drop of at least 6v, the lowest voltage needed for V-th+ (the V-ihc1 case). That would only leave 6v for the rest of the circuit.

5. I suppose we could get transistors involved to use a lower resistance. That would mean a lower voltage drop and then amplify it with a transistor to so the 6v threshold falls in a suitable range suitable range. Perhaps there is a better way. --

A3700 Brainstorming Critizing Notes

1 - Yes, me playing with DC12V do have a problem. And you playing with AC24V too have the same problem. The cause of the problem is that A3700 is not designed for, or at least not for low power applications.

I will for sure use A3700 for detecting power loss of my quad KY019 relay box switching 220VAC, driving induction motors. But for the other three relays in the same box switching 12VAC, 24VAC, 12VDC, my first thought is that it is wrong to use A3700 in detect power loss, not to mention power drop due to overloading.

You already pointed out my mission impossible: setting V- to the required value it won't work, because the unsettable V+ becomes too high. By the same token, if I set V+ low enough so that it works, then the unsettalbe V- does not meet my requirement. In short, for my lower voltage applications, either DC or AC, A3700 is not usable.

2, 3, 4, 5 - When I first saw you using MCP3008, I said I once played with MCP3208. My brainstorming idea was to use one MCP3208 differential channel to closely monitor a single diode rectified AC12V or AC24V, and log any big data you want, black out, brown out, power drop, daily usage pattern, you name it, ...

My friends down under are now having big trouble because they don't have enough rain and therefore no water for their crops, plants, gardens, green houses, so I am trying to help by sharing my hobbyist knowledge of humidity and temperature sensor, smart relay switching water pumps, etc to efficiently use scarce water resources, ...

Australia Drought: New South Wales farmers say drought worst ever - TRT World 2018aug01
https://www.youtube.com/watch?v=pNop3uNPEhc

Perhaps my hobbyist design is also usable in some place that never rains, ...

It Never Rains In Southern California - Albert Hammond 1972 - 4,861,685 views
https://www.youtube.com/watch?v=5UA3kFSvdN0
Last edited by tlfong01 on Mon Sep 03, 2018 6:30 am, edited 1 time in total.
I am an electronics and smart home hobbyist.

Brandon92
Posts: 949
Joined: Wed Jul 25, 2018 9:29 pm
Location: The Netherlands

Re: GPIO.input voltage levels vs edge detection

Mon Sep 03, 2018 5:26 am

There are also current sensors that could do this trick.
And this could also be an option. Then you can monitor the power consuming.
However there are many options more to monitor the current.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Mon Sep 03, 2018 8:58 am

Brandon92 wrote:
Mon Sep 03, 2018 5:26 am
There are also current sensors that could do this trick.
And this could also be an option. Then you can monitor the power consuming.
However there are many options more to monitor the current.

How about this 10 dollar toy?

RE: SMART POWER CONSUMPTION MONITORING SYSTEM - Post by tlfong01 » 2018-Sep-03 Mon 4:50 pm
https://www.raspberrypi.org/forums/view ... 5#p1360775
I am an electronics and smart home hobbyist.

petermeigs
Posts: 97
Joined: Thu Mar 23, 2017 1:34 pm
Location: Los Altos, California

Re: GPIO.input voltage levels vs edge detection

Mon Sep 03, 2018 7:50 pm

Status update on water meter project
testdetect24vac-mcp23017-a3700.png
testdetect24vac-mcp23017-a3700.png (53.54 KiB) Viewed 5009 times
This post started with a project I have where I would like to determine
which of 16 possible home irrigation lines are running. I am in Northern
California and it does rain here but only from October to March and rarely
the rest of the year. From March to October, we use water that comes from
the snow pack in the Sierra's. The Lake Tahoe area is a good ski area and
provides our water for the following year. Because some years do not get
good snowfall, we must always be careful to use what we need but be as
frugal as we can when we use it. My idea has been to us a Smart
Irrigation Controller (I have a Rachio). It can check the weather via the
internet and has a rain detector to skip cycles.

What it does not do is to tell me the volume of water actually dispensed
through each irrigation valve. If cute but pesky squirrels have chewed a
hole in a line or we have some other kind of leak, we may use too much
water. Similarly, we might have a clogged line or broken solenoid and not
be dispensing enough water.

I plan to add a water meter with a flow sensor that will close a circuit each time a unit of water passes through it. Monitoring that, I can know the total amount of water used by the system. Using the circuit I am working on (once it works properly, I can calculate when each value goes off and on and thereby attribute the water used to the line that was on. Only one line is on a time because of the water pressure.

Included in this post is the current state of my circuit. At this time, it only implements 1 24vac input through a single HCPL3700 (A3700). Thanks to the help of tlfong01 and Brandon92, I think we are getting close here. Their posts have provided a lot of insight and suggestions that has help me tremendously. (Thank you guys). It has been entertaining as well.

In particular, I might not have used the MCP23017 had it not been for their posts. This item greatly simplifies the circuit and the code to handle it as well.

One of my concerns is to make sure we do not exceed the power available on the Raspberry pi. It might even be nice if we can implement all of this on a raspberry pi zero-w.

Code: Select all

#!/usr/bin/env python3
import smbus
import sys
import RPi.GPIO as RPIGPIO
import time
import traceback
from datetime import datetime
from datetime import timedelta

bus = None
starttime = None
state = None


GPIOINT = 22 # gpio connected to port A interrupt line.
RELAY   = 23 # relay to turn on 24vac

DEVICE_ADDRESS = 0x20
# default addresses
BANKA = 0
BANKB = 1
IODIR      = 0x00 # Pin direction register A
IPOL       = 0x02 # Input polarity regsiter A
GPENTEN    = 0x04 # Interrupt on change pins A
IOCON      = 0x0a # Config register A  Bank, Mirror, SEQOP, DISSLW, HAEN, ODR, TPOL, N/U
GPPU       = 0x0c # 100k ohm pullups A
GPIO       = 0x12 # GPIO pins
INTF       = 0x0e # interupt flag register

def readREG(port, intbits = 0xFFFF):
    # need to separate bus reads because we don't want to clear an interupt we aren't handling
    # intbits will be non-zero in top 8 and/or bottom 8
    pinAdata = 0
    pinBdata = 0
    if (intbits >> 8) & 0xFF:
        pinBdata = bus.read_byte_data(DEVICE_ADDRESS, port + BANKB)
    if intbits & 0xFF:
        pinAdata = bus.read_byte_data(DEVICE_ADDRESS, port + BANKA)
    return (pinBdata << 8) | pinAdata

def writeREG(port, data):
    bus.write_byte_data(DEVICE_ADDRESS, port + BANKB, (data >> 8) & 0xFF)
    bus.write_byte_data(DEVICE_ADDRESS, port + BANKA, data & 0xFF)
    return None

def my_callback(channel):
    # Note: Multiple interupts can occur simultaneously
    global bus
    gpiolevel = RPIGPIO.input(GPIOINT)
    intfBA = readREG(INTF)
    if gpiolevel:     # if port 25 == 1
        print("level up clear interrupt")
        pinBAbits = readREG(GPIO, intfBA)
        print("----------level up infBA= 0x%04x, pinBA= 0x%04x" %(intfBA, pinBAbits))
    else:                  # if port 25 != 1
        print("level dn clear interrupt")
        pinBAbits = readREG(GPIO, intfBA)
        print("----------level dn infBA= 0x%04x, pinBA= 0x%04x" %(intfBA, pinBAbits))
    return

def init():
    global bus
    bus = smbus.SMBus(1)    # 0 = /dev/i2c-0 (port I2C0), 1 = /dev/i2c-1 (port I2C1)

    # port A & B all in excpet for low order 3
    writeREG(IODIR, 0xFFF8)

    # reverse input values.  This is because A3700 is low when upper threshold is detected
    writeREG(IPOL,  0xFFF8)

    # Activate all internal pullup resistors at Port A & B for output:
    writeREG(GPPU, 0xFFF8)

    # disable interupts on change
    writeREG(GPENTEN, 0x0000)

    # clear any previous interrupts
    pinBAbits = readREG(GPIO)

    # enable interupts on change
    writeREG(GPENTEN, 0xFFF8)

    # I/O Expander config register. Set INT pins internally connected, Interupt polarity Active-high
    writeREG(IOCON, 0x4242)

    time.sleep(.0100)

    RPIGPIO.setwarnings(False)
    RPIGPIO.setmode(RPIGPIO.BCM)

    RPIGPIO.setup(GPIOINT, RPIGPIO.IN)    # set interrupt from MCP23017
    RPIGPIO.setup(RELAY, RPIGPIO.OUT)    # set GPIO24 as output
    RPIGPIO.output(RELAY, False)

    # when a changing edge is detected on OPTO1 port, regardless of whatever
    # else is happening in the program, the function my_callback will be run
    RPIGPIO.add_event_detect(GPIOINT, RPIGPIO.RISING, callback=my_callback)
    # RPIGPIO.add_event_detect(GPIOINT, RPIGPIO.BOTH, callback=my_callback)
    # RPIGPIO.add_event_detect(GPIOINT, RPIGPIO.FALLING, callback=my_callback)
    pass


def main():
    global bus
    global starttime
    global state # 0 = not started, 1 = on, 2 = off, 3= zero reached
    voltimelist = []
    sleeptime = 0.005  # 5ms
    print("start=========================================================")
    init()
    starttime = datetime.utcnow()

    # turn on lights
    print ("---------- 0x07 lights on")
    writeREG(GPIO, 0x0007)

    pinData = readREG(GPIO)
    print ("0x07 lights on 0x%04x"%pinData)

    time.sleep(2)
    print ("----------- 0x07 lights off")
    writeREG(GPIO, 0x0000)
    pinData = readREG(GPIO)

    print ("lights off 0x%04x"%pinData)

    starttime = datetime.utcnow()
    measuretime =  datetime.utcnow() - starttime
    # voltimelist.append([datetime.utcnow(), -1, state, GPIO.input(OPTO1), measuretime])
    print ("----------- Relay on")
    RPIGPIO.output(RELAY, True)
    state = 1
    print("ON, state = " + str(state))

    while state < 3:
        elapsedtime = datetime.utcnow() - starttime
        if elapsedtime.seconds > 4 and state != 2:
            print ("----------- Relay off")
            RPIGPIO.output(RELAY, False)
            state = 2
            print("OFF, state = " + str(state))

        if elapsedtime.seconds > 5:
            print("TIMEOUT, state = " + str(state))
            state = 3

        time.sleep(sleeptime)
        # if elapsedtime.seconds > 4:
        #     print("TIMEOUT, state = " + str(state))
        #     break
        pass

    # while (True):
    #     pin = RPIGPIO.input(GPIOINT)
    #     print( "pin = %i"%pin)
    #     time.sleep(1)
    #
    pass

if __name__ =='__main__':
    try:
        main()
    except KeyboardInterrupt:
        pass
    except:
        traceback.print_exc()
        pass
    RPIGPIO.cleanup()
    print ("Done")


This code does implements interrupt driven handling of the circuits. It is only demo code at this point and there is no logic to actually do anything except print out that a 24vac circuit came on and then shut off.

It uses plain ol' GPIO code and plain ol' smbus. Other libraries are available but these work pretty nicely. Interrupts are implemented by writing the MCP23017 INTA output to GPIO-22 on the raspberry pi. The input GPA and GPB pins on the MCP23017 are reversed in polarity to make it a little more natural to deal with the fact that the A3700 is high when the 24vac is off. This lets us see a "1" on a GPA/B port when the 24vac is on and "0" when off. By setting a callback on a RISING GPIO-22, we can get the interrupt as it occurs.

I also set the MCP23017 to OR the interrupt A and B together so that a change on any input on Bank A or B would result in a change in INT A connection.

Lastly, I reversed the "active" state of the of the INTA line so that it would RISE when the interrupt is to occur and FALL when the interrupt is cleared.

Hopefully, this all becomes more clear when looking at the code and the MCP23017 datasheet. Note that are both I2C versions and SPI versions and I am using the I2C version.

More to follow ---

Brandon92
Posts: 949
Joined: Wed Jul 25, 2018 9:29 pm
Location: The Netherlands

Re: GPIO.input voltage levels vs edge detection

Mon Sep 03, 2018 8:10 pm

Good to hear that our information is helping you.
petermeigs wrote:
Mon Sep 03, 2018 7:50 pm
I plan to add a water meter with a flow sensor that will close a circuit each time a unit of water passes through it. Monitoring that, I can know the total amount of water used by the system. Using the circuit I am working on (once it works properly, I can calculate when each value goes off and on and thereby attribute the water used to the line that was on. Only one line is on a time because of the water pressure.
For or fish pond I'm also want to measure if the pomp is still working good and if it is not clogged. So, because there could be also plants true the tube. And because the "fan" provide some resistance. There is some energy wasted. So, I bought this sensor (note: first link). To see if the pressure is changed over time. And this can give my information if the pump is still operation at his best performance. I think it is also possible to calculate the flow in the tube by a sensor like this, but this is beyond the scope of my project.

This is my idea, I have already the sensor. But it is not tested yet.

And topic contains a lot of information about the io expander. Its at the back and tlfong01 is using this part a lot.

edit
By the way, is you goal to make a PCB of this project?

petermeigs
Posts: 97
Joined: Thu Mar 23, 2017 1:34 pm
Location: Los Altos, California

Re: GPIO.input voltage levels vs edge detection

Mon Sep 03, 2018 8:22 pm

You might look at a flow meter too: Something like
https://www.amazon.com/Uxcell-Thread-Ef ... eter+pulse

Or search on "water flow meter pulse". If you only have 1 line, you would not need all the circuit detection stuff.

Brandon92
Posts: 949
Joined: Wed Jul 25, 2018 9:29 pm
Location: The Netherlands

Re: GPIO.input voltage levels vs edge detection

Mon Sep 03, 2018 8:39 pm

Thanks for the search term.
But, to give you a idea about my situation: the tube that is connected to the pump has a diameter of 50mm. And the pump is capable of delivering, at his max stetting, around the 20000 liter per hour. And a sensor for that would be expansive and it could get stock if the pump sucks something up.

petermeigs
Posts: 97
Joined: Thu Mar 23, 2017 1:34 pm
Location: Los Altos, California

Re: GPIO.input voltage levels vs edge detection

Tue Sep 04, 2018 6:04 am

Wow! When you say "pond" you aren't talking about something tiny. I see your problem.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Thu Sep 06, 2018 7:29 am

Brandon92 wrote:
Mon Sep 03, 2018 8:39 pm
to give you a idea about my situation: the tube that is connected to the pump has a diameter of 50mm. And the pump is capable of delivering, at his max stetting, around the 20000 liter per hour. ...

Resetting Crazy MCP23017

Wow, my tiny pump is only 800L/hr, so it is 20000 / 800 == 25 times smaller than your huge pump!

(Pump) RE: RELAY MODULE KY-019 5V Post by tlfong01 » 2018-Jul-12 Thu 3:08 pm
https://www.raspberrypi.org/forums/view ... 0#p1339911
https://www.raspberrypi.org/forums/view ... 0#p1339931

My tiny pump does have a huge neighbour though, a huge 28 floor building elevator motor switching on/off 24/7, generating electromagnetic interferences (EMI) which I suspect make my 4 floors below AM radio receiver intermittently noisy. I think it will also make any nearby MCP23017 crazy. So I guess I need to check from time to time if the MCP23017 at the rooftop garden has become dead and reset it again.
Attachments
rooftop_garden_2018sep0601.jpg
rooftop_garden_2018sep0601.jpg (120 KiB) Viewed 4935 times
I am an electronics and smart home hobbyist.

petermeigs
Posts: 97
Joined: Thu Mar 23, 2017 1:34 pm
Location: Los Altos, California

Re: GPIO.input voltage levels vs edge detection

Thu Sep 06, 2018 1:57 pm

Very interesting... Do you think it would help to put your circuit on a UPS and place it in a Faraday cage to shield it from the electronically noisy environment?

The point of the UPS would be to put a battery between your circuit and the power.

Brandon92
Posts: 949
Joined: Wed Jul 25, 2018 9:29 pm
Location: The Netherlands

Re: GPIO.input voltage levels vs edge detection

Thu Sep 06, 2018 5:15 pm

The pump (DM -Vario 20 000) itself is not that big and it looks like this. But it is not a high pressure pump. And we are using it for this application, this is not ours.

If you have issues with the I2C connection in a electrically noisy environments you could consider to use a differential I2C-bus*, then you have no issues any more. If you filter the powersupply also at the end. And if the the voltage drop is to large, you could consider a ac power supply to the same wire, and convert it at the rooftop to a stable dc voltage.
petermeigs wrote: ..and place it in a Faraday cage to shield it from the electronically noisy environment?
..
Then you need also to shield the incoming cables. If you don't do that, the noise comes in via the wire. But, it could help is if the (wire) connection is filtered. You cant try this by yourself. If you have something like this. Place it on a metal place (or foil) and place a FM radio in the middel. If you place the colander over the radio, you don't hear the radio station. If you "press" a copper wire inside the colander, the radio is working again :)

Also one general thing. When I look at the pictures of the test setup I missing the decouple capacitor (100nF), this capacitor also contribute to a stable voltage rail for the IC. If the IC need to get a "large" amount of power. The capacitor will provide that power first.

*Is a example, there could be better ones for you

petermeigs
Posts: 97
Joined: Thu Mar 23, 2017 1:34 pm
Location: Los Altos, California

Re: GPIO.input voltage levels vs edge detection

Thu Sep 06, 2018 11:04 pm

I am doing some tests to see what happens if the mcp23017 gets changes too quickly.

On my raspberry PI i have the code setup as in my last circuit diagram. However, instead of connecting the A3007 Vo to any of the MCP23017 pins, I have connected 5 raspberry pi zero gpio output pins to GPB0,1 and GPA7,6,5 on the MCP23017. Then I run the following code of the raspberry pi zero:

Code: Select all

#!/usr/bin/env python2.7
## on esp
import sys
import RPi.GPIO as GPIO
import time
from datetime import datetime
from datetime import timedelta
from time import sleep     # this lets us have a time delay (see line 12)
import traceback

lines = [
    {
        "name" : "BankA 7",
        "color" : "blue",
        "mcp"  : "0x0080",
        "gpio" :  21
    },
    {
        "name" : "BankA 6",
        "color" : "gray",
        "mcp"  : "0x0040",
        "gpio" :  20
    },
    {
        "name" : "BankA 5",
        "color" : "orange",
        "mcp"  : "0x0020",
        "gpio" :  26
    },
    {
        "name" : "BankB 0",
        "color" : "yellow",
        "mcp"  : "0x0100",
        "gpio" :  16
    },
    {
        "name" : "BankB 1",
        "color" : "brown",
        "mcp"  : "0x0200",
        "gpio" :  19
    },
]


#port init
def init():
    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)
    # set up the SPI interface pins
    for line in lines:
        GPIO.setup(line["gpio"], GPIO.OUT)
        GPIO.output(line["gpio"], True)
    pass


def main():
    init()
    slice = 4
    for line in lines: # [slice : slice+1]:
        print("----------- On: %s, gpio=%d, mcp=%s"%(line["name"], line["gpio"], line["mcp"]))
        GPIO.output(line["gpio"], False)
        sleep(5)
        print("Off: %s, gpio=%d, mcp=%s"%(line["name"], line["gpio"], line["mcp"]))
        GPIO.output(line["gpio"], True)
        sleep(0.1)


if __name__ =='__main__':
    try:
        main()
    except KeyboardInterrupt:
        pass
    except:
        traceback.print_exc()
        pass
    GPIO.cleanup()

In the code, I do a sleep for 5 seconds to simulate the sprinker running for 5 secs. Then I simulate turning off one sprinkle and going to the next. I have a .1 second wait going from one sprinkler to the next.

However, if I remove the sleep(0.1) I don't get all the interrupts on the MCP23017 side and the program seems to hang.

In the MCP23017, I have INTA and INTB OR'ed together so I would only need one interrupt routine. I'll do tests to see if trying to handle two BANK's with one routine is causing the issue.

One test I did before was to wire two MCP23017 GP pins together to see what happens if two change state at exactly the same time. In that case, it seems to handle things properly. We get 1 interrupt with multiple bits set in INTFA,B and GPIOA,B representing the ping changes. In my simulation, they are not happening exactly at the same time and there are more than two of them. Perhaps the MCP23017 datasheet will give some clues to this behavior.

tlfong01 mentioned he had to reset his mcp23017 from time to time. Perhaps it is not noise but rather an inability to handle multiple interrupts.

Brandon92
Posts: 949
Joined: Wed Jul 25, 2018 9:29 pm
Location: The Netherlands

Re: GPIO.input voltage levels vs edge detection

Fri Sep 07, 2018 5:37 am

I think, if I remember correctly, that you can connect the INTA and INTB. And use only one of those pins. You can do it by turning on the right bit inside the chip itself.

And for you other questions I need to take a look at the datasheet. And I will come back to that.

If you need it reset the mcp from time to time it can be a sign that the power supply is possible not stable (decouple capacitor) and it that chip turns of. You need to send the the config settings again. Before you can use it as expected.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Fri Sep 07, 2018 5:44 am

petermeigs wrote:
Thu Sep 06, 2018 1:57 pm
1. put your circuit on a UPS and place it in a Faraday cage to shield it from the electronically noisy environment?
2. The point of the UPS would be to put a battery between your circuit and the power.

UPS and 18650 Lithium ion batteries

I forgot what is a Faraday cage. I am not sure if I heard it before. I need to google to refresh my memory. I vaguely remember I read about a "screen room" which is all covered by metal screen.

I once played with li-ion battery 16450. But my 16450s are cheapies and I never actually used them, because I worry they might explode. I heard that even Samsung smart phone batteries explode. So I don't have that much confidence in, well, cheap li-ion batteries.

Appendix - Lithium Ion Battery

Lithium-ion battery - Wikipedia
https://en.wikipedia.org/wiki/Lithium-ion_battery

Teardown of a faulty Samsung lithium 18650 cell. (2200mAh) - Big Clive with Egyptian Gin Tonic - 132,479 views
https://www.youtube.com/watch?v=gYFuVbZmu5M

Ali-express BC-4S15D 18650 Lithium Ion Battery Charger & Voltage Detector - US$19
https://www.aliexpress.com/item/BC4S15D ... 80161.html

Specifications:
Operating voltage range: DC 9V-16V
Operating temperature range: -20 ~ 45 Celsius degree
Support battery type: 2-4S li-ion or li-po battery
Input power requirement: ≥ 30W
The maximum charge power: 25W
Charging current: 1500mA
Charging accuracy: ±10mV
Balancing current: 1000mA
Display accuracy: ±10mV
This charger is for 2S/3S/4S li-ion or li-po battery. When you charge, you can only charge the same type of battery. It can be used as voltage detector, too.

Features:
1. Simple operation, one-step charging.
2. Voltage display, directly detects.
3. Ultra-high precision of charging, the error is within 10mV.
4. Multiple protection functions, to ensure the safety of user and battery.
5. Auto repair function for old battery.
6. All new design of balance architecture and algorithm, no need to discharge battery before charging.
Attachments
liion_18650x3_2018sep0701.jpg
liion_18650x3_2018sep0701.jpg (100.97 KiB) Viewed 4865 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Fri Sep 07, 2018 6:27 am

tlfong01 wrote:
Fri Sep 07, 2018 5:44 am
UPS and 18650 Lithium ion batteries

UPS and Panasonic Sealed Lead Acid (SLA) batteries

In those were my good old Arduino days (2008~2013) I played with lead batteries, but just for fun, and never used in any completed projects (well, almost all my Arduino and Rpi projects never completed! :) )

This lead battery is only 4AH, seems not efficient when comparing to the much smaller sized 16450 which is 3AH.

Appendix - Lead Battery

Panasonic Sealed Lead Acid Batteries Handbook 1998
https://media.digikey.com/pdf/Data%20Sh ... 8,99v2.pdf
Attachments
lead_battery_2018sep0701.jpg
lead_battery_2018sep0701.jpg (67.23 KiB) Viewed 4853 times
Last edited by tlfong01 on Sat Sep 08, 2018 12:15 am, edited 2 times in total.
I am an electronics and smart home hobbyist.

Brandon92
Posts: 949
Joined: Wed Jul 25, 2018 9:29 pm
Location: The Netherlands

Re: GPIO.input voltage levels vs edge detection

Fri Sep 07, 2018 6:51 am

The funniest thing is that in my case I want to use the Sealed Lead Acid battery. Because of that my project will be used outside and the temperutes goes in the winter below 0 degrees Celsius. And below the 0 degrees you cant charge the li-ion battery, link.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Fri Sep 07, 2018 7:10 am

petermeigs wrote:
Thu Sep 06, 2018 11:04 pm
1. I am doing some tests to see what happens if the mcp23017 gets changes too quickly.
2. Then I run the following code of the raspberry pi zero: ...
3. However, if I remove the sleep(0.1) I don't get all the interrupts on the MCP23017 side and the program seems to hang. ...
4. tlfong01 mentioned he had to reset his mcp23017 from time to time. Perhaps it is not noise but rather an inability to handle multiple interrupts.

MCP23xxx hanging up problem

I did not read your code because I always find it hard to read other people's code. But you do remind me that when I played with MCP23008/017/S08/S17, I noticed that mcp23xxx seemed to hang from time to time, with unknown reason.

That is why I later add a big manual reset button (the big blue buttons in the post below) on every board, to save time resetting Rpi every time when MCP23xxx hangs.

RE: RELAY MODULE KY-019 5V Post by tlfong01 » 2018-Sep-05 Wed 10:22 pm
https://www.raspberrypi.org/forums/view ... 5#p1361816

And the following 2014 discussion concludes that MCP23017 has some 'special features' not documented.

MCP23017 PROBLEM Postby JonasE » 2014-Nov-09 Sun 4:52 pm Viewed 3083 times
https://www.raspberrypi.org/forums/view ... 44&t=91209

I got a response from Microchip. They actually confirm there is a problem in the MCP23017. At least they have seen the problem before.

So, as a general advice, don't use GPA7 or GPB7 as inputs when using a MCP23017!

Best regards, Jonas 2014
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Fri Sep 07, 2018 11:49 am

petermeigs wrote:
Thu Sep 06, 2018 11:04 pm
I am doing some tests to see what happens if the mcp23017 gets changes too quickly.

In the code, I do a sleep for 5 seconds to simulate the sprinker running for 5 secs. Then I simulate turning off one sprinkle and going to the next. I have a .1 second wait going from one sprinkler to the next.

However, if I remove the sleep(0.1) I don't get all the interrupts on the MCP23017 side and the program seems to hang.

In the MCP23017, I have INTA and INTB OR'ed together so I would only need one interrupt routine. I'll do tests to see if trying to handle two BANK's with one routine is causing the issue.

One test I did before was to wire two MCP23017 GP pins together to see what happens if two change state at exactly the same time. In that case, it seems to handle things properly. We get 1 interrupt with multiple bits set in INTFA,B and GPIOA,B representing the ping changes. In my simulation, they are not happening exactly at the same time and there are more than two of them.

tlfong01 mentioned he had to reset his mcp23017 from time to time. Perhaps it is not noise but rather an inability to handle multiple interrupts.

Making use of the Interrupt Capture Register

I skimmed through your code quickly to get a very rough idea, but did not try to understand everything.

And just a suggestion.

You might like to make use of the Interrupt Capture Register. Actually this nice photographic memory thing is one of the the main reasons that, in the first place, I suggested you to try MCP23017.
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Sat Sep 08, 2018 3:37 am

Brandon92 wrote:
Fri Sep 07, 2018 6:51 am
The funniest thing is that in my case I want to use the Sealed Lead Acid battery. Because of that my project will be used outside and the temperutes goes in the winter below 0 degrees Celsius. And below the 0 degrees you cant charge the li-ion battery, link.


Battery University, sleeping Li-ion battery

Battery University is very good. I have never heard of it before. I only know Goggle University. I must attend more lectures there. :lol:

Learn what you can do to prevent a Li-ion battery to fall asleep. BU-808a: How to Awaken a Sleeping Li-ion
https://batteryuniversity.com/learn/art ... ge_cut_off

Do not boost lithium-based batteries back to life that have dwelled below 1.5V/cell for a week or longer.

Li-ion Rechargeable Battery Spec
https://www.powerstream.com/p/GMB043450S.pdf

Alibaba Lithium rechargeable battery 3.2V 16450 600mAh lifepo4 battery cells
https://www.alibaba.com/product-detail/ ... 55472.html
I am an electronics and smart home hobbyist.

petermeigs
Posts: 97
Joined: Thu Mar 23, 2017 1:34 pm
Location: Los Altos, California

Re: GPIO.input voltage levels vs edge detection

Sat Sep 08, 2018 6:11 am

tlfong01 wrote:
Fri Sep 07, 2018 7:10 am

I did not read your code because I always find it hard to read other people's code. But you do remind me that when I played with MCP23008/017/S08/S17, I noticed that mcp23xxx seemed to hang from time to time, with unknown reason.

MCP23017 PROBLEM Postby JonasE » 2014-Nov-09 Sun 4:52 pm Viewed 3083 times
https://www.raspberrypi.org/forums/view ... 44&t=91209

I got a response from Microchip. They actually confirm there is a problem in the MCP23017. At least they have seen the problem before.

So, as a general advice, don't use GPA7 or GPB7 as inputs when using a MCP23017!

Best regards, Jonas 2014
Thanks for this useful information. I have a test case I am working on. I have been ORing the A and B interrupts together on a single interrupt. I'm going to try to separate them to see if that helps. It's nice to know it might be the chip so I'll be on the lookout for that. I can already see that the chip seems to combine (OR) interrupt masks if they come in too fast.

Putting on my dull professor hat, with regard to reading other people's code, I'd like to suggest that this is an important skill. I find that I learn many new and interesting tips because someone has approached a problem in a way foreign to what I would have done. When that happens, there is often a new technique to be added to my bag of tricks. Sometimes, it's a nice way to express a common action that makes clear what the author intends. To butcher a quote: "We all stand taller if we stand on the shoulders of giants who have gone before us." (or something like that) Anyway, that's why I have enjoyed the discussion we have been having here.

Return to “Python”