Searching \ for '[PIC] measuring 220V mains' in subject line. ()
Make payments with PayPal - it's fast, free and secure! Help us get a faster server
FAQ page: www.piclist.com/techref/microchip/devices.htm?key=pic
Search entire site for: 'measuring 220V mains'.

Exact match. Not showing close matches.
PICList Thread
'[PIC] measuring 220V mains'
2010\03\08@051806 by Dario Greggio

face picon face
I am to use a 24FJxxGA106 to (along other things) measure 220V mains
voltage with some coarse accuracy, say 1-2%

I have a small 220->6V transformer, whose inputs goes via a partitor
(still have to decide, but let's assume it 4K7 - 2K2) to AN2 of the PIC.
So, more or less 2Vrms or 3Vpp circa when mains is nominal 220V.

I'm planning on sampling/reading the input voltage some ... 100? times /
second, and perform a ... FFT or something simpler upon it.

Can you suggest the simplest way to achieve that result?

TIA


--

Ciao, Dario
--
Cyberdyne

2010\03\08@053916 by Tony Vandiver

flavicon
face
I've done something similar, (but with a little less accuracy) by
rectifying the output of the transformer and just doing a straight
average of the ADC then translating back with a fixed multiplier.  Works
o.k. as long as there's no other load on the transformer.  You'll get
better results if you calibrate this (it's difficult to depend on the
repeatability of the turns ratio of the transformer for a 1% accuracy).

hth,

Tony



Dario Greggio wrote:
{Quote hidden}

2010\03\08@062404 by Mohit (Lists)

picon face
1. Can you do a 'peak-detector' in software? Continuously
read the ADC, keep comparing all the readings and the
maximum value would be what you are after.

2. If you know the frequency (F), then detect zero-crossing
 and begin to take a set of ADC readings a few tens of
milliseconds before (zero-cross + 1/4F seconds) and carry on
till a few seconds after (zero-cross + 1/4F seconds).
Compare these readings and get the maximum value. This would
be less heavy on the processing resources than 1 above as
you will be reading the ADCs lesser times per cycle, but
will need hardware for zero-detection (an extra PIC pin).

HTH,
Mohit Mahajan.
http://www.BioZen.co.in

Dario Greggio wrote:
{Quote hidden}

2010\03\08@063005 by Russell McMahon

face picon face
> I am to use a 24FJxxGA106 to (along other things) measure 220V mains
> voltage with some coarse accuracy, say 1-2%

What is the intended application.
What you are proposing is vast overkill for some applications and
maybe not good enough for others.

A transformer may somewhat modify the waveform. If you have heavy loads
present which modify the voltage from open circuit to on-load then
waveform shape may change depending on whether the load is resistive or
reactive or some mix (or changing).  Other factors such as energy return from
rotating machines or electronic supplies MAY make a difference. But
may not, or may not matter.

If you have a reasonable sine wave you could consider peak measuring a
lightly loaded secondary and scaling (by 0.7071 in ideal case).

If you use an FFT you'll want to measure integral half cycles if you
want to avoid windowing complexities.

You could consider a precision ("ideal") rectifier and DC measurement
or just peak measurement with ADC or even measurements at fixed points
along cycle from zero to zero to confirm the sine shape with minimal
calculation.

Or ...

So, knowing intended use may help provide a cheap or low complexity answer.



      Russell

2010\03\08@065350 by Wouter van Ooijen

face picon face
> Can you suggest the simplest way to achieve that result?

For the hardware I would prefer a mains-powered PIC that does the A/D
and transmits the (possibly processed) result to the main PIC by
optocoupler. Eliminates the transformer (bulky, uncalibrated, might
change the waveform) in exchange for an extra PIC, optocoupler and a
C-based power supply.

--

Wouter van Ooijen

-- -------------------------------------------
Van Ooijen Technische Informatica: http://www.voti.nl
consultancy, development, PICmicro products
docent Hogeschool van Utrecht: http://www.voti.nl/hvu

2010\03\08@092827 by Dario Greggio

face picon face
Tony Vandiver ha scritto:
> I've done something similar, (but with a little less accuracy) by
> rectifying the output of the transformer and just doing a straight
> average of the ADC then translating back with a fixed multiplier.  Works
> o.k. as long as there's no other load on the transformer.  You'll get
> better results if you calibrate this (it's difficult to depend on the
> repeatability of the turns ratio of the transformer for a 1% accuracy).

I see Tony, I actually wanted to avoid most of external components.
I basically have the transformer and a R partitor.
Calibration is something I'll have to perform anyway, unfortunately...

thanks

2010\03\08@093059 by Dario Greggio

face picon face
Mohit (Lists) ha scritto:
> 1. Can you do a 'peak-detector' in software? Continuously
> read the ADC, keep comparing all the readings and the
> maximum value would be what you are after.

This is one of the methods I considered


{Quote hidden}

I DO have zero-cross detection since I'll also be driving a
dimmering-triac, so definitely I'm going to make use of it.

thank you!

2010\03\08@093434 by Dario Greggio

face picon face
Russell McMahon ha scritto:
>> I am to use a 24FJxxGA106 to (along other things) measure 220V mains
>> voltage with some coarse accuracy, say 1-2%
>
> What is the intended application.
> What you are proposing is vast overkill for some applications and
> maybe not good enough for others.


Hi Russell, this is a air-pump, pressure monitoring, temperature.
Basically I need to be sure that VAC is not lower than 200V (say) or
higher than 240 before activating the pumps, the valves, or else.
So precision is not *that* important, but still somehow.


> A transformer may somewhat modify the waveform. If you have heavy loads
> present which modify the voltage from open circuit to on-load then
> waveform shape may change depending on whether the load is resistive or
> reactive or some mix (or changing).  Other factors such as energy return from
> rotating machines or electronic supplies MAY make a difference. But
> may not, or may not matter.

This transformer is very small one, dedicated to this purpose.
I hope that returning energy won't disturb... or not even make their way
through :) (except for fast peaks / transients maybe)




> If you have a reasonable sine wave you could consider peak measuring a
> lightly loaded secondary and scaling (by 0.7071 in ideal case).

so this is more or less ok (as I was suggested above)


> If you use an FFT you'll want to measure integral half cycles if you
> want to avoid windowing complexities.

yeah, maybe safer, though more costly in terms of cycles.
But let's consider that the "timeframe" of the device is 10 seconds or
so, so definitelt a looong time.


> You could consider a precision ("ideal") rectifier and DC measurement
> or just peak measurement with ADC or even measurements at fixed points
> along cycle from zero to zero to confirm the sine shape with minimal
> calculation.


Yeah, I want to avoid more components.


> Or ...
>
> So, knowing intended use may help provide a cheap or low complexity answer.

thanks :)

--

Ciao, Dario
--
Cyberdyne

2010\03\08@093622 by Dario Greggio

face picon face
Wouter van Ooijen ha scritto:
>> Can you suggest the simplest way to achieve that result?
>
> For the hardware I would prefer a mains-powered PIC that does the A/D
> and transmits the (possibly processed) result to the main PIC by
> optocoupler. Eliminates the transformer (bulky, uncalibrated, might
> change the waveform) in exchange for an extra PIC, optocoupler and a
> C-based power supply.



Yeah, a good one for another project :)

In this case the whole board is already made up with power, PIC, other
"things" etc.
I stated the most of its characteristics in my other replies.

thank you Wouter anyway :)

2010\03\08@100614 by peter green

flavicon
face

> I'm planning on sampling/reading the input voltage some ... 100? times /
> second, and perform a ... FFT or something simpler upon it.
>
> Can you suggest the simplest way to achieve that result?
A FFT is overkill unless you actually want to measure the harmonics.

Trying to detect the peak value and scale that is IMO a bad idea because
a single brief spike could throw the reading way off.

Taking the average of the magnitude and scaling it would probablly be a
reasonable option. True RMS is also pretty easy to calculate (square the
individual values, average them and take the square root at the end)

Ideally for stable values you should detect the zero crossings and do
your averaging (whether true RMS or average of the magnitude) over a
whole number of half-cycles.

Also 100Hz is about the worst choice of sampling rate you could pick.
Combine that with a 50Hz waveform and you may miss all the peaks! If you
want  good results from simple algorithms within a single cycle i'd
suggest at least 1KHz. If you are averaging over many cycles and can't
afford to sample quickly make sure you select a sample rate that is NOT
a multiple or subdivision of the supply frequency!

2010\03\08@100628 by Russell McMahon

face picon face
> Hi Russell, this is a air-pump, pressure monitoring, temperature.
> Basically I need to be sure that VAC is not lower than 200V (say) or
> higher than 240 before activating the pumps, the valves, or else.
> So precision is not *that* important, but still somehow.

OK. Nice simple application.
Finding the peak voltage over N cycles and averaging it would very
likely be good enough. Loading the transformer lightly to damp effects
of noise, capacitive coupling etc may be a good idea. Use of standard
values, probably calculated and then checked in practice, would
probably be good enough. A diode, resistor and capacitor would allow a
single reading, but in this case code sounds preferable to even a few
components.

As described the voltage sounds to be bipolar wrt to ground. If so,
you need to be sure your ADC input will handle that (I won't go and
look up the datasheet). If not, then a discussion of simple extra
circuitry may be about to happen:-).



            Russell

2010\03\08@101801 by Dario Greggio

face picon face
Russell McMahon ha scritto:
> Finding the peak voltage over N cycles and averaging it would very
> likely be good enough. Loading the transformer lightly to damp effects

ok


> of noise, capacitive coupling etc may be a good idea. Use of standard
> values, probably calculated and then checked in practice, would

yeah, small load i.e. partitor in place, whose value still to be
determined but in the range of Kohms


> probably be good enough. A diode, resistor and capacitor would allow a
> single reading, but in this case code sounds preferable to even a few
> components.

yes



> As described the voltage sounds to be bipolar wrt to ground. If so,
> you need to be sure your ADC input will handle that (I won't go and
> look up the datasheet). If not, then a discussion of simple extra
> circuitry may be about to happen:-).


I *hope* that a 24FJ will handle it and the few negative mA. Will check
soon :)

thanks again

--

Ciao, Dario
--
Cyberdyne

2010\03\08@101954 by Dario Greggio

face picon face
peter green ha scritto:
> A FFT is overkill unless you actually want to measure the harmonics.

indeed, I guess that's true


> Trying to detect the peak value and scale that is IMO a bad idea because
> a single brief spike could throw the reading way off.

that's true, even if I could perform some averaging here and there.


> Taking the average of the magnitude and scaling it would probablly be a
> reasonable option. True RMS is also pretty easy to calculate (square the
> individual values, average them and take the square root at the end)

ok


> Ideally for stable values you should detect the zero crossings and do
> your averaging (whether true RMS or average of the magnitude) over a
> whole number of half-cycles.

yeah, point taken, will try to use it.


> Also 100Hz is about the worst choice of sampling rate you could pick.
> Combine that with a 50Hz waveform and you may miss all the peaks! If you
> want  good results from simple algorithms within a single cycle i'd
> suggest at least 1KHz. If you are averaging over many cycles and can't
> afford to sample quickly make sure you select a sample rate that is NOT
> a multiple or subdivision of the supply frequency!


yeah :) I definitely wrote 100Hz but of course had my mind set elsewhere :)
I agree in that.
The device has actually "plenty of time" to perform even a lot of
reading, since (as I wrote in my other reply) the response time is in
the order of seconds.

thank you Peter

2010\03\08@104057 by Alan B Pearce

face picon face
> I am to use a 24FJxxGA106 to (along other things) measure 220V mains
> voltage with some coarse accuracy, say 1-2%

Is there a specific reason to use this chip?

My reason for asking is that Microchip have some application notes on using
members of the dsPic family in a UPS, and you may be able to leverage code
from that for your purpose.

2010\03\08@105259 by Dario Greggio

face picon face
Alan B Pearce ha scritto:
>> I am to use a 24FJxxGA106 to (along other things) measure 220V mains
>> voltage with some coarse accuracy, say 1-2%
>
> Is there a specific reason to use this chip?
>
> My reason for asking is that Microchip have some application notes on using
> members of the dsPic family in a UPS, and you may be able to leverage code
> from that for your purpose.


Yes :)
because the whole board does a number of things, among which Ethernet
and/or USB (with the GB version).

But I'm going to use C, so basically other code can be easily adapted (I
guess).

thank you!

--

Ciao, Dario
--
Cyberdyne

2010\03\08@114458 by Michael Rigby-Jones

flavicon
face


> -----Original Message-----
> From: spam_OUTpiclist-bouncesTakeThisOuTspammit.edu [.....piclist-bouncesKILLspamspam@spam@mit.edu] On
Behalf
> Of Dario Greggio
> Sent: 08 March 2010 10:18
> To: Microcontroller discussion list - Public.
> Subject: [PIC] measuring 220V mains
>
> I am to use a 24FJxxGA106 to (along other things) measure 220V mains
> voltage with some coarse accuracy, say 1-2%
>
> I have a small 220->6V transformer, whose inputs goes via a partitor
> (still have to decide, but let's assume it 4K7 - 2K2) to AN2 of the
PIC.
> So, more or less 2Vrms or 3Vpp circa when mains is nominal 220V.

Sorry if this is being obvious, but you will either need to rectify the
output of the transformer or apply a suitable voltage offset in order to
prevent any negative voltages on the PIC pin.

Mike

=======================================================================
This e-mail is intended for the person it is addressed to only. The
information contained in it may be confidential and/or protected by
law. If you are not the intended recipient of this message, you must
not make any use of this information, or copy or show it to any
person. Please contact us immediately to tell us that you have
received this e-mail, and return the original to us. Any use,
forwarding, printing or copying of this message is strictly prohibited.
No part of this message can be considered a request for goods or
services.
=======================================================================

2010\03\08@143719 by Russell McMahon

face picon face
> I *hope* that a 24FJ will handle it and the few negative mA. Will check
> soon :)

No.
Not with certainty.

The negative voltage spec is in the "absolute ratings" section of all
data sheets. Body/protection diode conduction is only meant as
protection and proper IC operation is not guaranteed.

For guaranteed operation pin voltages must be within specified range
between power rails. Many ICs may run with inputs outside the spec
sometimes maybe. YMMV and will sometimes. That way lies intermittent
operation and problems forever.

You can almost get away with (read "essentially statistically
certainly") currents in the low microamp range. Often anyway :-). But
mA and even hundreds of uA and maybe 10's of uA MAY cause problems.
Current goes to nodes where it was never designed to and interesting
stuff happens.

Those who tell you that you can inject say 1 mA odd into a body diode
on an operating processor with impunity have not yet fully learned
their engineering art and/or how to properly read data sheets.


        Russell

2010\03\08@143727 by Carl Denk

flavicon
face
That's what I do on my standby generator's PLC, but should work on a
PIC. A wallwart with 12 VAC out, rectifier bridge, and resistor voltage
divider with a pot for for calibration adjustment. All I need is voltage
within a few volts accuracy, to verify the generator is actually putting
out current, or the power line is down.

Michael Rigby-Jones wrote:
>  
>> {Original Message removed}

2010\03\09@070920 by Dario Greggio

face picon face
Russell McMahon ha scritto:
>> I *hope* that a 24FJ will handle it and the few negative mA. Will check
>> soon :)
>
>[...] For guaranteed operation pin voltages must be within specified range
> between power rails. Many ICs may run with inputs outside the spec
> sometimes maybe. YMMV and will sometimes. That way lies intermittent
> operation and problems forever.


Table says
AD10 VINH-VINL Full-Scale Input Span VREFL  VREFH V (Note 2)
AD11 VIN Absolute Input Voltage AVSS  0.3  AVDD + 0.3 V
AD12 VINL Absolute VINL Input
Voltage
AVSS  0.3 AVDD/2 V
AD17 RIN Recommended Impedance
of Analog Voltage Source
  2.5K . 10-bit

ok basically :) AGND -0.3

well, will see. not a big issue to place a shottky diode externally. The
current will be no more than 8V (pp) / 5K (or 10K) (in order tom eet
impedance requirements) so 500-1.5mA.


thanks again !

--

Ciao, Dario
--
Cyberdyne

2010\03\09@071012 by Dario Greggio

face picon face
Michael Rigby-Jones ha scritto:
>
> Sorry if this is being obvious, but you will either need to rectify the
> output of the transformer or apply a suitable voltage offset in order to
> prevent any negative voltages on the PIC pin.

point taken :) and answered in other mails, Mike.
thank you

--

Ciao, Dario
--
Cyberdyne

2010\03\09@071046 by Dario Greggio

face picon face
Carl Denk ha scritto:
> That's what I do on my standby generator's PLC, but should work on a
> PIC. A wallwart with 12 VAC out, rectifier bridge, and resistor voltage
> divider with a pot for for calibration adjustment. All I need is voltage
> within a few volts accuracy, to verify the generator is actually putting
> out current, or the power line is down.


Yeah, as I said, I wanted to avoid those external parts.
thank you

--

Ciao, Dario
--
Cyberdyne

2010\03\09@072722 by ivp

face picon face
> ok basically :) AGND -0.3
>
> well, will see. not a big issue to place a shottky diode externally

You should. For example noise on the mains could come through the
transformer and exceed -0.3V. Bye-bye pin, possibly bye-bye PIC.
Been there

wbr, Joe

2010\03\09@073831 by Dario Greggio

face picon face
ivp ha scritto:
> You should. For example noise on the mains could come through the
> transformer and exceed -0.3V. Bye-bye pin, possibly bye-bye PIC.
> Been there


even with that small amount of current, Joe?

Been using dimmers with a 1Mohm straight to a 16F pin for zero-crossing
 - nothing else. makes some 400uA... working for years.

Are they that different?
I can't see "how much current" those "diodes" (or whatever) can shunt...

thx

--

Ciao, Dario
--
Cyberdyne

2010\03\09@080339 by Carl Denk

flavicon
face
Understand, I was just the opposite, wanting to keep dangerous (120 VAC)
away from untrained humans.:) There still is 2 ways to walk around the
town square, one with the sun in the eyes and the other with the wind at
you. :) I do have several extra wall warts and PCB's available as spares.

Dario Greggio wrote:
{Quote hidden}

2010\03\09@080403 by Michael Rigby-Jones

flavicon
face


> -----Original Message-----
> From: piclist-bouncesspamKILLspammit.edu [.....piclist-bouncesKILLspamspam.....mit.edu] On
Behalf
{Quote hidden}

zero-crossing
>   - nothing else. makes some 400uA... working for years.
>
> Are they that different?
> I can't see "how much current" those "diodes" (or whatever) can
shunt...
>

The issue is not how much current the protection diodes can safely
shunt, but the affect that sinking current into them will have on the
operation of the PIC.  This particular issue has been covered several
times before on the list, and several people have discovered that
allowing the protection diodes to conduct can affect the operation of
other pins, especially analog ones.  

Note that the Microchip specification for the -0.3v pin voltage is an
"absolute maximum" which simply means the device will not be damaged.
As explained in the datasheet, it does not mean the device the will
actually work as expected under those conditions.

Regards

Mike

=======================================================================
This e-mail is intended for the person it is addressed to only. The
information contained in it may be confidential and/or protected by
law. If you are not the intended recipient of this message, you must
not make any use of this information, or copy or show it to any
person. Please contact us immediately to tell us that you have
received this e-mail, and return the original to us. Any use,
forwarding, printing or copying of this message is strictly prohibited.
No part of this message can be considered a request for goods or
services.
=======================================================================

2010\03\09@082631 by ivp

face picon face
> even with that small amount of current, Joe?

The internal diodes vs external Schottkys has been discussed in
depth before but I honestly can't remember the figures. Personally
I just don't like the risk. Another problem I've encountered once
was noise caused by machinery that got through to Vss. I didn't
investigate but perhaps Vss rose relative to the inputs. Schottkys
did prevent any more PICs burning out

> Been using dimmers with a 1Mohm straight to a 16F pin for zero-
> crossing - nothing else. makes some 400uA... working for years

The waveform is centred about Vss ? The internal pull-ups have
around 400uA pulling power, maybe yours is a safe current like
that

2010\03\09@122357 by Dwayne Reid

flavicon
face
At 03:17 AM 3/8/2010, Dario Greggio wrote:
>I am to use a 24FJxxGA106 to (along other things) measure 220V mains
>voltage with some coarse accuracy, say 1-2%
>
>I have a small 220->6V transformer, whose inputs goes via a partitor
>(still have to decide, but let's assume it 4K7 - 2K2) to AN2 of the PIC.
>So, more or less 2Vrms or 3Vpp circa when mains is nominal 220V.
>
>I'm planning on sampling/reading the input voltage some ... 100? times /
>second, and perform a ... FFT or something simpler upon it.

I'm currently doing something similar with a 12f675 running directly
from a 120Vac power-line input.

In my case, I threw extra parts at the problem to make the software
easier and to allow the PIC pin to work as both an input and an
output.  The 120Vac input is sampled with a 100K resistor, then to 2-
1n4148 diodes: one to clamp the negative half-cycle, the other feeds
into a 1u0 63V capacitor.  The capacitor also feeds into a 100K / 10K
voltage divider which then feeds the PIC input.  Note that the first
1n4148 diode wouldn't be needed if I used diodes with a higher PIV
rating but 1n4148 is a standard part for us - easier to add the extra
diode.  All three resistors are 1%.  Total of 6 extremely inexpensive parts.

The software samples the input every 1.024ms and feeds a 16 times IIR
filter.  The output of that filter is then fed into a peak detector
with a period of 20ms (20 ticks of 1.024ms each).

This allows me to accurately measure the 120Vac line voltage and make
decisions on whether to allow system operation or not.

You could scale this for 220Vac input just by changing the input
resistor.  I'd be tempted to use 2 resistors in series for better
protection against transient spikes, though.

Hope this helps!

dwayne

--
Dwayne Reid   <EraseMEdwaynerspam_OUTspamTakeThisOuTplanet.eon.net>
Trinity Electronics Systems Ltd    Edmonton, AB, CANADA
(780) 489-3199 voice          (780) 487-6397 fax
http://www.trinity-electronics.com
Custom Electronics Design and Manufacturing

2010\03\09@131112 by Dario Greggio

face picon face
Dwayne Reid ha scritto:
> In my case, I threw extra parts at the problem to make the software
> easier and to allow the PIC pin to work as both an input and an
> output.  The 120Vac input is sampled with a 100K resistor, then
> [...]

> The software samples the input every 1.024ms and feeds a 16 times IIR
> filter.  The output of that filter is then fed into a peak detector
> with a period of 20ms (20 ticks of 1.024ms each).
>
> This allows me to accurately measure the 120Vac line voltage and make
> decisions on whether to allow system operation or not.


this is perfectly good :)
I will consider the shunting diodes, and I do have transformer so
isolation should not be an issue.

Do you have a quick link for the IIR filter? I know it has been
published and commented tons of times but...

thanks

--

Ciao, Dario
--
Cyberdyne

2010\03\09@160934 by Dwayne Reid

flavicon
face
This routine runs in my background task which executes every 1.024ms.

"rampg1" & "rampg0" are macros that set the appropriate page
bits.  Those are a single instruction for the 12f675 but
would  expand to two instructions for PICs with 4 RAM pages.

A/D is configured for 10 bit result (right-justified).  The a/d start
command occurs when the background task is about to finish and is not
shown here.

;AD routines: 1 ch with 16 sample IIR filter.  Choose 16 samples 'cuz
; 16 * 1.024ms ~ 16.667ms (period of 60Hz signal).
; Would need to go to more than 20 samples for 50Hz signal (use 32 samples).

;divide sum by 16   AD1:AD1L /16 -> BGTMP2:BGTMP1
    swapf       AD1L,W          ;LO byte
    andlw       b'00001111'
    movwf       BGTMP1          ;hi nib AD1L -> lo nib BGTMP (>>4)
    swapf       AD1,W           ;HI byte
    movwf       BGTMP2          ;swap nibs AD1 -> BGTMP2     (>>4)
    andlw       b'11110000'     ;clr lo nib in W
    xorwf       BGTMP2,F        ;clr hi nib BGTMP2 (XOR value with
itself is 0)
    iorwf       BGTMP1,F        ;lo nib AD1 -> hi nib BGTMP1 (>>4)

;subtract old sample from sum
    movfw       BGTMP1          ;LS byte
    subwf       AD1L,F          ;F-W ->d

    movfw       BGTMP2
    skpc
      incfsz    BGTMP2,W
        subwf   AD1,F

;add new sample to sum
    rampg1
    movfw       RB1(ADRESL)
    rampg0
    addwf       AD1L,F

    movfw       ADRESH
    skpnc
      incfsz    ADRESH,W
        addwf   AD1,F
;done.  Do all line voltage tests on sum (AD1,AD1L)



At 11:11 AM 3/9/2010, Dario Greggio wrote:
{Quote hidden}

--
Dwayne Reid   <dwaynerspamspam_OUTplanet.eon.net>
Trinity Electronics Systems Ltd    Edmonton, AB, CANADA
(780) 489-3199 voice          (780) 487-6397 fax
http://www.trinity-electronics.com
Custom Electronics Design and Manufacturing

2010\03\09@172054 by Russell McMahon

face picon face
> > You should. For example noise on the mains could come through the
> > transformer and exceed -0.3V. Bye-bye pin, possibly bye-bye PIC.
> > Been there

> even with that small amount of current, Joe?

> Been using dimmers with a 1Mohm straight to a 16F pin for zero-crossing
>  - nothing else. makes some 400uA... working for years.

> Are they that different?
> I can't see "how much current" those "diodes" (or whatever) can shunt...

Alas, all deices are potentially different. As someone else noted,
it's what happens to the current that matters. The protection diodes
will or may inject it into the substrate at points that were not
designed with operational current flow in mind. this may eg operate a
parasitic transistor that never normally functions or cause current
flow to some node that is "not expecting it" or ... . The problem is
that nobody know for sure. The IC designers COULD deign things so that
the system is moderately robust against such usage, but there's no
certainty that they have, and ongoing occasional indications that
sometimes they haven't done so well enough for a given application. I
got caught doing this with an RS232 input long ago, using a circuit
suggested by a kit supplier. The result was so intermittent and so
variable in effect that I'd decided to make it one of my life missions
ever since to warn people about it :-). It's clear from all data
sheets that it shouldn't be done during normal operation, and it's
quite likely that you MAY get away with doing it in many applications.
Sticking to 'data sheet says ..." us usually a good idea.

Note that even using a Schottky clamp MAY violate the spec by a small
amount. All experience I have had and heard of suggests that in fact a
Schottky clamp works OK. again YMMV but so far nobody's has :-) ).

One last 'trick' - in ultra low power circuits, a clamp diode to
supply can "pump up" the power supply voltage if the input circuit can
provide more current than the processor draws. That would be unusual
but worth being aware of. (One Microchip ap note appeared to do just
that - and also violated the body-diode conduction 'rule' above.
Several people argued vigorously that if uC did it in an ap note it
must be OK. I suspect the uC datasheet writers would have disagreed
:-)).



  Russell

2010\03\09@172806 by Dario Greggio

face picon face
Russell McMahon ha scritto:

> Alas, all deices are potentially different. As someone else noted,
> it's what happens to the current that matters. The protection diodes
> will or may inject it into the substrate at points that were not
> [...]

I know, I know Russell... :)

Stick with the Datasheet is best, of course. I'm going to check this as
part of the debugging prototype part...

thanks

--

Ciao, Dario
--
Cyberdyne

2010\03\09@175222 by Xiaofan Chen

face picon face
On Wed, Mar 10, 2010 at 1:23 AM, Dwayne Reid <@spam@dwaynerKILLspamspamplanet.eon.net> wrote:

> I'm currently doing something similar with a 12f675 running directly
> from a 120Vac power-line input.
>
Just wondering how you power up the 12F675? Since it is pure AC,
there are different ways to do that.

In my past job, I developed two universal power supply sensors,
one level sensor and one photoelectric sensor. Both run
from 20...250 VAC and 12...60V DC (actually 12...250V DC).
I have to use a full bridge rectifier and DC/DC converters
made of transistors. The two design are different, but
both use buck converter. The current requirement is not high
though (a PIC running slow and a relay).

--
Xiaofan http://mcuee.blogspot.com

2010\03\09@180912 by ivp

face picon face
> Stick with the Datasheet is best, of course. I'm going to check this
> as part of the debugging prototype part...

Dario, I'll tell you how bad it can be. The project that really opened
my eyes was an 877-based cine-camera stepper. It's basically a timer
for time-lapse photography. There are relays to supply current to the
shutter and film advance solenoids

The first indication of a problem was that the LCD display would go
loopy when one particular relay operated. I found that the wiring and
position of the relay was disturbing the PIC when it de-energised, so
the circuit was re-configured to stop that. In doing so however it now
affected the ADC pin used for a switch + resistors to set the interval
multiplier. This now became unreliable and unpredictable. After only
a few operations the PIC suddenly started sucking the life out of the
battery and a pinhole was blown through the PIC. I believe the
mechanism is that a comparatively hefty SCR is formed

I've also had this happen with a 6522 CIA, which actually cracked
the chip in half. You'd think the die would just fail quietly, after all
it's
just a logic device, but occassionally enough heat is generated to do
actual physical damage

2010\03\09@183423 by Dwayne Reid

flavicon
face
At 03:52 PM 3/9/2010, Xiaofan Chen wrote:
>On Wed, Mar 10, 2010 at 1:23 AM, Dwayne Reid <KILLspamdwaynerKILLspamspamplanet.eon.net> wrote:
>
> > I'm currently doing something similar with a 12f675 running directly
> > from a 120Vac power-line input.
> >
>Just wondering how you power up the 12F675? Since it is pure AC,
>there are different ways to do that.
>
>In my past job, I developed two universal power supply sensors,
>one level sensor and one photoelectric sensor. Both run
>from 20...250 VAC and 12...60V DC (actually 12...250V DC).
>I have to use a full bridge rectifier and DC/DC converters
>made of transistors. The two design are different, but
>both use buck converter. The current requirement is not high
>though (a PIC running slow and a relay).

This version uses a standard capacitive-type power supply.  However,
the circuit topology is quite different in that the relay portion of
the circuit has one power supply and the rest of the electronics has
a separate supply.  The two supplies are in series - I have lots of
voltage available but limited current.  Operating range for this
particular product is 90 through 150Vac but there is no reason that
the power supply wouldn't do 90 through 240Vac.

It works rather well and I hope to publish the details in EDN or
Electronic Design sometime soon.

dwayne

--
Dwayne Reid   <RemoveMEdwaynerTakeThisOuTspamplanet.eon.net>
Trinity Electronics Systems Ltd    Edmonton, AB, CANADA
(780) 489-3199 voice          (780) 487-6397 fax
http://www.trinity-electronics.com
Custom Electronics Design and Manufacturing

2010\03\09@190026 by Xiaofan Chen

face picon face
On Wed, Mar 10, 2010 at 7:34 AM, Dwayne Reid <spamBeGonedwaynerspamBeGonespamplanet.eon.net> wrote:
> This version uses a standard capacitive-type power supply.  However,
> the circuit topology is quite different in that the relay portion of
> the circuit has one power supply and the rest of the electronics has
> a separate supply.  The two supplies are in series - I have lots of
> voltage available but limited current.  Operating range for this
> particular product is 90 through 150Vac but there is no reason that
> the power supply wouldn't do 90 through 240Vac.
>
> It works rather well and I hope to publish the details in EDN or
> Electronic Design sometime soon.
>

I see. If it is pure 50/60Hz AC, another poorman's DC/DC
converter can be used. Supertex used to make two ICs,
SR036 and SR037 which use the same mechanism to
use the AC crossing as the base of switching regulator.
http://www.futurel.bg/datasheets/4/SR03.pdf
You can make your own based on discrete components
as well.

The efficiency is not that high but much better than
the linear one. Supertex makes a high voltage
linear regulator LR8 for SMPS startup.
http://www.supertex.com/pdf/datasheets/LR8.pdf


--
Xiaofan http://mcuee.blogspot.com

2010\03\09@190237 by Xiaofan Chen

face picon face
On Tue, Mar 9, 2010 at 3:37 AM, Carl Denk <TakeThisOuTcdenkEraseMEspamspam_OUTwindstream.net> wrote:
> That's what I do on my standby generator's PLC, but should work on a
> PIC. A wallwart with 12 VAC out, rectifier bridge, and resistor voltage
> divider with a pot for for calibration adjustment. All I need is voltage
> within a few volts accuracy, to verify the generator is actually putting
> out current, or the power line is down.

Yes I will go this route if I were Dario. A rectifier does not cost much
and it is the proper way to go.


--
Xiaofan http://mcuee.blogspot.com

2010\03\09@211510 by Russell McMahon

face picon face
How does a transformer and 2 resistors sound?

If you wanted a relatively minimalist implementation you could connect
one side of the secondary to a resistive divider across Vdd-Gnd and
the other to a resistive divider to ground with the PIC A2C tapped off
that.


As long as Vpp < Vdd the output is always positive.

In the limiting version of this you connect one side of transformer to
Vdd and the output to a divider to ground and tap ADC input off the
divider. ADC input is always positive.

             Total requirement = transformer + 2 resistors.

Here Vpp must be less than 2 x Vdd and output divider ratio K such
that (Vdd + Vpp/2) x k < Vdd

The smallish downside is that the available measured voltage may be
slightly less than in some other systems - BUT you lose the non
linearity / offset introduced if diodes are used, notionally* need no
clamp diodes etc.

* Here mains noise can appear at reduced V on PIC pin scaled by
transformer ratio. Protecting against this may or may not be a good
idea [tm] but is not a terrible one unless minimum parts count is
absolutely crucial. Clamp Schottkys to each rail may be OK. Small cap
on PIC pin may be all that is needed, noting phase delay and peak V
reduction caused (both of which can be small).


             Russell

2010\03\10@115039 by Dwayne Reid

flavicon
face
At 05:00 PM 3/9/2010, Xiaofan Chen wrote:

>I see. If it is pure 50/60Hz AC, another poorman's DC/DC
>converter can be used. Supertex used to make two ICs,
>SR036 and SR037 which use the same mechanism to
>use the AC crossing as the base of switching regulator.
>http://www.futurel.bg/datasheets/4/SR03.pdf
>You can make your own based on discrete components
>as well.

That's interesting - I've been using a very similar circuit in other
products since 1999 or so.  Mine is done with discrete components and
the performance is not as good as the Supertex version since I have
only half-wave AC available instead of full-wave.

I wasn't aware of the Supertex version but I had seen the ST version
in the early 2000's.  I didn't bother going with any of the
integrated versions that I saw - the cost for my version was just too
low (less than $1 in hundreds).

But the capacitive supply I'm using in this particular product was
chosen for other reasons.

dwayne

--
Dwayne Reid   <RemoveMEdwaynerspamTakeThisOuTplanet.eon.net>
Trinity Electronics Systems Ltd    Edmonton, AB, CANADA
(780) 489-3199 voice          (780) 487-6397 fax
http://www.trinity-electronics.com
Custom Electronics Design and Manufacturing

2010\03\10@195550 by Dario Greggio

face picon face
Russell McMahon ha scritto:
> How does a transformer and 2 resistors sound?

Well, this is also good!
(in parts, more or less what I have now). I actually did not think of
much about alternatives since I was almost sure of the clamping diodes...

I will consider one of these 2 approaches and some tests.

thx!

--

Ciao, Dario
--
Cyberdyne

2010\03\18@081814 by Dario Greggio

face picon face
Dwayne Reid ha scritto:
> This routine runs in my background task which executes every 1.024ms.

Hello Dwayne, sorry for not replying earlier :)
I've been making up the board - almost fine now - and hence moved to the
measurer.

I took your code and made it into C:

       if(!BusyADC10()) {                // non deve succedere
               ADC_220_sample=ReadADC10(0);
               }

       ConvertADC10();

       ADC_220_old_sample=ADC_220_sum/(1000/50);                // freq. sampl
       ADC_220_sum-=ADC_220_old_sample;
       ADC_220_sum+=ADC_220_sample;
//                ADC_220_old_sample=ADC_220_sample;
       if(!(cnt % 50)) {
               ADC_220=ADC_220_sum;         //
               ADC_220_sum=0;
               }



It's called every 1mS and every 20 I take the result.

It's not working so far, but will see :)

thank you!
--

Ciao, Dario
--
Cyberdyne

2010\03\18@154915 by Vitaliy

face
flavicon
face
Dario Greggio wrote:
> I took your code and made it into C:
>
> if(!BusyADC10()) { // non deve succedere
> ADC_220_sample=ReadADC10(0);
> }
>
> ConvertADC10();
>
> ADC_220_old_sample=ADC_220_sum/(1000/50); // freq. sampl
> ADC_220_sum-=ADC_220_old_sample;
> ADC_220_sum+=ADC_220_sample;
> // ADC_220_old_sample=ADC_220_sample;
> if(!(cnt % 50)) {
> ADC_220=ADC_220_sum; //
> ADC_220_sum=0;
> }
>

Dario, just an OT observation: you can improve readability (now and
especially in the future) if you use more meaningful function and variable
names and replace magic numbers with variables or #defines. Also, proper use
of whitespace can make a huge difference.

Best regards,

Vitaliy

2010\03\18@174143 by Dario Greggio

face picon face
Vitaliy ha scritto:
> Dario, just an OT observation: you can improve readability (now and
> especially in the future) if you use more meaningful function and variable
> names and replace magic numbers with variables or #defines. Also, proper use
> of whitespace can make a huge difference.


Yeah, thank you Vitaliy :)

I often, usually, do. In this case, 50Hz is almost fixed "forever" so I
was not needing it. As for variable names, I considered that the names
above were good enough :)


--

Ciao, Dario
--
Cyberdyne

2010\03\19@095111 by Dario Greggio

face picon face
Hmmm, I may be missing something but.. I can't get any result out of the
IIR filtering, nor the raw samples, nor their average...

Well, I simulated 20 samples (one full sine wave) on an Excel
spreadsheet, and tried shifting the sine with respect to the sampling
point, and the result does change a lot - not good.

Can you suggest where I'm going wrong?
thx!

--

Ciao, Dario
--
Cyberdyne

2010\03\19@112754 by Olin Lathrop

face picon face
Dario Greggio wrote:
> Hmmm, I may be missing something but.. I can't get any result out of
> the IIR filtering, nor the raw samples, nor their average...
>
> Well, I simulated 20 samples (one full sine wave) on an Excel
> spreadsheet, and tried shifting the sine with respect to the sampling
> point, and the result does change a lot - not good.
>
> Can you suggest where I'm going wrong?

It's not clear what exactly you're doing.  You have 20 samples of a sine
wave, but what are you trying to get from those and what are you getting?

If this signal contains harmonics, did you remember to apply a anti-aliasing
filter to get rid of the ones your sample stream can't represent?


********************************************************************
Embed Inc, Littleton Massachusetts, http://www.embedinc.com/products
(978) 742-9014.  Gold level PIC consultants since 2000.

2010\03\19@113838 by Dario Greggio

face picon face
Olin Lathrop ha scritto:
> It's not clear what exactly you're doing.  You have 20 samples of a sine
> wave, but what are you trying to get from those and what are you getting?



Hello Olin, I started this thread some 3 weeks ago, and got some several
good replies. Now I have the PCB and am testing it.

Basically I need to measure 220V mains, by mean of a 220->6 tiny
transformer and a partitor and a protection diode, staight into a PIC's ADC.

I'm sampling the sine every 1mS and was wondering of a FFT or average or
else... I need some 5% accuracy.



--

Ciao, Dario
--
Cyberdyne

2010\03\19@115656 by Dwayne Reid

flavicon
face
At 10:27 AM 3/19/2010, Olin Lathrop wrote:
>Dario Greggio wrote:
> > Hmmm, I may be missing something but.. I can't get any result out of
> > the IIR filtering, nor the raw samples, nor their average...
> >
> > Well, I simulated 20 samples (one full sine wave) on an Excel
> > spreadsheet, and tried shifting the sine with respect to the sampling
> > point, and the result does change a lot - not good.
> >
> > Can you suggest where I'm going wrong?
>
>It's not clear what exactly you're doing.  You have 20 samples of a sine
>wave, but what are you trying to get from those and what are you getting?
>
>If this signal contains harmonics, did you remember to apply a anti-aliasing
>filter to get rid of the ones your sample stream can't represent?

Hi there, Olin.

He's referring to a post I made where I showed my IIR filter (written
in assembler).  I'll paste a copy below.

He's converting it to C - I'm not adequately competent to determine
if there is an error in translation or not.

Copy starts:

This routine runs in my background task which executes every 1.024ms.

"rampg1" & "rampg0" are macros that set the appropriate page
bits.  Those are a single instruction for the 12f675 but
would  expand to two instructions for PICs with 4 RAM pages.

BGTMP1,2 are temporary RAM bytes for use by the background routine
and are not persistent.

A/D is configured for 10 bit result (right-justified).  The a/d start
command occurs when the background task is about to finish and is not
shown here.

;AD routines: 1 ch with 16 sample IIR filter.  Choose 16 samples 'cuz
; 16 * 1.024ms ~~ 16.667ms (period of 60Hz signal).
; Would need to go to more than 20 samples for 50Hz signal (use 32 samples).

;divide sum by 16   AD1:AD1L /16 -> BGTMP2:BGTMP1
    swapf       AD1L,W          ;LO byte
    andlw       b'00001111'
    movwf       BGTMP1          ;hi nib AD1L -> lo nib BGTMP (>>4)
    swapf       AD1,W           ;HI byte
    movwf       BGTMP2          ;swap nibs AD1 -> BGTMP2     (>>4)
    andlw       b'11110000'     ;clr lo nib in W
    xorwf       BGTMP2,F        ;clr hi nib BGTMP2 (XOR value with
itself is 0)
    iorwf       BGTMP1,F        ;lo nib AD1 -> hi nib BGTMP1 (>>4)

;subtract old sample from sum
    movfw       BGTMP1          ;LS byte
    subwf       AD1L,F          ;F-W ->d

    movfw       BGTMP2
    skpc
      incfsz    BGTMP2,W
        subwf   AD1,F

;add new sample to sum
    rampg1
    movfw       RB1(ADRESL)
    rampg0
    addwf       AD1L,F

    movfw       ADRESH
    skpnc
      incfsz    ADRESH,W
        addwf   AD1,F
;done.  Do all line voltage tests on sum (AD1,AD1L)


dwayne

--
Dwayne Reid   <dwaynerEraseMEspam.....planet.eon.net>
Trinity Electronics Systems Ltd    Edmonton, AB, CANADA
(780) 489-3199 voice          (780) 487-6397 fax
http://www.trinity-electronics.com
Custom Electronics Design and Manufacturing

2010\03\19@120732 by Dario Greggio

face picon face
Dwayne Reid ha scritto:
> He's referring to a post I made where I showed my IIR filter (written
> in assembler).  I'll paste a copy below.


thank you Dwayne :)

Basically - pseudocode:

Take 20 samples/sine
for each sample
       take previous sum
       divide by 20
       subtract this (sum/20) from previous sum
       add new sample to sum

At the end of 20 samples... then what?

--

Ciao, Dario
--
Cyberdyne

2010\03\19@122404 by Olin Lathrop

face picon face
Dario Greggio wrote:
> Basically I need to measure 220V mains,

Measure the actual voltage?  Peak?  RMS?  What?

> by mean of a 220->6 tiny
> transformer and a partitor and a protection diode, staight into a
> PIC's ADC.

So the 0 value is Vdd/2 and the peaks are within the A/D range?

> I'm sampling the sine every 1mS and was wondering of a FFT or average
> or else... I need some 5% accuracy.

It sounds like you are trying to measure the mains voltage, so it being
close to a sine wave is a good assumption.  I don't see anything useful a
FFT is going to do for you, although it's still not clear exactly what you
want out.

If you have the memory, you could keep the last 20 samples, which will
always contain the most recent top and bottom peaks.  Each sample is spaced
18deg apart, so there is always a sample within 9deg of each peak.
COS(9deg) = 0.988, which is well within your 5% error tolerance.  In other
words, peak detection of your samples yields at most 1.2% error due to
missing the peaks a little.

The max minus min of the stored samples gives you the peak to peak voltage.
That divided by 2*sqrt(2) yields the RMS voltage, assuming sine wave.

There are a lot more details depending on what you want to do about short
term spikes, harmnoic content, etc.  If memory is a issue, there are ways to
get the peaks without storing a whole cycle worth of data.


********************************************************************
Embed Inc, Littleton Massachusetts, http://www.embedinc.com/products
(978) 742-9014.  Gold level PIC consultants since 2000.

2010\03\19@122717 by Olin Lathrop

face picon face
Dwayne Reid wrote:
> He's referring to a post I made where I showed my IIR filter (written
> in assembler).  I'll paste a copy below.

You are getting way ahead of the requirements.  I haven't heard a reason why
a IIR filter is needed, and you didn't explain what exactly your IIR filter
is trying to filter.  Looking at implementation details at this stage is
pointless.


********************************************************************
Embed Inc, Littleton Massachusetts, http://www.embedinc.com/products
(978) 742-9014.  Gold level PIC consultants since 2000.

2010\03\19@123343 by Olin Lathrop

face picon face
Dario Greggio wrote:
> Take 20 samples/sine
> for each sample
> take previous sum
> divide by 20
> subtract this (sum/20) from previous sum
> add new sample to sum

That makes no sense for any reasonable interpretation of "measure mains
voltage".  Remember this is a AC signal.  This description above is not
totally clear, but it looks like you're box filtering the signal, sortof, I
guess.  Box filtering a AC signal with a aperture width a multiple of the
period will always yield 0.  In other words, the sum of any consecutive 20
samples (one whole period) will be 0.

Again, it's too early to jump into the implementation since there isn't yet
a clear definition of what exactly you want.  On top of that this
implementation appears broken, at first glance at the level of detail of
what I think the above description is saying anyway.


********************************************************************
Embed Inc, Littleton Massachusetts, http://www.embedinc.com/products
(978) 742-9014.  Gold level PIC consultants since 2000.

2010\03\19@124227 by Dario Greggio

face picon face
Yeah, I need the RMS i.e. 220V :)

The Filtering idea was provided by Dwayne as part of his code and I took
it kind of good, since "smoothing" could've helped in making the samples
more "smooth"...

But indeed the idea of grabbing the peak out of 20mS makes sense - I
started with a FFT, then I realized (and was suggested) it was too much.
Then I wanted to take a sample here & there, and this was not going to
work. Then I made up my mind with the "20mS window" and now this gets
better.

I do have memory - a 24F PIC, so I might try what you suggest. I will
recheck your calculations about degrees and errors, but makes sense.

I also have to say that, after the IIR, overall sum of 20 samples does
no longer yeld 0... ! (this was part of my astonishment, but I have
proably skipped some steps)

thank you!

--

Ciao, Dario
--
Cyberdyne

2010\03\19@125900 by Marechiare

picon face
Dario Greggio wrote:

> Basically I need to be sure that VAC is not lower
> than 200V (say) or higher than 240 before activating
> the pumps, the valves, or else. So precision is not
> *that* important, but still somehow.

...

{Quote hidden}

Why not some simple scheme with Zener diode and an optocoupler to send
a signal to the PIC when the peak voltage is higher than some certain
level?

Two voltage dividers and the optocouple between them. One divider
would have a Zener instead of the bottom resistor. Select the resistor
values the way that the shortest signal would correspond to the bottom
value of the desired voltage range. Measuring length of the signal
you could figure out the peak voltage.

Also a PIC could adjust the divider ratio using relays if you need to
change the measured range dynamically.

2010\03\19@130432 by Michael Rigby-Jones

flavicon
face


> -----Original Message-----
> From: EraseMEpiclist-bouncesspamMIT.EDU [RemoveMEpiclist-bouncesEraseMEspamEraseMEMIT.EDU] On
Behalf
{Quote hidden}

mains
> voltage".  Remember this is a AC signal.  This description above is
not
> totally clear, but it looks like you're box filtering the signal,
sortof,
> I
> guess.  Box filtering a AC signal with a aperture width a multiple of
the
> period will always yield 0.  In other words, the sum of any
consecutive 20
> samples (one whole period) will be 0.
>
> Again, it's too early to jump into the implementation since there
isn't
> yet
> a clear definition of what exactly you want.  On top of that this
> implementation appears broken, at first glance at the level of detail
of
> what I think the above description is saying anyway.

Looking back through the posts in this topic I think there may be a
fundamental disconnect between Dwaynes measurement technique and what
Dario is hoping to achieve.  Dwayne is rectifying and smoothing the AC,
so a box filter could be useful to get the mean DC value and reject any
ripple.  

I may be wrong but I get the impression that Dario is effectively half
wave rectifying the AC waveform by clipping the negative side to ground
with a diode since there was some discussion on the dangers of not using
the PICs protection diodes for this.  Since that will give one half
cycle of positive input followed by one half cycle of 0 volts it's not
surprising his box filter isn't giving zero (would be Vpeak/PI I
think?).  A schematic would certainly reduce confusion here.

Regards

Mike

=======================================================================
This e-mail is intended for the person it is addressed to only. The
information contained in it may be confidential and/or protected by
law. If you are not the intended recipient of this message, you must
not make any use of this information, or copy or show it to any
person. Please contact us immediately to tell us that you have
received this e-mail, and return the original to us. Any use,
forwarding, printing or copying of this message is strictly prohibited.
No part of this message can be considered a request for goods or
services.
=======================================================================

2010\03\19@130707 by Olin Lathrop

face picon face
Dario Greggio wrote:
> Yeah, I need the RMS i.e. 220V :)

But how do you want to handle harmonics and spikes?  Are you trying to
detect the spikes or want to filter them out?  If you want more of a
smoothed RMS, what kind of response time?  You can't start thinking about
the right filter until you know what you want it to accomplish.

> The Filtering idea was provided by Dwayne as part of his code and I
> took it kind of good, since "smoothing" could've helped in making the
> samples more "smooth"...

OK, so it sounds like you want a smoothed recent RMS voltage.  Now we're
finally getting somewhere, although I still haven't heard what response time
you are willing to live with in order to get a smoothed value, and how much
you want to attenuate random noise.

If that's all you want, a simple peak detector followed by two low pass
filter will work nicely.  You don't need to store 20 recent samples, only 1
and a flag.  As the samples come in, look for local minima and maxima.  Each
go into separate low pass filters.  You adjust the time constant and number
of poles of these filters to get the random noise reduction and reponse time
you want.  Keep in mind that each filter will only be fed at the line
frequency of 50Hz.  Every time you update the filters, the final filtered
maxima minus the final filtered minima times a fixed constant is the line
voltage.

> I also have to say that, after the IIR, overall sum of 20 samples does
> no longer yeld 0... !

Actually it should yield 20x whatever the representation of 0 line voltage
is in your system.  If your input signal is offset by half Vdd and that is
not subtracted out then you will get 20x that offset.  However, the AC
information you are looking for will be gone and only this "effective zero"
will be left.


********************************************************************
Embed Inc, Littleton Massachusetts, http://www.embedinc.com/products
(978) 742-9014.  Gold level PIC consultants since 2000.

2010\03\19@131032 by Olin Lathrop

face picon face
Michael Rigby-Jones wrote:
> A schematic would certainly reduce confusion here.

Definitely.  The requirements are vague and the implementation even vaguer.
I thought the scaled down AC was centered on Vdd/2 with the peaks within the
A/D range.  That would be the best for measuring the "smoothed recent line
voltage", but we need to know what we actuall have.


********************************************************************
Embed Inc, Littleton Massachusetts, http://www.embedinc.com/products
(978) 742-9014.  Gold level PIC consultants since 2000.

2010\03\19@131323 by Dario Greggio

face picon face
Michael Rigby-Jones ha scritto:
> Looking back through the posts in this topic I think there may be a
> fundamental disconnect between Dwaynes measurement technique and what
> Dario is hoping to achieve.  Dwayne is rectifying and smoothing the AC,
> so a box filter could be useful to get the mean DC value and reject any
> ripple.  

This makes sense definitely :) !



> I may be wrong but I get the impression that Dario is effectively half
> wave rectifying the AC waveform by clipping the negative side to ground
> with a diode since there was some discussion on the dangers of not using
> the PICs protection diodes for this.  Since that will give one half
> cycle of positive input followed by one half cycle of 0 volts it's not
> surprising his box filter isn't giving zero (would be Vpeak/PI I
> think?).  A schematic would certainly reduce confusion here.


And this too.
I'll try to make up the schematic, but it is really that simple:

220V -> transformer -> one leg to GND, other to partitor -> partitor
output to PIC || diode.

--

Ciao, Dario
--
Cyberdyne

2010\03\19@131803 by Dario Greggio

face picon face
Olin Lathrop ha scritto:
> But how do you want to handle harmonics and spikes?  Are you trying to
> detect the spikes or want to filter them out?  If you want more of a
> smoothed RMS, what kind of response time?  You can't start thinking about
> the right filter until you know what you want it to accomplish.

No, I need the Basic 220V, indeed filtered "somehow" - but my response
time is in the range of 1-5 seconds i.e. less than an average multimeter.
Basically, let's avoid spikes such as pumps starting etc.


> If that's all you want, a simple peak detector followed by two low pass
> filter will work nicely.  You don't need to store 20 recent samples, only 1
> and a flag.  As the samples come in, look for local minima and maxima.  Each
> go into separate low pass filters.  You adjust the time constant and number
> of poles of these filters to get the random noise reduction and reponse time
> you want.  Keep in mind that each filter will only be fed at the line
> frequency of 50Hz.  Every time you update the filters, the final filtered
> maxima minus the final filtered minima times a fixed constant is the line
> voltage.

ok... I guess I get this too.
Something like the "simple" (you showed it many times)

new_value = (ADC_value+(old_value) ) / 2

done for both max and min.



>> I also have to say that, after the IIR, overall sum of 20 samples does
>> no longer yeld 0... !
>
> Actually it should yield 20x whatever the representation of 0 line voltage
> is in your system.  If your input signal is offset by half Vdd and that is
> not subtracted out then you will get 20x that offset.  However, the AC
> information you are looking for will be gone and only this "effective zero"
> will be left.


makes sense, and this is indeed a different application. Useful to know
for the future :)

2010\03\19@131943 by Marechiare

picon face
> The requirements are vague and the implementation even
> vaguer. I thought the scaled down AC was centered on
> Vdd/2 with the peaks within the A/D range.

Conceptually "scaled down full AC range" is not quite perfect
approach. Better one would be to scale down the _measured_ range.

2010\03\19@131957 by Dario Greggio

face picon face
Marechiare ha scritto:
> Why not some simple scheme with Zener diode and an optocoupler to send
> a signal to the PIC when the peak voltage is higher than some certain
> level?

Thank you Marechiare - we've been into this and I did not want to add
more parts. Liked a complete-software approach..



--

Ciao, Dario
--
Cyberdyne

2010\03\19@132419 by Adam Field

flavicon
face
> And this too.
> I'll try to make up the schematic, but it is really that simple:
>
> 220V -> transformer -> one leg to GND, other to partitor -> partitor
> output to PIC || diode.

Where does the diode go? I think you are rectifying the signal to the
PIC ADC, which means you are only receiving the top half. Leaving the
bottom half clipped at either your diode or the PIC internal
protection diode.

You either need to account for this in software or capacitivly couple
the signal and add a DC bias, but with a 6V transformer, you don't
have enough room between your 0-VDD rail without a resistive divider.

2010\03\19@132640 by Olin Lathrop

face picon face
Dario Greggio wrote:
> 220V -> transformer -> one leg to GND, other to partitor -> partitor
> output to PIC || diode.

Oh, that makes things a bit more difficult.  I'm assuming "partitor" is a
resistive voltage divider?


********************************************************************
Embed Inc, Littleton Massachusetts, http://www.embedinc.com/products
(978) 742-9014.  Gold level PIC consultants since 2000.

2010\03\19@132822 by Olin Lathrop

face picon face
Dario Greggio wrote:
> ok... I guess I get this too.
> Something like the "simple" (you showed it many times)
>
> new_value = (ADC_value+(old_value) ) / 2
>
> done for both max and min.

Not any more since you explained that negative values are clipped.  That
makes things more difficult.


********************************************************************
Embed Inc, Littleton Massachusetts, http://www.embedinc.com/products
(978) 742-9014.  Gold level PIC consultants since 2000.

2010\03\19@133038 by Russell McMahon

face picon face

> 220V -> transformer -> one leg to GND, other to partitor -> partitor
> output to PIC || diode.

1. "Partitor" does not translate well into English speaking brains :-)

Explaining what a "partitor" is will help those (including me) with limited
languages.

Maybe:

partītor, ōris, m. [partior], a divider, distributer: cum te partitorem ad
partiendas merces missum putares, Cic. Vatin. 5, 12 dub. (al. portitorem);
cf. partitor, μεριστής, Gloss. Philox.

= junction ?, connection point, terminal? ...

If "junction" then description translates to:
Transformer secondary with 1 leg to ground. Other leg via diode to PIC ADC
input.

If partitor = resistor then

... Other led voa series resistor and series diode to PIC ADC input.



2. The discussion has become extremely circular. Much of what is being said
in the last X posts was covered near the start of this thread.

Summary from memory:

- Aim is to detect that mains is within desired voltage range.

- Transformer secondary output is available.

- Use of PIC ADC as means of measurement is desired.

- Absolute minimum of hardware desired.

- Various peak detection and waveform magnitude measurement systems have
been described.

- Connection of transformer secondary to Vdd with resistor divider to PIC
pin was suggested (by me) giving always +ve signal always between Vdd-Vss
and 2 resistors total (and maybe smoothing cap.

- Effects of noise etc were commented on along the way.

- Current hardware seems slightly inferior to and more complex than my 2
resistor suggestion. Reason for not using my suggestion is unknown.


   Russell

2010\03\19@133125 by Marechiare

picon face
On Fri, Mar 19, 2010 at 7:19 PM, Dario Greggio wrote:
> Marechiare ha scritto:
>> Why not some simple scheme with Zener diode and an optocoupler
>> to send a signal to the PIC when the peak voltage is higher than some
> certain level?
>
> Thank you Marechiare - we've been into this and I did not want to add
> more parts. Liked a complete-software approach..

Let us speak about transformers, for the mentioned transformer seems
not to fit well the "complete-software approach" :-)

2010\03\19@133441 by Russell McMahon

face picon face
> > 220V -> transformer -> one leg to GND, other to partitor -> partitor
> > output to PIC || diode.

> Oh, that makes things a bit more difficult.  I'm assuming "partitor" is a
> resistive voltage divider?

Ah!

IF partitor is a resistive divider then you can.
- Connect one transformer leg to Vdd.
- Connect other leg to top of divider.
- Discard diode
- Connect PIC ADC input to divider "tap".

You now have my scheme, always positive, full cycle.
Minimum is above ground and positive below Vdd when divider is set correctly.
(See prior decription).

           Russell
.

2010\03\19@133826 by Russell McMahon

face picon face
A circuit diagram would be a REALLY good idea.
A partitor MAY be a simple device but until we know what it is then we
don't understand the question.

IF it is a divider consisting of two resistors then it would be very
wise to fully describe how each resistor is connected so that there is
no uncertainty OR provide a diagram.

At the moment people (including me) are "wandering around in the dark"
because the circuit description is uncertain.




                   Russell

2010\03\19@134153 by Russell McMahon

face picon face
>> The requirements are vague and the implementation even
>> vaguer. I thought the scaled down AC was centered on
>> Vdd/2 with the peaks within the A/D range.

> Conceptually "scaled down full AC range" is not quite perfect
> approach. Better one would be to scale down the _measured_ range.

Circuit PLEASE

           Russell

2010\03\19@134637 by Russell McMahon

face picon face
>> Thank you Marechiare - we've been into this and I did not want to add
>> more parts. Liked a complete-software approach..

> Let us speak about transformers, for the mentioned transformer seems
> not to fit well the "complete-software approach" :-)

I understand that connecting AC mains seemed to result in magic smoke
being let out of the PIC, so a transformer seemed like a good idea
:-).

I think that we can't do too much more good until we know the final
actual circuit. It is obviously simple but undertain. I think that
Olin's version is probably correct (and that mine is wrong). When we
all know what a partitor is (divider?) it will be clearer.


              Russell

2010\03\19@135334 by Dario Greggio

face picon face
ok ok circuit coming soon :)

I actually know, at the moment, of the implications of clipping (good or
poorly) one half of the wave, and the DC offset etc.

But I'd like to know the way "it would be done" if a sine wave was
available :)


PS: I learnt from some forum/sites that "partitor" was good english
(somewhat at least :) for "resistor-based divider". Sorry if I was
wrong.. :)

--

Ciao, Dario
--
Cyberdyne

2010\03\19@135422 by Dwayne Reid

flavicon
face
At 11:27 AM 3/19/2010, Olin Lathrop wrote:
>Dwayne Reid wrote:
> > He's referring to a post I made where I showed my IIR filter (written
> > in assembler).  I'll paste a copy below.
>
>You are getting way ahead of the requirements.  I haven't heard a reason why
>a IIR filter is needed, and you didn't explain what exactly your IIR filter
>is trying to filter.  Looking at implementation details at this stage is
>pointless.

Sorry - looks like you missed the previous part of this thread.

My IIR filter is used to reduce the ripple as measured from a line
voltage sampling network.  Basically, that is a half-wave rectified
sine wave fed into a RC network, then into the PIC.

He had asked for advice on measuring a line voltage, I had replied
with a description of my most recent version which is a combination
of hardware and a software filter, he then asked for a copy of my IIR filter.

dwayne

--
Dwayne Reid   <RemoveMEdwaynerspam_OUTspamKILLspamplanet.eon.net>
Trinity Electronics Systems Ltd    Edmonton, AB, CANADA
(780) 489-3199 voice          (780) 487-6397 fax
http://www.trinity-electronics.com
Custom Electronics Design and Manufacturing

2010\03\19@135713 by Mark E. Skeels

flavicon
face
OK, Fine; measuring is one thing, but what about circuit protection?

If there are spikes and surges present, how would you go about
protecting the circuit?

Mark Skeels
Engineer
Competition Electronics, Inc.
TEL: 815-874-8001
FAX: 815-874-8181
http://www.competitionelectronics.com


2010\03\19@135836 by Dario Greggio

face picon face
part 0 44 bytes
his is a multi-part message in MIME format.
part 1 74 bytes content-type:text/plain; charset=ISO-8859-1; format=flowed (decoded 7bit)

circuit
--

Ciao, Dario
--
Cyberdyne


part 2 26520 bytes content-type:image/jpeg; (decode)


part 3 35 bytes content-type:text/plain; charset="us-ascii"
(decoded 7bit)

2010\03\19@135904 by Dario Greggio

face picon face
Marechiare ha scritto:

> Let us speak about transformers, for the mentioned transformer seems
> not to fit well the "complete-software approach" :-)


:) but I *needed* to isolate mains from the board...

2010\03\19@140014 by Dario Greggio

face picon face
Russell McMahon ha scritto:
{Quote hidden}

very good resume :) Russell, thank you :)
I'll consider the "full-positive, go VDD" approach later...

2010\03\19@141351 by Marechiare

picon face
Russell McMahon wrote:
>>> The requirements are vague and the implementation even
>>> vaguer. I thought the scaled down AC was centered on
>>> Vdd/2 with the peaks within the A/D range.
>
>> Conceptually "scaled down full AC range" is not quite perfect
>> approach. Better one would be to scale down the
>>_measured_ range.
>
> Circuit PLEASE

Which circuit, Dario's or mine is so desperately expected to break the
darkness the people are "wandering around in" at the moment?

2010\03\19@150328 by Olin Lathrop

face picon face
Dwayne Reid wrote:
> My IIR filter is used to reduce the ripple as measured from a line
> voltage sampling network.  Basically, that is a half-wave rectified
> sine wave fed into a RC network, then into the PIC.
>
> He had asked for advice on measuring a line voltage, I had replied
> with a description of my most recent version which is a combination
> of hardware and a software filter, he then asked for a copy of my IIR
> filter.

So then how did the transformer get wired up in such a inconvenient way?
Which rocket scientist suggested clipping half the signal?


********************************************************************
Embed Inc, Littleton Massachusetts, http://www.embedinc.com/products
(978) 742-9014.  Gold level PIC consultants since 2000.

2010\03\19@151927 by Dario Greggio

face picon face
Olin Lathrop ha scritto:

> So then how did the transformer get wired up in such a inconvenient way?
> Which rocket scientist suggested clipping half the signal?


ehm, me :)
Dwayne is not implied at all.

But, in my opinion, it was not much different from a single-diode rectifier


--

Ciao, Dario
--
Cyberdyne

2010\03\19@153452 by Olin Lathrop

face picon face
part 1 962 bytes content-type:text/plain; (decoded 7bit)

Dario Greggio wrote:
> circuit

Yucc.  It's inconvenient to only have the PIC see half the wave, but that
can be dealt with in firmware.  What I really don't like is the way the
negative values are clipped.  At the very least, D4 needs to be a zener
diode.  Allowing any appreciable current to flow thru the protection diodes
can really mess up A/D readings.  I have found this from experience, and the
datasheet, especially for newer PICs, frowns on this too.

Attached is a simple circuit that provides all the possible information to
the PIC firmware and doesn't have any issues with clipping.  For Vdd of
3.3V, this will tolerate input line voltage up to about 260V, assuming 220/6
stepdown ratio of your transformer.  This should leave reasonable room for
part tolerances, voltage range, etc, but still allow plenty of resolution
with the PIC A/D.  It also filters out spikes and frequencies that will
cause aliasing.


part 2 6919 bytes content-type:image/gif; (decode)


part 3 35 bytes content-type:text/plain; charset="us-ascii"
(decoded 7bit)

2010\03\19@154331 by Olin Lathrop

face picon face
Olin Lathrop wrote:
> At the very least, D4 needs to be a zener diode.

Doh!  I meant to say Schottky diode.


********************************************************************
Embed Inc, Littleton Massachusetts, http://www.embedinc.com/products
(978) 742-9014.  Gold level PIC consultants since 2000.

2010\03\19@155040 by Dario Greggio

face picon face
Olin Lathrop ha scritto:
> Olin Lathrop wrote:
>> At the very least, D4 needs to be a zener diode.
>
> Doh!  I meant to say Schottky diode.

sure :)

ok
so, now assuming that I will re-do the pcbs :))

you suggest I still use the max-min approach?
I'm testing it now in Excel and, though I do at times get errors up to
9%... it seems to be good enough. No filtering right now.

--

Ciao, Dario
--
Cyberdyne

2010\03\19@161026 by Olin Lathrop

face picon face
Dario Greggio wrote:
> so, now assuming that I will re-do the pcbs :))

I think clever firmware can figure out the voltage with what you've got.
It's not how I would have done it, but it should still be possible.  You do
however have to change the silicon diode to a Schottky.

> you suggest I still use the max-min approach?

No, not with the half wave rectified method.

If you make the assumption the input is nearly a sine, then you can get away
with measuring only the peaks.  There are various things you can do to get
successively more clever, depending on what performance you really need.

First approximation is simply finding the peak of each period, and low pass
filtering those a little.  The theoretical error due to missing the peak is
about 1.2%, which is well under your 5% spec, so maybe you can stop there.

If you're worried about spikes and other noise messing up the peak
measurements, you can apply just a little low pass filtering and then look
for the peaks.  The next step is to do third order approximation on the
three nearest samples to the peak to find the true peak.  Such a small part
of a sine can be approximated quite well with a 3rd order polynomial, so the
1.2% error will pretty much vanish.

It depends on what characteristics you care about and how much programming
and CPU time you are willing to spend on it.


********************************************************************
Embed Inc, Littleton Massachusetts, http://www.embedinc.com/products
(978) 742-9014.  Gold level PIC consultants since 2000.

2010\03\19@163225 by Marechiare

picon face
> Russell McMahon ha scritto:
>> - Aim is to detect that mains is within desired voltage range.
>>
>> - Transformer secondary output is available.

It is not unusual that the trade-off for a transformer is that the
secondary voltage drops 20% or even more under the full load. If this
is the case, it may cause some difficulty to "measure 220V mains
voltage with some coarse accuracy, say 1-2%" using the available
secondary output.

2010\03\19@164303 by Dario Greggio

face picon face
Marechiare ha scritto:
> It is not unusual that the trade-off for a transformer is that the
> secondary voltage drops 20% or even more under the full load. If this
> is the case, it may cause some difficulty to "measure 220V mains
> voltage with some coarse accuracy, say 1-2%" using the available
> secondary output.


No, this transformer is dedicated to this aim - measuring.
(it was taken into account :) - circuitry is powered by a couple of
Traco AC-DC and DC-DC modules)

--

Ciao, Dario
--
Cyberdyne

2010\03\19@231714 by Marechiare

picon face
--0015174791866b87c8048232e608
Content-Type: text/plain; charset=ISO-8859-1

Perhaps the attached scheme could replace the dedicated transformer
and related parts.

The optocoupler can be Vishay VO221AT 1 mA LED current Optocoupler,
Photodarlington Output, Low Input Current. It should work at a
fraction of 1 mA current through its LED.

Regards.

===

Why not some simple scheme with Zener diode and an optocoupler to send
a signal to the PIC when the peak voltage is higher than some certain
level?

Two voltage dividers and the optocouple between them. One divider
would have a Zener instead of the bottom resistor. Select the resistor
values the way that the shortest signal would correspond to the bottom
value of the desired voltage range. Measuring length of the signal you
could figure out the peak voltage.

Also a PIC could adjust the divider ratio using relays if you need to
change the measured range dynamically.

===

On Fri, Mar 19, 2010 at 10:42 PM, Dario Greggio <RemoveMEadpm.toTakeThisOuTspamspaminwind.it> wrote:
{Quote hidden}

> -

2010\03\20@084544 by Dario Greggio

face picon face
Marechiare ha scritto:
>[...]
> Why not some simple scheme with Zener diode and an optocoupler to send
> a signal to the PIC when the peak voltage is higher than some certain
> level?
>
> Two voltage dividers and the optocouple between them. One divider
> would have a Zener instead of the bottom resistor. Select the resistor
> values the way that the shortest signal would correspond to the bottom
> value of the desired voltage range. Measuring length of the signal you
> could figure out the peak voltage.


Hmmm, a nice approach :)
I used that circuitry - actually with a .47nF 630V capacitor - to make
up a "220V presence sensor" which alerts me of when mains goes away (you
know, interfacing to the UPS is never easy :) because of protocols etc;
and anyway I wanted a more generic method).

I'd like to try your method of "measuring the peak width in order to get
the peak amplitude", I'll check it...

Still, using some "large" resistors (or the large capacitor) is not that
smaller (and maybe cheaper) than the transformer.

but thank you !

--

Ciao, Dario
--
Cyberdyne

2010\03\20@091314 by Marechiare

picon face
Dario Greggio wrote:
> Still, using some "large" resistors (or the large capacitor)
> is not that smaller (and maybe cheaper) than the transformer.

The resistors are not necessarily large.

VOD223T - high current transfer ratio (CTR) optocoupler would start
working with LED current as low as 0.1 mA, I'm almost sure. It should
be easy to achieve that 0.1 mA change on VOD223T at, say, 10 mA
combined peak current of the circuit. 10 mA would mean 3 W peak power
dissipation. The fact that it's sine cuts the power twice, and we use
only half the wave, this would cut twice the power dissipation again.

3 W / 4 = 0.75 W per 4 components would demand 0.25 resistors, and you
could try 5 mA combined current, not 10 mA.

Thanks for the opportunity to have some fun.

2010\03\20@111806 by Dario Greggio

face picon face
Olin Lathrop ha scritto:
> No, not with the half wave rectified method.

ok, though I don't see an exact... reason. I mean, scaling it
differently, it should give some good results all the same. But actually
maybe it is no longer needed.


> If you make the assumption the input is nearly a sine, then you can get away
> with measuring only the peaks.  There are various things you can do to get
> successively more clever, depending on what performance you really need.

ok


> First approximation is simply finding the peak of each period, and low pass
> filtering those a little.  The theoretical error due to missing the peak is
> about 1.2%, which is well under your 5% spec, so maybe you can stop there.

ok, my idea was to make this peak-measurement every 20mS, and average it
with the previous one. Resimulated the peak method, and it fits in the
1.2% error indeed.


> If you're worried about spikes and other noise messing up the peak
> measurements, you can apply just a little low pass filtering and then look
> for the peaks.  The next step is to do third order approximation on the
> three nearest samples to the peak to find the true peak.  Such a small part
> of a sine can be approximated quite well with a 3rd order polynomial, so the
> 1.2% error will pretty much vanish.

I also implemented this, storing 20 samples and grabbing the 3 highest,
and averaging them. Still have to try it on both simulation and
hardware. What would you suggest, if you can point me to an "algorithm",
in depth?



> It depends on what characteristics you care about and how much programming
> and CPU time you are willing to spend on it.


As I said, timing is not critical at all, even making one measure out of
1 second would be more than good (compared to the 50, now). CPU power is
indeed in excess (apart from the Ethernet part of it).

thx
Dario

2010\03\20@132815 by Olin Lathrop

face picon face
Dario Greggio wrote:
>> No, not with the half wave rectified method.
>
> ok, though I don't see an exact... reason. I mean, scaling it
> differently, it should give some good results all the same. But
> actually maybe it is no longer needed.

The method I thought you were referring to was finding the negative and
positive peaks, low pass filtering each of those seperately, then using the
difference between the two filter outputs to be the line voltage.  This
can't work now since the processor can't see the negative peaks.

> ok, my idea was to make this peak-measurement every 20mS, and average
> it
> with the previous one. Resimulated the peak method, and it fits in the
> 1.2% error indeed.

You are still sampling at 1KHz to find the peaks, right?  The 1.2% error I
mentioned comes from the 1KHz samples missing the peak by as much as 500uS.

> I also implemented this, storing 20 samples and grabbing the 3
> highest, and averaging them.

Hmm.  I'm not sure what that does to the worst case error.  You still don't
know where the peak was in time any better than before.  It may be that you
get a little less variation in the output as the sample frequency shifts in
phase with respect to the signal being sampled.  The constant to go from
this result to the input line voltage would also need to be a little higher
since you're never getting exactly the peak voltage.

This is where simulation is probably easier than going thru all the math.
Try a bunch of cases, each differing only in the phase between the 1KHz
samples and the input signal.  When using a single peak sample, the results
will be over a 1.2% range.  If you get a lower variation by averaging the
top 3 samples, then that sounds like a easy way to get a little less error.
The simulation can also tell you what the center scale factor is.  However,
I would worry about the effects of random noise on this method.

> Still have to try it on both simulation and
> hardware. What would you suggest, if you can point me to an
> "algorithm", in depth?

At this point I would probably apply a little low pass filtering to the raw
1KHz samples before doing anything more with them.  Two poles with a filter
fraction of .25 (2 bit shift) looks about right.  Every filter output sample
then is a function of a bunch of recent raw input samples, with random noise
attenuated by a factor of 16.  Let this do the "averaging" for you.  Now you
can pick off the peaks of the filtered signal and use them times a fixed
scale factor to get input line voltage.  Since each of these peaks will be a
function of a bunch of input samples, the result will have less variation
due to sample phase, in addition to having some noise immunity.

You got me curious, so I create a quick hack program to simulate this.  I
simulated one second plus one cycle.  You can see the result at
http://www.embedinc.com/temp/dario.csv.  The filters were still initializing
for the first cycle, so ignore that one.  I made the sample period 1.001 mS
so that the phase would change thru one whole cycle over the simulated
second.  You can see that the peaks of the filter output vary very little
over the full phase difference.  http://www.embedinc.com/temp/dario.gif
shows the cycle in the middle, when the input peak is straddeled evenly with
two sample.  Note that the top of the red curve doesn't quite reach 1.0.
That's the 1.2% error I was talking about before.

However, you'd be using the peaks of the cyan curve.  Those vary much less
with the phase because each of those samples is a function of a bunch of
recent raw input samples.  Look in the CSV file at the peak at 0.5085
seconds and the one at 1.009 seconds.  These are at the worst case opposites
of the phase.  The difference is less than 1/2 percent, so you can just
ignore it according to your ealier specs.

The program that generated this CSV file is at
http://www.embedinc.com/temp/dario.pas, although there is nothing really to
see in there.


********************************************************************
Embed Inc, Littleton Massachusetts, http://www.embedinc.com/products
(978) 742-9014.  Gold level PIC consultants since 2000.

2010\03\20@134502 by Russell McMahon

face picon face
There seems to be a reluctance to even consider the suggestion I made.
It may have been commented on an rejected for some good reason but I
don't recall seeing it.
Transformer and 2 resistors in basic form.
Connect one leg to Vdd, other via divider to ground and tap to ADC in.
Add cap if desired for noise handling.

Track smoothed minimum and maximum to give loaded full voltage excursion.
Sounds super easy, no body diodes at risk, no diode drops, minimum
components, full cycle of waveform, ... .
?

     R

2010\03\20@135053 by Olin Lathrop

face picon face
Russell McMahon wrote:
> There seems to be a reluctance to even consider the suggestion I made.
> It may have been commented on an rejected for some good reason but I
> don't recall seeing it.
> Transformer and 2 resistors in basic form.
> Connect one leg to Vdd, other via divider to ground and tap to ADC in.
> Add cap if desired for noise handling.

The hardware has apparently been built already, so it is what it is.  That
means the problem shifts to what can be done in firmware given the current
hardware.  While the current hardware is not ideal, it is still definitely
possible to figure out the original line voltage in firmware with the
information it does have available.


********************************************************************
Embed Inc, Littleton Massachusetts, http://www.embedinc.com/products
(978) 742-9014.  Gold level PIC consultants since 2000.

2010\03\20@135933 by Dario Greggio

face picon face
Russell McMahon ha scritto:
> There seems to be a reluctance to even consider the suggestion I made.
> It may have been commented on an rejected for some good reason but I
> don't recall seeing it.
> Transformer and 2 resistors in basic form.
> Connect one leg to Vdd, other via divider to ground and tap to ADC in.
> Add cap if desired for noise handling.
>
> Track smoothed minimum and maximum to give loaded full voltage excursion.
> Sounds super easy, no body diodes at risk, no diode drops, minimum
> components, full cycle of waveform, ... .


No Russell, I did consider it :)
it's appreciated!

As Olin said too, the hardware is already there AND I'm almost sure that
I can get the result all the same with this configuration.

In case I put my hands on the circuit, I'll go with your approach to get
full-span wave and also avoid the -GND overflowing.


I also liked Marechiare's idea, though it brings in completely different
... things.

--

Ciao, Dario
--
Cyberdyne

2010\03\20@140136 by Olin Lathrop

face picon face
Russell McMahon wrote:
> Transformer and 2 resistors in basic form.
> Connect one leg to Vdd, other via divider to ground and tap to ADC in.

You could just as well connect one leg to ground, and the divider between
the other leg and Vdd.

> Sounds super easy, no body diodes at risk, no diode drops,
> minimum components, full cycle of waveform, ...

No.  Go show us real component values and you'll find the flaw in your
topology.  The transformer produces 6V RMS out, which is 17V peak to peak or
+-8.5V if one leg is connected to ground (this is the same as you suggested
just flipped around to make it easier to think about).  Obviously no
resistor divider from 0V to 3.3V can possibly keep a 8.5V input clipped to
3.3V.  There will always be some excursion above Vdd (or below ground
flipped your original way).  That means "full cycle waveform" is impossible
with this method.

To get what you want, you need to add another resistor.  That's basically
the circuit I showed, except that while I was at it I AC coupled it by
adding a cap.  I also added a little low pass filtering cap, which you
mentioned as optional with your approach too.


********************************************************************
Embed Inc, Littleton Massachusetts, http://www.embedinc.com/products
(978) 742-9014.  Gold level PIC consultants since 2000.

2010\03\20@145650 by Dwayne Reid

flavicon
face
At 11:44 AM 3/20/2010, Russell McMahon wrote:
>There seems to be a reluctance to even consider the suggestion I made.
>It may have been commented on an rejected for some good reason but I
>don't recall seeing it.
>Transformer and 2 resistors in basic form.
>Connect one leg to Vdd, other via divider to ground and tap to ADC in.
>Add cap if desired for noise handling.

I suspect there have been no comments for a couple of reasons:

1) One of the schematics that Dario posted shows another signal
tapped off the transformer signal and going to somewhere marked
"dimmer".  I assume that signal needs to be ground-referenced.

2) I don't think that your approach works as you envision it.  I
*think* that Dario mentioned that the transformer has a 12Vac
winding.  That means peak voltage is about plus minus 17V.  Put that
in series with the 5V rail: that gives voltage range of +22V through
-12V.  Doesn't matter what your divider is, you are still going to
see the voltage go below ground.

You would need to add another resistor from Vdd to the divider
tap.  That's pretty much what Olin suggested (although he also
AC-coupled the signal).

dwayne

--
Dwayne Reid   <EraseMEdwaynerspamspamspamBeGoneplanet.eon.net>
Trinity Electronics Systems Ltd    Edmonton, AB, CANADA
(780) 489-3199 voice          (780) 487-6397 fax
http://www.trinity-electronics.com
Custom Electronics Design and Manufacturing

2010\03\20@150753 by Dario Greggio

face picon face
Dwayne Reid ha scritto:

> 2) I don't think that your approach works as you envision it.  I
> *think* that Dario mentioned that the transformer has a 12Vac
> winding.  That means peak voltage is about plus minus 17V.  Put that
> in series with the 5V rail: that gives voltage range of +22V through
> -12V.  Doesn't matter what your divider is, you are still going to [...]


No it is 6V, actually the least I could find :) but the talk is correct
for the rest, including the Dimmer thing.

Actually, I'm considering if I can use the ADC for the Zero Crossing
Task - this would free one pin and some software. Will check later...


--

Ciao, Dario
--
Cyberdyne

2010\03\20@153110 by Marechiare

picon face
> You are still sampling at 1KHz to find the peaks, right?
> The 1.2% error I mentioned comes from the 1KHz samples
> missing the peak by as much as 500uS.

>From what I've read, he needs to reconstruct the sine with that
precision. That's about statistic, peaks does not matter at all. 1000
samples per second in the course of the very slowly (tenths seconds)
changing parameters of the sine signal - that's much more than just
enough to figure out the sine with the precision.

2010\03\20@192657 by Russell McMahon

face picon face
>  You could just as well connect one leg to ground, and the divider between
> the other leg and Vdd.
>
> > Sounds super easy, no body diodes at risk, no diode drops,
> > minimum components, full cycle of waveform, ...
>
> No.  Go show us real component values and you'll find the flaw in your
> topology.

Yes. I understood the limitation with the voltage specified (as you
might expect :-) ).
My subsequent description didn't completely replicate the original -
but I've now don't ahat below :-).

Originally there was no mention of the "dimmer" afair and I gained the
impression that the transformer voltage mentioned was semi-arbitrary
could have a voltage output to suit. Not a good assumption in
retrospect.

As noted, adding one more resistor allows you to both scale and shift
the waveform, allowing arbitrayy input voltage. You could even do it
with main input and 3 resistors :-) :-) :-) :-) .

As the early stuff hasn't been seen by some, here's how I originally
described it (11 days ago now.)



______________

On March 10th  j'escrit:

How does a transformer and 2 resistors sound?

If you wanted a relatively minimalist implementation you could connect
one side of the secondary to a resistive divider across Vdd-Gnd and
the other to a resistive divider to ground with the PIC A2C tapped off
that.


As long as Vpp < Vdd the output is always positive.

In the limiting version of this you connect one side of transformer to
Vdd and the output to a divider to ground and tap ADC input off the
divider. ADC input is always positive.

            Total requirement = transformer + 2 resistors.

Here Vpp must be less than 2 x Vdd and output divider ratio K such
that (Vdd + Vpp/2) x k < Vdd

The smallish downside is that the available measured voltage may be
slightly less than in some other systems - BUT you lose the non
linearity / offset introduced if diodes are used, notionally* need no
clamp diodes etc.

* Here mains noise can appear at reduced V on PIC pin scaled by
transformer ratio. Protecting against this may or may not be a good
idea [tm] but is not a terrible one unless minimum parts count is
absolutely crucial. Clamp Schottkys to each rail may be OK. Small cap
on PIC pin may be all that is needed, noting phase delay and peak V
reduction caused (both of which can be small).

2010\03\20@193759 by M.L.

flavicon
face
On Sat, Mar 20, 2010 at 1:44 PM, Russell McMahon <RemoveMEapptechnzKILLspamspamgmail.com> wrote:
> There seems to be a reluctance to even consider the suggestion I made.
> It may have been commented on an rejected for some good reason but I
> don't recall seeing it.
> Transformer and 2 resistors in basic form.
> Connect one leg to Vdd, other via divider to ground and tap to ADC in.
> Add cap if desired for noise handling.
>
> Track smoothed minimum and maximum to give loaded full voltage excursion.
> Sounds super easy, no body diodes at risk, no diode drops, minimum
> components, full cycle of waveform, ... .
> ?

It's too simple, Russell. This is a common problem for designs
presented on public forums :)

--
Martin K.

2010\03\21@005533 by Steve Smith

flavicon
face
Oh come on guys.....


Use an Avo



Steve

(sorry couldn't resist)

-----Original Message-----
From: piclist-bouncesSTOPspamspamspam_OUTmit.edu [spamBeGonepiclist-bouncesSTOPspamspamEraseMEmit.edu] On Behalf Of
M.L.
Sent: 20 March 2010 23:38
To: Microcontroller discussion list - Public.
Subject: Re: [PIC] measuring 220V mains

On Sat, Mar 20, 2010 at 1:44 PM, Russell McMahon <KILLspamapptechnzspamBeGonespamgmail.com>
wrote:
{Quote hidden}

It's too simple, Russell. This is a common problem for designs
presented on public forums :)

--
Martin K.

2010\03\26@183439 by Dario Greggio

face picon face
[sorry for late reply, I worked on this all, and now it looks ok :)]


Olin Lathrop ha scritto:
> The method I thought you were referring to was finding the negative and
> positive peaks, low pass filtering each of those seperately, then using the
> difference between the two filter outputs to be the line voltage.  This
> can't work now since the processor can't see the negative peaks.

Hmm, wouldn't I measure the heigth of a half-sinewave? wouldn't it just
change my scale? (anyway it don't matter since I'm using the other
approach..)



>> ok, my idea was to make this peak-measurement every 20mS, and average
>> it
>> with the previous one. Resimulated the peak method, and it fits in the
>> 1.2% error indeed.
>
> You are still sampling at 1KHz to find the peaks, right?  The 1.2% error I
> mentioned comes from the 1KHz samples missing the peak by as much as 500uS.

Yes, my (and your) simulation show that.



{Quote hidden}

I did some simulation and also tested it in real. I adapted the scaling
factor, and the readout is stable enough, +-2 units with continous (say,
every 100mSec) readout.
I first stored the 20 samples and every 20th made a pick and average of
the 3 highest; then I chose to store the max 3 on the fly - IMO an
improved approach.



> This is where simulation is probably easier than going thru all the math.
> Try a bunch of cases, each differing only in the phase between the 1KHz
> samples and the input signal.  When using a single peak sample, the results
> will be over a 1.2% range.  If you get a lower variation by averaging the
> top 3 samples, then that sounds like a easy way to get a little less error.
> The simulation can also tell you what the center scale factor is.  However,
> I would worry about the effects of random noise on this method.


It all looks good enough. I'll check the result of random noise on the
field...
I'll possibly also add a filtering capacitor at the PIC's input in next PCB.


{Quote hidden}

:) I know I can probably find it "anywhere" but.. can you show a
pseudocode for this filter like you mention it?
I did average every "cooked" readout (the 20th - peak - value) with the
previous one, to just smooth it. Maybe I can do more :)



{Quote hidden}

thanks for that - in fact it makes perfect sense. It's similar to the
Excel table I had made up in the beginning.


{Quote hidden}

yeah. again, thank you very much :)

Dario

2010\03\27@043149 by Marechiare

picon face
>>> ok, my idea was to make this peak-measurement every 20mS,
>>> and average it with the previous one. Resimulated the peak
>>> method, and it fits in the 1.2% error indeed.
>>
>> You are still sampling at 1KHz to find the peaks, right?  The
>> 1.2% error I mentioned comes from the 1KHz samples missing
>> the peak by as much as 500uS.
>
> Yes, my (and your) simulation show that.


Detecting peaks is not a good idea in my opinion. Much better advice was:


> Trying to detect the peak value and scale that is IMO a bad idea
> because a single brief spike could throw the reading way off.
>
> Taking the average of the magnitude and scaling it would probablly
> be a reasonable option. True RMS is also pretty easy to calculate
> (square the individual values, average them and take the square root
> at the end)

2010\03\27@093738 by Olin Lathrop

face picon face
Marechiare wrote:
> Detecting peaks is not a good idea in my opinion. Much better advice
> was:
>
>> Trying to detect the peak value and scale that is IMO a bad idea
>> because a single brief spike could throw the reading way off.

True, but you can filter first and then detect the peaks.  Each peak is then
the result of a bunch of input samples, and therefore random noise is
attenuated.

I the simulation I posted here some days ago, I passed the raw samples thru
two poles of low pass filtering, each with a filter fraction of 1/4.  That
means random noise is attenuated by 16.

>> Taking the average of the magnitude and scaling it would probablly
>> be a reasonable option. True RMS is also pretty easy to calculate
>> (square the individual values, average them and take the square root
>> at the end)

True RMS requires much more computation.  It all depends on how much
harmonic content you expect the input to have, and how much you care if it
does.  Since he is measuring the power line, the harmonic content should be
quite low such that little is gained from true RMS.


********************************************************************
Embed Inc, Littleton Massachusetts, http://www.embedinc.com/products
(978) 742-9014.  Gold level PIC consultants since 2000.

2010\03\27@094512 by Isaac Marino Bavaresco

flavicon
face
Em 27/3/2010 05:31, Marechiare escreveu:
{Quote hidden}

I agree, once I designed an equipment to protect AC induction motors
from line disturbances. This equipment was intended to substitute
another from a big brand here in Brazil that was not working well. I
used an integrator to measure the RMS value.

After the new design was done I decided to study the circuit of the big
brand equipment and found that it used a peak detector.

I then decided to analyze the power supply in an industry I had access
(the same that would produce the new equipment) and found that it is
common for some circuits to have permanently distorted waveforms. Most
had the peak "shaved off", and when the generators took over, they
produced very high and narrow peaks once every cycle.

The big brand equipment was detecting a too low voltage because the peak
was a few volts below the nominal. It didn't took in account that the
peaks bear very little energy. Somebody forgot that the AC is a sinusoid :)

The problem with the generators was due to their electronic "excitators"
that fed the field only once every cycle, deriving power to the field
from only one phase, half-wave rectified. This caused the field to
receive an initial current inrush and decay through a free-wheeling
diode. Bad design, but worked. The glitch was something like 500V but
just a vertical line on the scope, the sinusoid was somewhat distorted
around it also.

Several multi-meters (including true RMS ones) showed a nominal voltage
in both cases, and for the industrial equipment it was the same as if
the disturbances were not there, but the protection equipment was
measuring an absurdly high value.

The dangerous disturbances that needed to be avoided were too low or too
high (RMS) voltage and loss of one phase.


Best regards,

Isaac

__________________________________________________
Faça ligações para outros computadores com o novo Yahoo! Messenger
http://br.beta.messenger.yahoo.com/

2010\03\27@130917 by Marechiare

picon face
>>> Trying to detect the peak value and scale that is IMO a
>>> bad idea because a single brief spike could throw the
>>> reading way off.
>
> True, but you can filter first and then detect the peaks.
> Each peak is then the result of a bunch of input samples,
> and therefore random noise is attenuated.

Random noise probably would be attenuated indeed, but what if, for
instance, some power SCR/TRIAC-regulated load were present on the
line? Tops of the sine would be heavily suppressed, the filter won't
restore the shape.


> True RMS requires much more computation.

Looks like the statement is not true. RMS approach being a "statistic"
approach does not require that many measurements per sine period as
the peak-detect polling does to achieve the same precision.
Considering the fact that PIC24FJxxx got high-speed 17-bit x 17-bit
hardware multiplier, we may conclude that the total of required
operations per second would be much less.

2010\03\27@162401 by Dario Greggio

face picon face
Marechiare ha scritto:
>>>> Trying to detect the peak value and scale that is IMO a
>>>> bad idea because a single brief spike could throw the
>>>> reading way off.
>> True, but you can filter first and then detect the peaks.
>> Each peak is then the result of a bunch of input samples,
>> and therefore random noise is attenuated.
>
> Random noise probably would be attenuated indeed, but what if, for
> instance, some power SCR/TRIAC-regulated load were present on the
> line? Tops of the sine would be heavily suppressed, the filter won't
> restore the shape.

I put apart the filtering note, waiting for Olin's reply. (I've actually
been reading at the PAS code he wrote for me and I can see the IIR
filter in there - as I suspected he had already shown such a filter... :)

So far, the result is good enough but indeed in real environment there
might be spikes - though it has to be said that I'll need rather "slow"
readouts (< 2-3 secs) and I'm already averaging the output, and the 3 peaks.
Since there will be fans and 1CV pump(s), spikes will indeed be there.


>> True RMS requires much more computation.
>
> Looks like the statement is not true. RMS approach being a "statistic"
> approach does not require that many measurements per sine period as
> the peak-detect polling does to achieve the same precision.

tell me more :)



--

Ciao, Dario
--
Cyberdyne

2010\03\27@163505 by Olin Lathrop

face picon face
Marechiare wrote:
> Random noise probably would be attenuated indeed,

There is nothing probablistic about it.  The math shows quite clearly that
random noise will be attenuated, and by how much.

> but what if, for
> instance, some power SCR/TRIAC-regulated load were present on the
> line? Tops of the sine would be heavily suppressed, the filter won't
> restore the shape.

Actually it will to some extent.  Low pass filtering reduces the harmonics
compared to the fundamental.  Therefore the more filtering, the more the
result will look like a sine.  In the limit, you are left with only the
fundamental component of the distored waveform, which will be a pure sine.
Take a look at the plot I posted a few days ago.  The input to the filter
was a sine with the whole bottom cut off.  The output of the two pole filter
looked a lot more sinusoidal.

Dario is looking at the line voltage, which has very low impedence.  That
means that even with significant harmonics in the current drawn from this
line, the voltage will have little harmonic content.  The approximation that
most of the power is in the fundamental is quite reasonable for many line
voltage measuring purposes.  Remember that Dario only needs 5% accuracy.

>> True RMS requires much more computation.
>
> Looks like the statement is not true. RMS approach being a "statistic"
> approach does not require that many measurements per sine period as
> the peak-detect polling does to achieve the same precision.

Put down the dead fish and do the math instead.  This statement is just
silly superstition, unless of course you can define what a "statistic"
approach is, how RMS is one and low pass filtering with peak picking isn't,
then then show that such statistic approaches require less computation for
the same accuracy.

My recollection from past experience is that RMS requires more samples for
the same accuracy.  However, I don't feel like doing the math or writing a
simulation right now, so I can't substantiate that claim.

> Considering the fact that PIC24FJxxx got high-speed 17-bit x 17-bit
> hardware multiplier, we may conclude that the total of required
> operations per second would be much less.

Yes, the multiplies are the same cost as adds, but you conveniently left out
the square root at the end.  RMS would require one multiply and one add per
sample.  The two poles of low pass filtering I showed used 4 adds and 2
multiplies per sample.  A good chunk of the 80 extra operations per line
cycle will be offset by the square root operation of RMS.  However, both
methods will take only a tiny fraction of processor cycles, and Dario made
it clear that there were plenty of cycles available, so there is no real
distinction here.


********************************************************************
Embed Inc, Littleton Massachusetts, http://www.embedinc.com/products
(978) 742-9014.  Gold level PIC consultants since 2000.

2010\03\27@180526 by Dario Greggio

face picon face
Olin Lathrop ha scritto:
> Take a look at the plot I posted a few days ago.  The input to the filter
> was a sine with the whole bottom cut off.  The output of the two pole filter
> looked a lot more sinusoidal.


going to put it in there, then :)


> Dario is looking at the line voltage, which has very low impedence.  That
> means that even with significant harmonics in the current drawn from this
> line, the voltage will have little harmonic content.  The approximation that
> most of the power is in the fundamental is quite reasonable for many line
> voltage measuring purposes.  Remember that Dario only needs 5% accuracy.

More realistically I may want some +-1% (218..222 out of 220) but I seem
to be pretty close at the moment.


> Yes, the multiplies are the same cost as adds, but you conveniently left out
> the square root at the end.  RMS would require one multiply and one add per
> sample.  The two poles of low pass filtering I showed used 4 adds and 2
> multiplies per sample.  A good chunk of the 80 extra operations per line
> cycle will be offset by the square root operation of RMS.  However, both
> methods will take only a tiny fraction of processor cycles, and Dario made
> it clear that there were plenty of cycles available, so there is no real
> distinction here.


Now I'm wondering how can I save some cycles, i.e. I need one readout
out of 1-2 seconds, so am wondering if I still have to sample every 1mS
and do the math for IIR and peak-detect every time...
I may wish to do it only for one or two full sine every 1 second...
maybe: what do you think about this?


--

Ciao, Dario
--
Cyberdyne

2010\03\27@182937 by Olin Lathrop

face picon face
Dario Greggio wrote:
> Now I'm wondering how can I save some cycles, i.e. I need one readout
> out of 1-2 seconds, so am wondering if I still have to sample every
> 1mS and do the math for IIR and peak-detect every time...

You do if you want good noise immunity.

Take a look at the cycles though.  Compared to a 24F at anything near full
speed, the cycles used by this is a tiny fraction.  Let's say for example
the PIC is running at 30MHz instruction rate.  That's 30K instructions per
1mS sample.  1% of that would be 300 instruction, which is way more than the
filtering and peak detection would take.  Are you really so tight on CPU
cycles that a fraction of 1% makes a difference?


********************************************************************
Embed Inc, Littleton Massachusetts, http://www.embedinc.com/products
(978) 742-9014.  Gold level PIC consultants since 2000.

2010\03\27@184438 by Dario Greggio

face picon face
Olin Lathrop ha scritto:
> You do if you want good noise immunity.

ok


> Take a look at the cycles though.  Compared to a 24F at anything near full
> speed, the cycles used by this is a tiny fraction.  Let's say for example
> the PIC is running at 30MHz instruction rate.  That's 30K instructions per
> 1mS sample.  1% of that would be 300 instruction, which is way more than the
> filtering and peak detection would take.  Are you really so tight on CPU
> cycles that a fraction of 1% makes a difference?

I have some other interrupts going on - I posted a thread @ forum but
was going to replicate it in here. Basically I have an underlying
Ethernet or USB app going on (or even none of them - simplest case), a
text LCD and some simple keys; and I have dimmer going on (zero-crossing
plus 100uS steps for triggering the Triac), and a FM-out which is
basically a 1000-2000 Hz sine-wave that I plan on doing using a HW PWM
and a 16 step sine-table. This calls for a total of:

1KHz IRQ for RMS
10KHz IRQ for dimmer
32KHz IRQ for the 16step sine-wave @2KHz

Should be definitely doable, but of course I want to do it "best I can" :)

2010\03\27@185248 by Olin Lathrop

face picon face
Dario Greggio wrote:
> 1KHz IRQ for RMS
> 10KHz IRQ for dimmer
> 32KHz IRQ for the 16step sine-wave @2KHz
>
> Should be definitely doable, but of course I want to do it "best I
> can" :)

Remember that the PIC 24 has selectable interrupt priorities.  Optimize the
code carefully for each of the fast interrupts and make their priorities
higher than anything else.  Make the line sampling interrupt third.  It will
have a little jitter, but that shouldn't be too much.


********************************************************************
Embed Inc, Littleton Massachusetts, http://www.embedinc.com/products
(978) 742-9014.  Gold level PIC consultants since 2000.

2010\03\27@185900 by Dario Greggio

face picon face
Olin Lathrop ha scritto:
> Remember that the PIC 24 has selectable interrupt priorities.  Optimize the
> code carefully for each of the fast interrupts and make their priorities
> higher than anything else.  Make the line sampling interrupt third.  It will
> have a little jitter, but that shouldn't be too much.


Yeah, thank you, I'm studying that. I also discovered the "shadow"
attribute which is available to make one ISR quicker.
Will go in depth on this tomorrow.


--

Ciao, Dario
--
Cyberdyne

2010\03\27@195756 by Marechiare

picon face
>> Random noise probably would be attenuated indeed,
>
> There is nothing probablistic about it.  The math shows quite
> clearly that random noise will be attenuated, and by how much.

Since "math" word mentioned, the pathetic statement would look much
better if  "theoretically" word were used: "The math shows quite
clearly that random noise will THEORETICALLY be attenuated, and by how
much."

In real life (OP mentioned pumps) everything could happen, say, a
drunken technician would solder something wrong or stupid non-relevant
math model would have been chosen. That's why I've used "probably"
word.


>> but what if, for instance, some power SCR/TRIAC-regulated
>> load were present on the line? Tops of the sine would be
>> heavily suppressed, the filter won't restore the shape.
>
> Actually it will to some extent.  Low pass filtering reduces the
> harmonics compared to the fundamental.  Therefore the more
> filtering, the more the result will look like a sine.  In the limit,
> you are left with only the fundamental component of the distored
> waveform, which will be a pure sine.

The more filtering, the more the result will look like a sine, the
less useful it could be for our analysis. We need to protect the pump.
Among other main factors that kill the device is "how much" real
waveform differs from that fundamental component, and not only on top
of the wave but also throughout the whole wave period.

The mentioned RMS approach could easily be extended to calculate the
deviation from the  fundamental component since the amplitude of the
fundamental component could be predicted based on its previous values.
.

> Take a look at the plot I posted a few days ago.  The input to
> the filter was a sine with the whole bottom cut off.  The output
> of the two pole filter looked a lot more sinusoidal.
>
> Dario is looking at the line voltage, which has very low impedence.

You were told many times "impedence" should be impedAnce. Why not the
spelling to get fixed already. Besides as you might have known
everything is trade-off including the mentioned line impedance. It may
not be very low. A 2 kWatt motor on 2 Ohm 220 V line would cause 20 V
drop that not necessarily be of a sine waveform due to its SCR/TRIAC
regulator. Copper cable is expensive, so 2 Ohm could be quite
realistic.


> That means that even with significant harmonics in the current
> drawn from this line, the voltage will have little harmonic content.
> The approximation that most of the power is in the fundamental
> is quite reasonable for many line voltage measuring purposes.

No, it often could not be reasonable to suggest the waveform is sine
pure enough.


> Remember that Dario only needs 5% accuracy.

I do.


>>> True RMS requires much more computation.
>>
>> Looks like the statement is not true. RMS approach being a
>> "statistic" approach does not require that many measurements
>> per sine period as the peak-detect polling does to achieve the
>> same precision.
>
> Put down the dead fish and do the math instead.  This statement
> is just silly superstition,

Your style casts serious doubts on your ability to stay concentrated
on EE-related problems.


> unless of course you can define what a "statistic" approach is,
> how RMS is one and low pass filtering with peak picking isn't,
> then then show that such statistic approaches require less
> computation for the same accuracy.

Basically, as far as I understand, your low pass filtering takes into
the filtering only a subset of all the measurements. RMS takes them
all. That's why, since the number of points is considerably greater,
then at the same quantization period it yields greater accuracy.
That's a long story to prove it strictly. You may wish to do it on
your own.


>> Considering the fact that PIC24FJxxx got high-speed
>> 17-bit x 17-bit hardware multiplier, we may conclude
>> that the total of required operations per second would
>> be much less.
>
> Yes, the multiplies are the same cost as adds, but you
> conveniently left out the square root at the end.

A bit of creativity might tell one that we may compare the result to
square of upper and bottom values thus eliminating the need to take
the square root at the end.


> RMS would require one multiply and one add per
> sample.  The two poles of low pass filtering I showed
> used 4 adds and 2 multiplies per sample.

Let it be so.


> A good chunk of the 80 extra operations per line
> cycle will be offset by the square root operation of RMS.

I am not getting what you are talking about, first we don't have to
calculate square root at all. And if we had to figure out square root,
it would take much less operations:

- Keep last average of individual square values and corresponding square root;
- Calculate the difference between new average and that last average
of individual square values.
- Divide the difference by 2 (do you remember what's the derivative of
square function?)
- Increment last square root by the result;
- Square the incremented value and compare it to that new average of
individual square values.
- If equal then it is sought-for square root, if not repeat with the
last pair of values as last average and its square.

In two, I believe, loops you'll get the square root.

Regards.

2010\03\27@202552 by Marechiare

picon face
> - Keep last average of individual square values and
> corresponding square root;
> - Calculate the difference between new average and
> that last average of individual square values.
> - Divide the difference by 2 (do you remember what's
> the derivative of square function?)

Typo, sorry. It should be "Divide the difference by 2 multiplied by
old square root";

For example:
- old average of individual square values = 40000
- old square root 200
- new average of individual square values = 41000

41000-40000=1000
1000/(2*200)=2.5
202.5*202.5=41006.25

41006.25 is almost equal to 41000
Thus 202.5 should be taken as square root of 41000
New voltage 202.5 has been found in one cycle.

2010\03\28@100051 by Olin Lathrop

face picon face
Marechiare wrote:
> Since "math" word mentioned, the pathetic statement would look much
> better if  "theoretically" word were used: "The math shows quite
> clearly that random noise will THEORETICALLY be attenuated, and by how
> much."
>
> In real life (OP mentioned pumps) everything could happen, say, a
> drunken technician would solder something wrong or stupid non-relevant
> math model would have been chosen. That's why I've used "probably"
> word.

Yes, noise can happen, but this is all before the aforementioned math is
applied.  Since this math is performed digitally in a deterministic
processor, it is totally predictable.

> The more filtering, the more the result will look like a sine,

Yes.

> the less useful it could be for our analysis.

More waving of dead fish.

> The mentioned RMS approach could easily be extended to calculate the
> deviation from the  fundamental component since the amplitude of the
> fundamental component could be predicted based on its previous values.

I have no real objection to doing RMS, although I would like it better if
the whole waveform were available to the processor and I would certainly
want some low pass filtering together with the RMS calculations.  You seem
to be skipping over that part.

My objection to your posts is not about RMS as a method, but your
unscientific way of dismissing other methods.  This includes things like
saying something is a "statistics" approach, which is supposed to make it
inherently better (or was that worse?) than some other approach, and
unfounded statements like a sine makes things less useful for some reason.

> You were told many times "impedence" should be impedAnce. Why not the
> spelling to get fixed already.

Eyell trie too remember.  However unless you write perfectly, it's probably
not a good idea to get into a food fight about writing correct English.

> Basically, as far as I understand, your low pass filtering takes into
> the filtering only a subset of all the measurements. RMS takes them
> all. That's why, since the number of points is considerably greater,
> then at the same quantization period it yields greater accuracy.

It's not as simple as that.  First, low pass filtering does take into
account many samples, with the most recent ones weighted more heavily.  In
general it is a weighted average.  This can be seen two ways.  One way is to
follow the contribution of a single sample into the filter and as it decays
away.  Another is to think of the filter realized as a convolution.  The
filter kernel function is then the weighting function of the weighted
average.  These are all just different ways of looking at the same thing.

Second, both methods have to apply filtering to make use of multiple
samples.  The instantaneous squared values don't tell you much useful on
their own.  These have to be low pass filtered to be useful.  That's what
the M in RMS implies.  Whatever filtering you chose can just as well be
applied to either method.

> A bit of creativity might tell one that we may compare the result to
> square of upper and bottom values thus eliminating the need to take
> the square root at the end.

I thought Dario wanted a readout of line voltage, so a square root needs to
be performed at least every time the display is updated.

{Quote hidden}

That's a long winded way of saying to calculate the square root iteratively
each sample.  Yes, that's probably a good approach.

Again, I'm not against RMS, only how you were dismissing other methods.


********************************************************************
Embed Inc, Littleton Massachusetts, http://www.embedinc.com/products
(978) 742-9014.  Gold level PIC consultants since 2000.

2010\03\29@005701 by Russell McMahon

face picon face
>> True RMS requires much more computation.

> Looks like the statement is not true. RMS approach being a "statistic"
> approach does not require that many measurements per sine period as
> the peak-detect polling does to achieve the same precision.
> Considering the fact that PIC24FJxxx got high-speed 17-bit x 17-bit
> hardware multiplier, we may conclude that the total of required
> operations per second would be much less.

Be aware that RMS computation, especially over shortish periods (seconds
rather than minutes) really wants integral cycles. The same real world
things that may cause problems with peak detect MIGHT cause some problems
with whole cycle detect.

Also, once you add in SCR/Triac control then the RMS sampling needs to be
fast enough to not alias the introduced harmonics.

Voltage rate of rise time from zero crossing was suggested. This may have
problems if zero crossing is uncertain. BUT "maximum rate of voltage change"
will occur symmetrically around  zero crossing and may be a quite productive
system. eg maintain N sample memories in FIFO. Determine rate of voltage
change between adjacent samples and store N samples. Push new value and
calculate slope of FIFO. Could be delta V between 1st and last or use all
samples in FIFO by weighting samples in some way. Whatever.
Store maximum value. When delta V goes negative that half cycle is ended.
Average N maxima - maybe with the filter mentioned previously* or whatever.
  (*Vo(n+1) = Vo(n) x (k-1)/k + Vin(n+1)/k).

Vsine = k.delta.V.

May even work :-).

                Russell

2010\03\29@065915 by Marechiare

picon face
>> - If equal then it is sought-for square root, if not
>> repeat with the last pair of values as last average
>> and its square.
>
> That's a long winded way of saying to calculate the
> square root iteratively each sample.  Yes, that's
> probably a good approach.

No, that was an attempt to say that there is a method that takes much
less than 80 operations. I could imagine tons of methods "to calculate
the square root iteratively each sample" in the declared 80+
operations.


> Yes, that's probably a good approach.

Nothing probabilistic here, That's just a good approach. Don't you
mind we will refer to this method (aren't we on PicList?) as "Newton's
method"?  :-) The guy did great job.

2010\03\29@081717 by Dario Greggio

face picon face
Russell McMahon ha scritto:

>
> May even work :-).


thanks Russell :)

2010\03\31@001759 by Marechiare

picon face
> Voltage rate of rise time from zero crossing was suggested.
> This may have problems if zero crossing is uncertain.

Seems it won't work with back-up UPS. Cheap UPS may approximate sine
in unexpected way.

2010\03\31@022055 by Marechiare

picon face
> I have no real objection to doing RMS, although I would
> like it better if the whole waveform were available to the
> processor and I would certainly want some low pass
> filtering together with the RMS calculations.  You seem
> to be skipping over that part.

It looks like the 50Hz transformer does low pass filtering quite well
on its own if we are talking about 1000 samples/s.


> My objection to your posts is not about RMS as a
> method, but your unscientific way of dismissing other
> methods.  This includes things like saying something
> is a "statistics" approach, which is supposed to make it
> inherently better (or was that worse?) than some other
> approach,

Yes, I would agree I should not use "better" word for the reason.


> and unfounded statements like a sine makes things less
> useful for some reason.

Yes, statements should be founded, but I just thought it was more or
less obvious as you wrote "In the limit, you are left with only the
fundamental component of the distorted waveform, which will be a pure
sine."

Imagine the device to be connected to a supply of very distorted sine
(say square waveform of the back-up UPS). Would the device care only
about what was the fundamental component behind the square waveform? I
believe, in this case it may fail at different "fundamental component
behind" amplitude than it would fail if it were real sine with the
amplitude.


{Quote hidden}

Yes, "low pass filtering does take into account many samples" but
still since you are judging about the sine effectively only on the
subset of the very top of it, you are bound to very high frequency of
getting samples.

Your idea to "low pass filter" the wave is fine in my opinion, it just
needs to be applied over the entire wave. I would adjust the idea
somewhat:
- do not figure out peak values
- assume you know the amplitude of fundamental component behind the wave;
- get samples and "low-pass" them. Add "virtual" points between
samples. For each point (including samples) calculate the difference
between the point and the fundamental component.
- get average of that differences for each 1/4 of the wave.
- based on these 4 values adjust amplitude/phase/frequency of the
imaginary fundamental component to be used in the next cycle;

Output values are:
- the amplitude of the imaginary fundamental component;
- RMS of that differences calculated along the cycle;

The higher RMS - the narrower should be the voltage operating range.


> Second, both methods have to apply filtering to
> make use of multiple samples. The instantaneous
> squared values don't tell you much useful on their
> own.  These have to be low pass filtered to be useful.
> That's what the M in RMS implies.

Total of instantaneous squared values for the cycle IS low pass
filtered by the very process of addition the values, isn't it? High
frequency distortions are unlikely after the transformer, I think. And
even if they are we would expect some rise in the total of squared
values - and this correspond to our idea to narrow the voltage
operating range in the presence of distortions.

2010\03\31@090113 by Olin Lathrop

face picon face
Marechiare wrote:
> Imagine the device to be connected to a supply of very distorted sine
> (say square waveform of the back-up UPS).

No, since one of the assumptions for the peak picking method is that the
voltage waveform is not significantly distorted.  If the system has to deal
with distortion, then doing the full RMS calculation is pretty much required
to get the "real" voltage.

> - assume you know the amplitude of fundamental component behind the
> wave

Bad assumption, since that's basically what he's trying to measure.

> Total of instantaneous squared values for the cycle IS low pass
> filtered by the very process of addition the values, isn't it?

No, that is a integral.  In the long run the AC components will sum to 0 and
you will be left with the integral of the DC component, which is a
infinitely increasing value for any non-zero DC offset.

> High frequency distortions are unlikely after the transformer,
> I think.

But wait, your earlier argument was exactly the opposite: "Imagine the
device to be connected to a supply of very distorted sine".  You can't have
it both ways.  In the end, only Dario can answer whether the mostly sine
approximation is valid in his case.


********************************************************************
Embed Inc, Littleton Massachusetts, http://www.embedinc.com/products
(978) 742-9014.  Gold level PIC consultants since 2000.

2010\03\31@122004 by Marechiare

picon face
>> Imagine the device to be connected to a supply of very
>> distorted sine (say square waveform of the back-up UPS).
>
> No, since one of the assumptions for the peak picking
> method is that the voltage waveform is not significantly
> distorted.

Have you noticed that Dario said about a pump to be monitored,
Normally this kind of rugged devices are expected to deal with bad
voltage waveform.


>> - assume you know the amplitude of fundamental component
>> behind the wave
>
> Bad assumption, since that's basically what he's trying to measure.

Have you noticed the last step in the iterative algorithm? The
statement you quoted was first step of the algorithm. The last step
was:

"- based on these 4 values adjust amplitude/phase/frequency of the
imaginary fundamental component to be used in the next cycle;"

In a few cycles the amplitude will be adjusted close to the "right"
value. Your filter coefficients seem to get few cycles to set up too.


>> Total of instantaneous squared values for the cycle IS
>> low pass filtered by the very process of addition the
>> values, isn't it?
>
> No, that is a integral. In the long run the AC components
> will sum to 0 and you will be left with the integral of the
> DC component, which is a infinitely increasing value for
> any non-zero DC offset.

Have you noticed "squared" word in the statement?
Under "squared" I meant the value to multiply the by itself. Did you
use some other math terminology in the school? The squared AC
component values are always positive, aren't you getting it? How is
you rant about integrating the AC components related to integrating
squared AC component values?


>> High frequency distortions are unlikely after the
>> transformer, I think.
>
> But wait, your earlier argument was exactly the opposite:
> "Imagine the device to be connected to a supply of very
> distorted sine".  You can't have it both ways.

Have you noticed "High frequency" phrase in the statement? The
waveform of the sine after the transformer could be heavily distorted,
but still there can be very little high frequency noise. I talked
about high frequency distortions because of your concern that low pass
filtering should be applied even for RMS method.


'[PIC] measuring 220V mains'
2010\04\01@212242 by Russell McMahon
face picon face
OK. Time to stop messing around here.
Who would have thought it would take so much effort to get this right?

Try: Apply AC signal to a resistor of adequately known electrothermal
characteristic.
Place in thermal contact with a thermistor of adequately known characteristics.
Calibrate combination for voltage & ambient temperature map.
Measure thermistor resistance & ambient temperature.
QED.
________________

OK. That should start it all off again ... :-).
Lots of fish-hooks. Too many parts. What does adequately and adequately mean?
How does ambient affect main and ambient sensor and ...?
How ... ?
:-)

RM

2010\04\02@074715 by Olin Lathrop

face picon face
Russell McMahon wrote:
> Try: Apply AC signal to a resistor of adequately known electrothermal
> characteristic.
> Place in thermal contact with a thermistor of adequately known
> characteristics. Calibrate combination for voltage & ambient
> temperature map.
> Measure thermistor resistance & ambient temperature.

HP actually made a RF power meter based on this principle.  I remember
hearing about it in 1980 when I worked for HP.

2010\04\02@080915 by Russell McMahon

face picon face
>> Try: Apply AC signal to a resistor of adequately known electrothermal
>> characteristic. Place in thermal contact with a thermistor ...

> HP actually made a RF power meter based on this principle.

If HP did it I must be doing something right then :-).





                Russell

More... (looser matching)
- Last day of these posts
- In 2010 , 2011 only
- Today
- New search...