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

Re: GPIO.input voltage levels vs edge detection

Tue Aug 28, 2018 1:05 am

figureA.PNG
figureA.PNG (13.27 KiB) Viewed 520 times
I have studied thee Application Note 1004 for the HCPL-3700 and worked out the math. I'll share my work here so folks won't have to go through the pain I did to understand it. (Maybe you already understand it but I hope this will help someone starting out with this device). First of all, I found a second version of the doc entitled "Threshold sensing for Industrial Control Systems with the HCPL-3700 Interface Optcoupler".
There is one copyright 1999 by Aglinet technologies and another by Avago date July 5, 2012. The later one is easier to read because it has two
wider columns of text insted of the 3 narrow columns that the older one has. However, the later one seems to have some errors when it was created from the first one. I found it easiest to read the second with the first one handy to help clarify some garbling that I noticed.

In the examples, the document uses V-th+, V-th-, V-ihc, I-th+ and I-th- values that differ from the typical ones given in the datasheet. They are within the Min to Max range so they are value but I think this unexplained difference is confusing. I think they would have been better off using
the Typical values and added a note that they might vary.

I'll do the calculation for resistors for the AC 24 vac case along with the power dissipated. I hope my example will be more clear. I will use
Electrical characteristics taken from the Feb 2106 Fairchild HCPL3700M Rev 1.1 datasheet and calculate the case for "Example 2. AC operation with no filtering" shown Application Note 1004

Using the Typical (Typ.) values from the HCPL3700 Data Sheet Rev 1.1 for AC on pins 1,4 with pins 2&3 Open we see:

V-th+ 5.00v
V-th- 3.70v
I-th+ 2.40mA
I-th- 1.20 mA
V-IHC2 7.0v, I-in 10mA

Let's assume the voltage we want to detect is 2/3 of 24vac or 16vac. This makes sure we detect it is on even if the solenoid we expect the circuit is driving cause a voltage drop.

See Figure A

For a resistor R1 in series with pins 1 and 4 of the device, we know that the voltage drop across the HCPL3700 is 5.00 V because that is V-th+.
Since the sum of the voltages around a cirucit must equal 0, we can say that the voltage across R1 is 16vac - 5vac or 11vac. We also know that the current is 2.40mA because that is the current for I-th+. Therefore the resistor R1 would be 11v / 2.4mA or 4.58k ohms. If we use 2 x 2.2k
ohm resistors then 2.4mA * 4.4k would be 10.56 + 5vac or 15.56vac. This is close enough and at any voltage between 15.56vac and 24vac we would detect ac on.

Now that we have picked value for the resistor, the voltage at which we stop detecting the circuit can be calculated. We know the current I-th-
to be 1.20mA. The resistor R1 has been chosen to be 4.4k ohms. When the voltage is at the lower threshold, the voltage drop across R1 is 1.20mA * 4.4k ohms or 5.28 vac. V-th- is 3.7v so summing the voltages around the circuit we get 5.28vac + 3.7vac or 8.98 vac.

In App note 1004 there is a discussion of filtering. I'll consider this later but I'm guessing a 10uF capacitor across pins 2 & 3 will do the
trick. I'll report more about that later.

I spent a bit of time staring at the document before I understood what they were talking about and where they got their equations. There were
some confusing typos here and there to make things worse.

I did the power dissipation calculations and we are well within limits.

So much for the theory. I'll test this and see what I get. At this point I wish I had a scope to see the output on Vo. I'm hoping it will be nice and square with no chatter at the end. We'll see----

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

Re: GPIO.input voltage levels vs edge detection

Tue Aug 28, 2018 1:12 am

petermeigs wrote:
Mon Aug 27, 2018 3:33 pm
tlfong01 is showing: What are these?:
They look like ammeter / voltmeter. Did you build these yourself or can I just buy one? Where can I get one? They look useful for instrumenting a circuit.

Poorman's High Class Adjustable Power Supply Unit


Ah, it is a really high class thing, 40 yuan each. :)

Adjustable Step Down Regulated Power Supply DC 3A LCD amp meter volt meter 40 yuan
https://detail.tmall.com/item.htm?id=55 ... 3ad4Bchypk

Reguated voltage or current 1.2~32V, 5A, 40 yuan
https://detail.tmall.com/item.htm?spm=a ... 0.23864_0

Regulated 60V, 7A, 50 yuan
https://detail.tmall.com/item.htm?spm=a ... 20.23864_0
I am an electronics, smart phone, and smart home hobbyist.

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

Re: GPIO.input voltage levels vs edge detection

Tue Aug 28, 2018 3:21 am

petermeigs wrote:
Tue Aug 28, 2018 1:05 am
1. Therefore the resistor R1 would be 11v / 2.4mA or 4.58k ohms. 15.56vac. close enough and at any voltage between 15.56vac and 24vac we would detect ac on.
2. filtering. I'll consider this later but I'm guessing a 10uF capacitor across pins 2 & 3 will do the trick.

HCPL3700 detecting AC24V

Oh my goodness. You talk like a boring professor. I skipped the whole lecture and just took a picture.
Attachments
nxY3Ryk[1].jpg
nxY3Ryk[1].jpg (47.53 KiB) Viewed 507 times
Last edited by tlfong01 on Tue Aug 28, 2018 11:50 am, edited 1 time in total.
I am an electronics, smart phone, and smart home hobbyist.

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

Re: GPIO.input voltage levels vs edge detection

Tue Aug 28, 2018 4:47 am

Well, somebody commented about the scary math. ;) And then after all the trouble of understanding it, I just knew the world would want to know as well. It turned out to be not so scary. I could make a you tube video of it? :lol: Probably not....

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

Re: GPIO.input voltage levels vs edge detection

Tue Aug 28, 2018 4:58 am

tlfong01 wrote:
Tue Aug 28, 2018 3:21 am
Oh my goodness. You speak like a boring professor. I skipped the whole lecture and just took a picture.

HCPL3700 detecting AC24V

I also took a picture of my AC24V waveform. I forgot why rms is related of square root of 2. Anyway my calculation looks OK.

My KY019 quad relay box have 4 inputs: AC220V, AC24V, AC12V, and DC12V.

I am using the third relay, with COM / NO = 24VAC. I am using my hand to connect 5V power line to relay input In. Next I will use 555 timer to input to the relay.
Attachments
MvR0KEq[1].jpg
MvR0KEq[1].jpg (139.44 KiB) Viewed 494 times
I am an electronics, smart phone, and smart home hobbyist.

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

Re: GPIO.input voltage levels vs edge detection

Tue Aug 28, 2018 5:10 am

petermeigs wrote:
Tue Aug 28, 2018 4:47 am
Well, somebody commented about the scary math. ;) And then after all the trouble of understanding it, I just knew the world would want to know as well. It turned out to be not so scary. I could make a you tube video of it? :lol: Probably not....
I will take a look at your calculation if I have time tonight. And the rest of your comments.
But why are you using a led as part of your pull up circuit. This is not what you want. If you want to see it, you can use it. But in combination with a real pull up resistor. This ensures the right high/ low voltage at that point. And it's fixed. And your Vf of your led is not "fixed". And it's nice for the Rpi to have a steady voltage at his input.

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

Re: GPIO.input voltage levels vs edge detection

Tue Aug 28, 2018 6:33 am

tlfong01 wrote:
Tue Aug 28, 2018 4:58 am
I also took a picture of my AC24V waveform.
My KY019 quad relay box have 4 COM inputs: AC220V, AC24V, AC12V, and DC12V.
I am using the third relay, with COM3 = 24VAC. I am using my hand to connect a 5V wire to trigger relay #3. Next I will use 555 timer to trigger to the relay.

HCPL3700 detecting AC24V

Now the 555 timer is chopping up the AC12V power 10 times a second.

Next, the chopped 12VAC is going to be hopefully detected by the HCPL3700.
Attachments
hatnyrk[1].jpg
hatnyrk[1].jpg (107.74 KiB) Viewed 474 times
I am an electronics, smart phone, and smart home hobbyist.

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

Re: GPIO.input voltage levels vs edge detection

Tue Aug 28, 2018 7:10 am

tlfong01 wrote:
Tue Aug 28, 2018 6:33 am
HCPL3700 detecting AC24V
Now the 555 timer is chopping up the AC12V power 10 times a second.
Next, the chopped 12VAC is going to be hopefully detected by the HCPL3700.

A3700 First Blood

So I connected the 555 chopped AC12V power to the little A3700, one end to AC (pin1), the other end also to AC (pin4).

Now pins 1, 4 were floating, and while I was wondering where should my scope probe ground go - chip ground (pin 5), or AC2 (pin4), then I smell something burning!

I knew something bad must be happening, I immediately pulled the plug, as fast as lighting, like a kung fu fighting guy, and used my kung fu finger to touch the component nearest me, the innocent 220R Rx (when smelling something bad I usually first touch the most expensive guy, but in this case the dear two yuan little guy A3700, is blocked by the cheap, 5 cent Rx). Anyway, I found Rx very hot, and one end seemed burnt (couldn't recognize the percentage colour ring!). :shock:

Carl Douglas - Kung Fu Fighting - 17,910,191 views
https://www.youtube.com/watch?v=jhUkGIsKvn0
Attachments
eU23qJO[1].jpg
eU23qJO[1].jpg (54.7 KiB) Viewed 463 times
Last edited by tlfong01 on Wed Aug 29, 2018 1:51 am, edited 4 times in total.
I am an electronics, smart phone, and smart home hobbyist.

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

Re: GPIO.input voltage levels vs edge detection

Tue Aug 28, 2018 7:24 am

Brandon92 wrote:
Mon Aug 27, 2018 3:17 pm
How did you measure the sine wave and the output of the device. I hope, in this case, that you didn't connect the ground pin of the scoop to the "ground" of the ac. And also connect the ground of the device to the ground of pin scoop. By the looks of the picture you did this. And you are probably one A3700 down ;)
:geek:

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

Re: GPIO.input voltage levels vs edge detection

Tue Aug 28, 2018 9:20 am

Brandon92 wrote:
Tue Aug 28, 2018 7:24 am
Brandon92 wrote:
Mon Aug 27, 2018 3:17 pm
1. How did you measure the sine wave and the output of the device.
2. And you are probably one A3700 down ;)
:geek:

What doesn't kill you makes you stronger

Well, I think the little guy is still alive, because my lighting fast kung fu saved its life. What doesn't kill it makes it stronger, and the show must go on!

But I still don't know how to use the scope to display the floating AC12V. I guess I need to try the input common mode, ie short AC2 (pin 4) to chip gnd (pin 5). Then I can connect scope ground to chip ground. But I don't know the CMRR (Common Mode Rejection Ratio) thing mentioned many times in the datasheet and app notes. I guess I need to wiki a bit.

Anyway, I followed the recommendation by prof, using Rx = 4k7, C filter = 10u, and just displayed the waveforms of 555 relay trigger signal, and A3700 Vo. The waves seem too good to be fake!

Supper time, see you later.

Kelly Clarkson - What Doesn't Kill You Makes You Stronger - 283,258,909 views
https://www.youtube.com/watch?v=Xn676-fLq7I
Attachments
HkDIGi2[1].jpg
HkDIGi2[1].jpg (90.39 KiB) Viewed 439 times
I am an electronics, smart phone, and smart home hobbyist.

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

Re: GPIO.input voltage levels vs edge detection

Tue Aug 28, 2018 2:48 pm

Brandon92 wrote:
Mon Aug 27, 2018 3:17 pm
1. How did you measure the sine wave and the output of the device.
2. I hope, in this case, that you didn't connect the ground pin of the scoop to the "ground" of the ac.
3. And also connect the ground of the device to the ground of pin scoop.

Oscilloscope Grounding Problem

1. To display A3700 output at Vo (pin 6), my scope probe ground wire is connected to A3700 power ground (pin 5). No problem at all.

2. Yes, I once tried to display mains 220VAC waveform using my scope, with scope ground wire connected to mains Earth, and probe to Live. And the RCBO tripped!

3. But for my 12VAC and 24VAC, I am using normal transformer with primary (200VAC)and secondary (12VAC or 24VAC) windings electrically insulated from each other. In other words, the secondary windings 12VAC or 24VAC are floating, not connected to mains L, N, or Earth. So it is safe to connect scope ground to either end of 12/24VAC power.

4. The problem is the following, using 24VAC as example. Now 24VAC is input to A3700 pins 1 and 4, as differential mode. If I don't connect pin 4 to A3700 power ground pin 5, then the scope with ground connected to pin 4 displays pin 1 voltage very large, over 60V! I guess the secondary coil is pickup line noise.

5. I am now thinking of connecting A3700 pin 4 to pin 5. I am not sure if this connection makes the 24VAC no longer differential, and therefore picks up line noise (or AC3700 ground noise). But I think the scope can then display pin1 to pin4 AC24V input.

Will let you know later the results.
I am an electronics, smart phone, and smart home hobbyist.

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

Re: GPIO.input voltage levels vs edge detection

Tue Aug 28, 2018 2:59 pm

tlfong01 wrote:
Tue Aug 28, 2018 7:10 am
A3700 First Blood
... and used my kung fu finger to touch the 220R Rx ...
I found Rx very hot, and one end seemed burnt (couldn't recognize the percentage colour ring!).

A3700 Rx burnt - Postmortem

Whenever I fry something, I almost always look back to see what goes wrong, and how to prevent the same mistake happening again.

Now I need to read the data sheet and application notes to check out why the Rx resistor is burnt. I googled and found 7 references about HCPL3700. I skimmed through all of them and found that only the datasheet and one of the many app notes, the App Note 1004 by Agilent Tech 1999, are useful.

/ to continue, ...

Appendix - HCPL3700 References

1. Threshold Sensing for Industrial Control Systems with the HCPL-3700 Interface Optocoupler Application Note 1004 - AgilentTech 1999 *****
http://www.slottechforum.com/slotinfo/T ... 20note.pdf

2. HCPL3700M AC/DC to Logic Interface Optocoupler Datasheet - Fairchild 2016Feb Rev 1.1
https://www.fairchildsemi.com/datasheet ... L3700M.pdf

3. Hewlett Packard-AN-1004 Threshold Sensing For Industrial Control Systems With The HCPL-3700 Interface Optocoupler OCR - Uploaded by Jeff Kaplan on January 28, 2014 * (book only)
https://archive.org/details/HewlettPack ... sManualOCR

4. Threshold Sensing for Industrial Control Systems with the HCPL-3700 Interface Optocoupler - Hewlett Packard, 1979
https://books.google.com.hk/books/about ... edir_esc=y * (achrive only)

5. HCPL-0370, HCPL-3700, HCPL-3760 Isolated Voltage/Current Detectors Data Sheet - Avago 2009 *
https://docs.broadcom.com/docs/AV02-2107EN

6. HCPL-0370, HCPL-3700, HCPL-3760 Isolated Voltage/Current Detectors Data Sheet - HP *
https://docs-emea.rs-online.com/webdocs ... 0287b5.pdf

7. HCPL-0370, HCPL-3700, HCPL-3760 AC/DC to Logic Interface Optocouplers - Avago 2007 **
https://datasheet.octopart.com/HCPL-370 ... 835929.pdf

8. Isolation Products in Motor Control Systems Reference Guide - Avago Tech 2006 ***
https://www.all-electronics.de/wp-conte ... ag0107.pdf
Last edited by tlfong01 on Wed Aug 29, 2018 1:56 am, edited 2 times in total.
I am an electronics, smart phone, and smart home hobbyist.

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

Re: GPIO.input voltage levels vs edge detection

Tue Aug 28, 2018 3:14 pm

When I'm home I will response to what you discrive above.

What is your exact test setup. Including the connections with your scope. Maybe there is something wrong with it. And you will not find that in the datasheet.

Also be very carefull how you connect/ measure things that are *indirect* connected through the means. You could kill the device under test or/and your scope!

And it has nothing to do with the dc or ac input of the A3700.

Edit
This YouTube movie is also a very good information about how not to blow up your scope.

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

Re: GPIO.input voltage levels vs edge detection

Tue Aug 28, 2018 4:14 pm

tlfong01 wrote:
Tue Aug 28, 2018 2:59 pm
Whenever I fry something, I almost always look back to see what goes wrong, and how to prevent the same mistake happening again.
....

6. HCPL-0370, HCPL-3700, HCPL-3760 Isolated Voltage/Current Detectors Data Sheet - HP *
https://docs-emea.rs-online.com/webdocs ... 0287b5.pdf
Two comments (even though I am probably telling folks something they already know :oops: )

1. Most of my resistors are 1/8 watt or .125w. I am a bit worried about frying things too so I spend a lot of time doing a power dissipation calculation for the resistor in question. You can easily measure the voltage drop (even AC) across the resistor and use (v^2 / r) to see if your resistor is chunky enough. Kung fu fighter speed may still be needed here to turn it off but you could start with a very chunky resistor and then go to a smaller one once you know

2. The doc #6 above seems to be the original Datasheet. It does NOT have the pesky typo's the Fairchild one had. I note that there are small differences in the Electrical Characteristics as well. Since we seem to have mystery A3700 chips, it probably doesn't matter much which data sheet we use and we need to stay well away from any values near minimums or maximums. Doc #6 is my new favorite

I very much appreciate your search results. The HP textbook in particular looks very useful. Thanks for sharing that.

quote=Brandon92 post_id=1358500 time=1535433023 user_id=273705]
But why are you using a led as part of your pull up circuit. This is not what you want. If you want to see it, you can use it. But in combination with a real pull up resistor. This ensures the right high/ low voltage at that point. And it's fixed. And your Vf of your led is not "fixed". And it's nice for the Rpi to have a steady voltage at his input.
[/quote]

I totally agree with you. I tried my rpi edge detection and ADC voltage check and got very messy output. The LED was just so I could check the VAC side and try different resistances before I did the calculations. It has served its purpose so it will be gone in my next step.

On the Vcc/Vo side, I have been setting Vcc to rpi 3.3vdc but I see that is probably not a good idea as Vcc at 4.5vdc yields Voh 2.4v. My ADC measures Vo at 1.47v I will try using Vcc from the rpi 5v pin. I like that better anyway because the 3.3 pins are more limited in total current. I'll add a 3.3v zener diode to protect my rpi's GPIO pin just in case. I haven't seen a discussion relating Vo to the pull up resistor or Vcc. However, I notice that Logic High output current Ioh has Voh = Vcc = 18v in the Electrical Specifications. It would be nice to be able to predict Voh to make sure it is never > 3.3v. Any thoughts here?

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

Re: GPIO.input voltage levels vs edge detection

Tue Aug 28, 2018 5:05 pm

petermeigs wrote:
Tue Aug 28, 2018 4:14 pm
On the Vcc/Vo side, I have been setting Vcc to rpi 3.3vdc but I see that is probably not a good idea as Vcc at 4.5vdc yields Voh 2.4v. My ADC measures Vo at 1.47v I will try using Vcc from the rpi 5v pin. I like that better anyway because the 3.3 pins are more limited in total current. I'll add a 3.3v zener diode to protect my rpi's GPIO pin just in case. I haven't seen a discussion relating Vo to the pull up resistor or Vcc. However, I notice that Logic High output current Ioh has Voh = Vcc = 18v in the Electrical Specifications. It would be nice to be able to predict Voh to make sure it is never > 3.3v. Any thoughts here?
The Rpi side of that chip can work on the 3.3V power rail. But you need to ad a real pull up resistor to it, so without a led in serie! If you want a led you could at it parallel to the real pull up resistor with a serie resistor. And I would start with a 1.5K resistor as pull up. (As stated in the datasheet 6)

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

Re: GPIO.input voltage levels vs edge detection

Tue Aug 28, 2018 7:43 pm

@petermeigs
As far as I can see you calculation are good.
The capacitor that they are adding is for that the ac is converted by a full bridge rectifier (youtube) into DC. As explained in that movie. When you connect a capacitor to the dc terminal. The voltage will not drop to zero. So, the detectors stays on.
However, I saw also that you could do a simulator solution toe the output of the ic. And I think this is the way to go. Because if you want to connect it at the “life” side the correct capacitor is much more expansive. And need to be a certain type. And the is not required by the Cl (output filter capacitor). And you need to calculate the Cl in combination with the Rl (pull up).

@tlfong01
tlfong01 wrote:
Tue Aug 28, 2018 2:48 pm
Brandon92 wrote:
Mon Aug 27, 2018 3:17 pm
1. How did you measure the sine wave and the output of the device.
2. I hope, in this case, that you didn't connect the ground pin of the scoop to the "ground" of the ac.
3. And also connect the ground of the device to the ground of pin scoop.

Oscilloscope Grounding Problem

1. To display A3700 output at Vo (pin 6), my scope probe ground wire is connected to A3700 power ground (pin 5). No problem at all.

2. Yes, I once tried to display mains 220VAC waveform using my scope, with scope ground wire connected to mains Earth, and probe to Live. And the RCBO tripped!

3. But for my 12VAC and 24VAC, I am using normal transformer with primary (200VAC)and secondary (12VAC or 24VAC) windings electrically insulated from each other. In other words, the secondary windings 12VAC or 24VAC are floating, not connected to mains L, N, or Earth. So it is safe to connect scope ground to either end of 12/24VAC power.

4. The problem is the following, using 24VAC as example. Now 24VAC is input to A3700 pins 1 and 4, as differential mode. If I don't connect pin 4 to A3700 power ground pin 5, then the scope with ground connected to pin 4 displays pin 1 voltage very large, over 60V! I guess the secondary coil is pickup line noise.

5. I am now thinking of connecting A3700 pin 4 to pin 5. I am not sure if this connection makes the 24VAC no longer differential, and therefore picks up line noise (or AC3700 ground noise). But I think the scope can then display pin1 to pin4 AC24V input.

Will let you know later the results.
Well to get straight to the point. It is not easy to measure this correctly. Because you are working with several potentials. And there are all mains reference.
  1. That is correct. You only use one powersupply
  2. That is not your smartest idea. You could easily killed you scope and possible yourself.
  3. Well this is a difficult measurement. Take a look at this A Differential Probe Guide youtube movie.
    But, there might be an easy way to trigger you scope with the mains. See the picture below. If you set this setting your scope will trigger at the AC line. And because you are using a transformer. They are practical the same. And you could play with this is this gives a desirable result. I think I know a couple options extra. But for that I need to know you setup diagram.
  4. Like I said beforece You dont want to do this. This will potential damage the chip. And you don't notice a different.
.
Well, I think that I answered all the question?
Attachments
triggerAcoption.png
triggerAcoption.png (62.03 KiB) Viewed 383 times

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

Re: GPIO.input voltage levels vs edge detection

Tue Aug 28, 2018 8:40 pm

I used a 1.8k resistor for the pull up and got rid of the LED as suggested. (I didn't have a 1.5k resistor). Also, I used the

I have run my rpi pigpio code that turns on 24vac using a relay for 3 seconds then turns it off. Meanwhile, I frequently measure the Voltage Vo using the ADC just to get an idea of how much it varies (.02 ms wait after each measurement). At that time, I query the Pin to see if it is on or off I also, detect an pigpio edge interrupt when the level changes. The states are 0 for relay off (no 24vac), 1 for relay on (24vac on), 2 for relay off after 3 sec). The state is bumped up by .2 when an edge interrupt happens so I correlate the times everything happens.
A3700Running3secs.PNG
A3700Running3secs.PNG (74.82 KiB) Viewed 375 times
I am very pleased with these results and they are exactly what I am looking for except for the negative logic. The fall and rise of the edge is very crisp. And I get exactly 1 edge detect when the 24vac circuit goes on and one when the 24vac circuit goes off. There are only about ~18 ms from when I turn off the relay and when the rpi gets the edge interrupt. Since I will be measuring water flows over a period of ~10-45 minutes, this delay is negligible for my water flow measurement. Some of it is due to the relay delay anyway and my application won't be controlling the relay anyway. It just needs to know the time from water valve on to water valve off and which valve of 16 we are talking about. There is an 24vac solenoid for the water value in parallel with my circuit. I'm not sure how much to worry about that. I'm hoping the A3700 will provide transient protection against that.

Because of the negative logic, when I am handling 16 lines, I am a little worried about the 3.3 v current draw. In my final circuit, I may want to use the MCP23017 and put my circuit on its own power supply.

I think my next step will be to include the MCP23017 in my circuit and see what that does. I'll also draw up my circuit (including my rpi setup) up to this point so others can see exactly what worked for me.

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

Re: GPIO.input voltage levels vs edge detection

Tue Aug 28, 2018 9:02 pm

Brandon92 wrote:
Tue Aug 28, 2018 7:43 pm
@petermeigs
As far as I can see you calculation are good.
The capacitor that they are adding is for that the ac is converted by a full bridge rectifier (youtube) into DC. As explained in that movie. When you connect a capacitor to the dc terminal. The voltage will not drop to zero. So, the detectors stays on.
However, I saw also that you could do a simulator solution toe the output of the ic. And I think this is the way to go. Because if you want to connect it at the “life” side the correct capacitor is much more expansive. And need to be a certain type. And the is not required by the Cl (output filter capacitor). And you need to calculate the Cl in combination with the Rl (pull up).
I liked the video. I think it's good tip on what to avoid doing.

With regard to putting the filter on the output side of the A3700, I was worried about putting the filter there because of the slow decay at the end. I had a lot of trouble with that when I was using the full bridge rectifier because the tail-off slope was so shallow, I got a lot of chatter on the rpi edge detect. As you can see in my graph, there are no intermediate values: Vo is high for a while, then low until the input on pins 1,4 changes and then high again. I can get the 10uF for under 0.20USD each including shipping in packs of 20 so their cost is not a worry.

Looking at the application note for recalculating Rx due to adding 10uF, I estimated that it would not make much difference. I'll recheck my calculations.

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

Re: GPIO.input voltage levels vs edge detection

Wed Aug 29, 2018 6:56 am

tlfong01 wrote:
Tue Aug 28, 2018 9:20 am
Anyway, I followed the recommendation by prof, using Rx = 4k7, C filter = 10u, and just displayed the waveforms of 555 relay trigger signal, and A3700 Vo. The waves seem too good to be fake!

Dual HCPL3700 setup and testing notes

Now I am trying to setup two A3700 for testing. My aim is to detect high threshold and low threshold voltages witch a small gap. I think I need two A3700 working together, one detecting high, the other low threshold. I need the high low threshold gap small, for heater control: heater on when detecting low threshold, and heater off when detecting high threshold. I am not using AC power for A3700 to detect. I am using two ADC, perhaps two differential channels of MCP3208.

But just for testing A3700 performance, I am still using AC12V and AC24V.

I found typing A3700 or HCPL3700 a bit tedious, so I am thinking of
using a short hand, perhaps PLI for Power to Logic Interface. (The official Fairchild name for HCPL3700M is AC/DC to Logic Interface Optocoupler, or ADLIO).

The left picture below shows both relays always on. The right showing both relays controlled by the 555 timer. In other words, the 12, 24 VAC power are chopped.

Next is to connect the two powers to two PLIs to be detected.
Attachments
uBae2F9[1].jpg
uBae2F9[1].jpg (132 KiB) Viewed 351 times
I am an electronics, smart phone, and smart home hobbyist.

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

Re: GPIO.input voltage levels vs edge detection

Wed Aug 29, 2018 12:28 pm

petermeigs wrote:
Tue Aug 28, 2018 4:47 am
Well, somebody commented about the scary math. ;) And then after all the trouble of understanding it, I just knew the world would want to know as well. It turned out to be not so scary. I could make a you tube video of it? :lol: Probably not....

Prerequisite YouTube Videos for Understanding HCPL3700

Well, I think to understand A3700 datasheet and app notes, one needs to have the prerequisite knowledge, including the following:


1. Bridge rectifier

2. Zener diode

3. Hysteresis

4. Schmitt trigger

If a student does not have the above knowledge, he is in hopelessly big trouble and will find the professor's lecture very boring. I would suggest the miserable student to watch the following videos before attending the lecture.

Appendix - Prerequisite Youtubes for understanding HCPL3700

1. What is Hysteresis? Beginners Bash series
https://www.youtube.com/watch?v=k7ZalV3KzZQ

2. What Is Schmitt Trigger and How It Works
https://www.youtube.com/watch?v=Nrp8OgQLAlw

3. Schmitt Trigger Oscillator, Schmitt Inverter 74AC14
https://www.youtube.com/watch?v=NuXitMK3HSA
I am an electronics, smart phone, and smart home hobbyist.

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

Re: GPIO.input voltage levels vs edge detection

Wed Aug 29, 2018 1:31 pm

tlfong01 wrote:
Tue Aug 28, 2018 2:48 pm
Brandon92 wrote:
Mon Aug 27, 2018 3:17 pm
1. How did you measure the sine wave and the output of the device.
Oscilloscope Grounding Problem
1. To display A3700 output at Vo (pin 6), my scope probe ground wire is connected to A3700 power ground (pin 5). No problem at all.
4. The problem is the following, using 24VAC as example. Now 24VAC is input to A3700 pins 1 and 4, as differential mode. If I don't connect pin 4 to A3700 power ground pin 5, then the scope with ground connected to pin 4 displays pin 1 voltage very large, over 60V! I guess the secondary coil is pickup line noise.
5. I am now thinking of connecting A3700 pin 4 to pin 5. I am not sure if this connection makes the 24VAC no longer differential, and therefore picks up line noise (or AC3700 ground noise). But I think the scope can then display pin1 to pin4 AC24V input.
Will let you know later the results.

Result of connecting Pin4 (AC2) to Pin 5 (Power Gnd)

If I short pins 4, 5 together, then I can connect scope probe ground to pin 4 (AC2) and display pin 1 (AC1 input).
Attachments
uTlXWmN[1].jpg
uTlXWmN[1].jpg (136.74 KiB) Viewed 326 times
I am an electronics, smart phone, and smart home hobbyist.

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

Re: GPIO.input voltage levels vs edge detection

Wed Aug 29, 2018 1:48 pm

tlfong01 wrote:
Wed Aug 29, 2018 1:31 pm
Result of connecting Pin4 (AC2) to Pin 5 (Power Gnd)
If I short pins 4, 5 together, then I can connect scope probe ground to pin 4 (AC2) and display pin 1 (AC1 input).

Winner Winner Chicken Dinner! :mrgreen:

After doing input filtering as advised by the boring prof, the ugly teething square wave is now sharp and clean! :D
Attachments
LIsHsKF[1].jpg
LIsHsKF[1].jpg (64.7 KiB) Viewed 324 times
I am an electronics, smart phone, and smart home hobbyist.

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

Re: GPIO.input voltage levels vs edge detection

Thu Aug 30, 2018 4:26 am

tlfong01 wrote:
Wed Aug 29, 2018 12:28 pm
Prerequisite YouTube Videos for Understanding HCPL3700
Well, I think to understand A3700 datasheet and app notes, one needs to have the prerequisite knowledge, including the following: Bridge rectifier, Zener diode, Hysteresis, Schmitt trigger, Optocoupler, Pull down resistor, ...
Appendix - Prerequisite Youtubes for understanding HCPL3700
1. What is Hysteresis? Beginners Bash series
https://www.youtube.com/watch?v=k7ZalV3KzZQ
2. What Is Schmitt Trigger and How It Works
https://www.youtube.com/watch?v=Nrp8OgQLAlw
3. Schmitt Trigger Oscillator, Schmitt Inverter 74AC14
https://www.youtube.com/watch?v=NuXitMK3HSA
tlfong01 wrote:
Mon Aug 06, 2018 8:34 am
You might find my following 2 old posts useful for general reference.
(Schmitt Trigger HC14 1/2) RE: RELAY KY-019 5V tlfong01 2018-Jun-23
https://www.raspberrypi.org/forums/view ... 5#p1331903
(Schmitt Trigger HC14 2/2) RE: RELAY KY-019 tlfong01 2018-Jun-23
https://www.raspberrypi.org/forums/view ... 0#p1332019

Comparing Two Schmitt Triggers - A3700 and HC14

/ to continue, ...
Attachments
8MWi8nl[1].jpg
8MWi8nl[1].jpg (79.96 KiB) Viewed 268 times
Last edited by tlfong01 on Thu Aug 30, 2018 9:06 am, edited 1 time in total.
I am an electronics, smart phone, and smart home hobbyist.

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

Re: GPIO.input voltage levels vs edge detection

Thu Aug 30, 2018 6:59 am

The videos explaining various components are helpful and entertaining. Here is the last circuit I tested with. It gives a nicely shaped output on GPIO-25. The MCP3008 is so I can measure voltage in the python code as I don't have a scope.


Important! I made an error in this schematic. I left off two important resistors: One 10k between MCP30008 pin 1 Ch 0 and Vo of A3007 and another 4.7k between rpi GPIO 25 and Vo of A3007. Without them there will be too much current in these connections. I have deleted the schematic I had placed here earlier and added it to a later post.


The code I run is here:

Code: Select all

#!/usr/bin/env python2.7
import pigpio
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)

pi = None
spi = None
state = 0
lastrise = None
lastdrop = None
starttime = 0

AO_pin = 0 #flame sensor AO connected to ADC chanannel 0
# change these as desired - they're the pins connected from the
# SPI port on the ADC to the Cobbler

SPIBAUD= 100000
SPISCLK = 11
SPICS = 8
SPIMISO = 9
SPIMODE = 0
SPIMOSI = 10

RELAY = 23
OPTO1 = 25

linerf = []

def adcvolts(ad_value):
    voltage = (ad_value * 3.3) / 1023
    return voltage

#fuction to check when the "trommelfilter" is active. And check how long it is on
# def TF_active(gpio, level, tick):
#     if level == 0:
#         #load the global variables
#         global timestamp
#         global datestamp
#         global timer_TF_active
#         #Get the current date and time
#         timestamp = strftime("%H:%M:%S")
#         datestamp = strftime("%d-%m-%Y")
#         #Get the time when the "trommelfilter" is active
#         timer_TF_active = time()
#         #For debug purposes
#         print("Preset at:",timer_TF_active)
#         logger.info("Active")
#     else:
#         #load the global variables
#         global timer_TF_inactive
#         global TF_was_active
#         #Get the time when the "trommelfilter" is inactive
#         timer_TF_inactive = time()
#         #Mark a flag for the main program
#         TF_was_active = 1
#         #For debug purposes
#         print("Release at:", timer_TF_inactive)
#         logger.info("Deactivate")
#         #change the pin interrupt to a falling edge \_
#     return
#
# #Start the detection wiht a falling edge
# cb1 = gpio.callback(TrommelFilter_io, pigpio.EITHER_EDGE, TF_active)



def TF_active(gpio, level, tick):
    global linerf
    global starttime
    global lastrise
    global lastdrop
    global state
    global AO_pin

    global SPIBAUD
    global SPISCLK
    global SPICS
    global SPIMISO
    global SPIMODE
    global SPIMOSI

    global pi
    # time.sleep(0.0001)
    # print gpio, level, tick
    nowtim = datetime.utcnow()
    # gpiolevel = pi.read(gpio)
    # ad_value = readadc(SPICS, AO_pin)
    # voltage = ad_value*(3.3 / 1024) # *5 no voltage divider here
    ad_value = readadc(SPICS, AO_pin)
    measuretime = datetime.utcnow() - nowtim
    timediff = None

    nowtim = datetime.utcnow()
    if level:     # if port 25 == 1
        # if lastrise:
        #     timediff = nowtim - lastrise
        # lastrise = nowtim
        # if (timediff and
        #     timediff.days == 0 and
        #     timediff.seconds == 0 and
        #     timediff.microseconds < 1000):
        #     return
        linerf.append([ nowtim, ad_value, state + .2, level, measuretime ])
        # lastdrop = None
    else:                  # if port 25 != 1
        # if lastdrop:
        #     timediff = nowtim - lastdrop
        # lastdrop = nowtim
        # if (timediff and
        #     timediff.days == 0 and
        #     timediff.seconds == 0 and
        #     timediff.microseconds < 1000):
        #     return
        linerf.append([ nowtim, ad_value, state + .2, level, measuretime])
        # lastrise = None
    return

#port init
def init():
    global pi

    global SPIBAUD
    global SPICS
    global SPIMISO
    global SPIMODE
    global SPIMOSI
    global SPISCLK

    pigpio.exceptions = True
    pi = pigpio.pi()
    if not pi.connected:
        print "Could not connect to pigpio. Did you run sudo pigpiod?"
        exit(0)
    # set up the SPI interface pins
    #pi.set_mode(SPIMOSI, pigpio.OUTPUT)
    #pi.set_mode(SPIMISO, pigpio.INPUT)
    #pi.set_mode(SPISCLK, pigpio.OUTPUT)
    # pi.set_mode(SPICS, pigpio.OUTPUT)

    pi.set_mode(OPTO1, pigpio.INPUT)    # set GPIO25 as input (button)
    pi.set_mode(RELAY, pigpio.OUTPUT)    # set GPIO24 as output
    pi.write(RELAY, False)
    print ("bb spi close")
    try:
        pi.bb_spi_close(SPICS)
    except:
        print("bb_spi_close error", sys.exc_info()[0])
        pass
    try:
        print (SPICS, SPIMISO, SPIMOSI, SPISCLK, SPIBAUD, SPIMODE)
        print("open bb_spi_open")
        pi.bb_spi_open(SPICS, SPIMISO, SPIMOSI, SPISCLK, SPIBAUD, SPIMODE)
    except:
        print("bb_spi_open error:", sys.exc_info()[0])
        raise
        pass
    # 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
    # GPIO.add_event_detect(OPTO1, GPIO.BOTH, callback=my_callback)
    pi.callback(OPTO1, pigpio.EITHER_EDGE, TF_active)

    pass

#read SPI data from MCP3008(or MCP3204) chip,8 possible adc's (0 thru 7)
def readadc(cspin, adcnum):
    global pi
    ct, data = pi.bb_spi_xfer(cspin, [1, (8 + adcnum) << 4, 0])
    val  = ((data[1]<<8) | data[2]) & 0x3FF
    # print (ct, val, "data=", [byte for byte in data] )
    return val

def oldreadadc(adcnum, clockpin, mosipin, misopin, cspin):
    if ((adcnum > 7) or (adcnum < 0)):
        return -1
    pi.write(cspin, True)

    pi.write(clockpin, False)  # start clock low
    pi.write(cspin, False)     # bring CS low

    commandout = adcnum
    commandout |= 0x18  # start bit + single-ended bit
    commandout <<= 3    # we only need to send 5 bits here
    for i in range(5):
        if (commandout & 0x80):
            pi.write(mosipin, True)
        else:
            pi.write(mosipin, False)
        commandout <<= 1
        pi.write(clockpin, True)
        pi.write(clockpin, False)

    adcout = 0
    # read in one empty bit, one null bit and 10 ADC bits
    for i in range(12):
        pi.write(clockpin, True)
        pi.write(clockpin, False)
        adcout <<= 1
        if (pi.read(misopin)):
            adcout |= 0x1

    pi.write(cspin, True)

    adcout >>= 1       # first bit is 'null' so drop it
    return adcout

def sortbytimekey(x):
    global starttime
    mstime = x[0] - starttime
    key = mstime.seconds + mstime.microseconds / 1000000.0
    return key

def main():
    init()
    global linerf
    global starttime
    global pi
    time.sleep(2)
    voltimelist = []
    sleeptime = 0.00002  # .02 ms
    global state # 0 = not started, 1 = on, 2 = off, 3= zero reached
    avgvolt = 0
    avgvoltcnt = 0
    maxvolt = 0
    minvolt = 99999
    voltage = 0   # initial voltage value
    endvolts = 1 # 0.0001 * 1023 / 3.3
    print ("will detect voltage. ")
    ad_value = readadc(SPICS, AO_pin)
    starttime = datetime.utcnow()
    measuretime =  datetime.utcnow() - starttime
    voltimelist.append([datetime.utcnow(), ad_value, state, pi.read(OPTO1), measuretime])
    pi.write(RELAY, True)
    state = 1
    print("ON, state = " + str(state))

    while state < 3:
        elapsedtime = datetime.utcnow() - starttime
        if elapsedtime.seconds > 2 and state != 2:
            pi.write(RELAY, False)
            state = 2
            print("OFF, state = " + str(state))
        if elapsedtime.seconds > 5:
            print("TIMEOUT, state = " + str(state))
        time.sleep(sleeptime)
        readtime = datetime.utcnow()
        ad_value = readadc(SPICS, AO_pin)
        if elapsedtime.seconds > 5:
            voltage = adcvolts(ad_value)
            print("TIMEOUT, state = " + str(state) + ", voltage=" + str("%.4f"%voltage))
            break
        thistime = datetime.utcnow()
        measuretime = thistime - readtime
        if state == 2 and ad_value <= endvolts:
            voltage = adcvolts(ad_value)
            print ("almost zero detected = " + str("%.4f"%voltage) + ", at time " + thistime.strftime("%H:%M:%S.%f"))
            state = 3
        voltimelist.append([thistime, ad_value, state, pi.read(OPTO1), measuretime])
        # print thistime, ad_value, state, pi.read(OPTO1), measuretime
        # if voltage > 0.5:
        #     avgvolt = ((avgvoltcnt * avgvolt) + voltage) / (avgvoltcnt + 1)
        #     avgvoltcnt += 1
        #     if voltage > maxvolt:
        #         maxvolt = voltage
        #     if voltage < minvolt:
        #         minvolt = voltage
        pass

    # print ("Time's up. Finished! Average volts=" + str("%.4f"%avgvolt) +
    #       ", Max volts = " + str("%.4f"%maxvolt) +
    #       ", Min volts = " + str("%.4f"%minvolt) +
    #       " , Count = " + str(avgvoltcnt) + ", state = " + str(state))
    print ("Time's up. Finished! state = " + str(state))

    print "voltimelist len =", len(voltimelist)
    file = open("voltpigpio.csv", "w")
    voltimelist = voltimelist + linerf
    starttime = voltimelist[0][0]
    voltimelist.sort(key = sortbytimekey)
    file.write( "Time" +
                ", State" +
                ", Volts" +
                ", PinVal" +
                ", ADCval" +
                ", MeasureTime" +
                ", ActualTime" +
                "\n"
              )
    for voltim, ad_value, state, pin, measuretime in voltimelist:
        mstime = voltim - starttime
        voltstr = ""
        if ad_value >= 0:
            voltstr = str("%.4f"%adcvolts(ad_value))
        file.write( "%d"%mstime.seconds + ".%06d"%mstime.microseconds +
                    "," + str(state) +
                    "," + voltstr +
                    "," + str(pin) +
                    "," + str(ad_value) +
                    ",%d"%measuretime.seconds + ".%06d"%measuretime.microseconds +
                    "," + voltim.strftime("%H:%M:%S.%f") +
                    "\n"
                  )
    file.close()


if __name__ =='__main__':
    try:
        main()
    except KeyboardInterrupt:
        pass
    except:
        print("Unexpected error:", sys.exc_info()[0])
        pass
    pi.write(RELAY, False)
    # pi.bb_spi_close(SPICS)
    pi.stop()
This code closes the relay (with builtin flyback diode) for 3 seconds and then opens it. Meanwhile, there is a voltage measurement after a .02ms wait. When the voltage is measured, the gpio-25 value is read. All output is accumulated in a csv array which can be uploaded to excel and graphed.

I am now working on putting my A3007 behind a MCP23017 so that I can simplify the connections to the rpi, isolating it a bit. I think it will make the code to handle it all when I finally put 16 x a3007 in front of it.

I'd like the MCP23017 to be interrupt driven as I am not a big fan of polling. I'm looking at the wiringpi http://wiringpi.com/library at the moment for a python interface but am open to suggestions if someone suggests a better library.
Last edited by petermeigs on Thu Aug 30, 2018 3:59 pm, edited 3 times in total.

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

Re: GPIO.input voltage levels vs edge detection

Thu Aug 30, 2018 7:12 am

I did not read it all, because of time.
But what is the working voltage of C2.

Return to “Python”

Who is online

Users browsing this forum: No registered users and 10 guests