Multiple readadc10 commands in a row

hax

New Member
Hi all,

For a crude energy monitor design, I'd like to capture half of a sine wave by using the readadc10 command, to measure AC voltage and AC current at 50 hz.

The voltage would be read with a single diode rectified transformer, with no capacitor, say a 20v transformer with a resistor divider to get 0 to 5v.

The current would be read with a LEM current sensor.


How quickly could the readadc10 command work?

I was thinking that I could store say hopefully 20 data points of the half sine wave. That would be one sample every 500uS. Is this realistic?

What picaxe has the fastest readadc10 ability?

The "data acquisition" could start at any random point of the sine wave. And after sampling say 40 data points, the software would choose the point at which the voltage is the highest (which would be the peak part of the sine wave), and the corresponding current value at that point in time could be used to calculate the watts. Is this asking too much of the picaxe?
 

oracacle

Senior Member
It should take too long, think every 500us would be an issue though.
You maybe better off doing some signal conditioning first, either a peak detector of envelope follower should work. You maybe be able to use them PICAXE comparators but I don't them well enough to advice
Also UK mains AC is 50hz so you are only going to get a peak every 20000us, that's 40 readings in every wave.
 

erco

Senior Member
My gut tells me that a Picaxe is too slow to sample that fast with ADC10. You could write a test program to loop through a few thousand consecutive ADC10s and time it by hand and djvide for a quick check. Sounds like a perfect opportunity ton use caps & inductors to find voltage & current peaks & zero crossings. Analog. Baby!
 
Last edited:

hippy

Technical Support
Staff member
How quickly could the readadc10 command work?
Testing on a 20X2 shows ten consecutive READADC10 take about 780us, so around 80us each at 64MHz.

What picaxe has the fastest readadc10 ability?
I would guess the 20X2 is the best choice as it allows 64MHz operation without an external crystal.

After sampling say 40 data points, the software would choose the point at which the voltage is the highest (which would be the peak part of the sine wave), and the corresponding current value at that point in time could be used to calculate the watts. Is this asking too much of the picaxe?
The PICAXE should easily be capable of this. You don't really need to sample, can run for a couple of mains cycles and determine what the highest reading was. This takes about 50ms to read 200 samples, a sample every 250us ...
Code:
#Picaxe 20X2

Symbol ADC_PIN = 9 ; C.1 / ADC9

Symbol sample  = w0
Symbol maximum = w1
Symbol counter = w2

#Define Highest(lhs, rhs) lhs Min rhs

SetFreq M64
Do
  maximum = 0
  counter = 200
  Do
    ReadAdc10 ADC_PIN, sample
    maximum = Highest(maximum, sample)
    counter = counter - 1
  Loop Until counter = 0
  ...
Loop
The beauty of this is it doesn't matter how long each sample loop takes so long as you run it for long enough to have read the maximum or thereabouts.

The only thing speed does is give you more responsiveness and a better chance of reading the peak or close to it with a shorter loop time.

So you could even use an 08M2.
 
  • Like
Reactions: hax

hippy

Technical Support
Staff member
The voltage would be read with a single diode rectified transformer, with no capacitor, say a 20v transformer with a resistor divider to get 0 to 5v.
I would recommend using a multi-turn pot or a multi-turn pot plus R divider. At least for the prototype and it will probably be useful for calibration in production if one were heading that way.

This way you can easily tweak the pot to suit whatever mathematical constants make the PICAXE maths easier when it comes to calculating the RMS or peak voltage, Watts etc -- It's much easier to divide by powers of two and tweak the input to suit that than have to figure out how to do complicated maths without losing accuracy or resolution.
 

Flenser

Senior Member
I just tested the cmd "READADC10 B.2, W1" on an 18M2 and it took 721 instructions at all clock frequencies from 250kHz - 32MHz:
4MHz: 721us
8MHz: 360.5us
16MHz: 180.25us
32MHz: 90.125us

On a 20X2 the "READADC10 B.2, W1" took 1210 instructions at all clock frequencies from 250kHz - 64MHz
4MHz: 1210us
8MHz: 605us
16MHz: 302.5us
32MHz: 151.25us
64MHz: 75.625us

You should not take these measurements as exact values. Because of the way PICAXE programs are compressed the measured duration of any command does vary by a few percent as code is added or removed from before its position in the program (and making my 20X2 measurement at 64MHz consistent with Hippy's).
This doesn't take into account the overhead for your program to save the 20 readings.
 
Last edited:

hippy

Technical Support
Staff member
I just tested the cmd "READADC10 B.2, W1" on an 18M2 and it took 721 instructions at all clock frequencies from 250kHz - 32MHz:
On a 20X2 the "READADC10 B.2, W1" took 1210 instructions at all clock frequencies from 250kHz - 64MHz

You should not take these measurements as exact values.
Thanks for testing and you are right to note it's not an exact science, particularly as alignment in memory can have an affect. and it's hard to have any control over that.

I was actually expecting the M2's to be slower than the X2 but I guess it comes down to exactly what configuration each does in preparing its hardware for a read. My 28X2 tests before trying a 20X2 were comparable.

I guess the bottom line is an M2 at 32MHz compares similarly with a 20X2 at 64MHz.
 

inglewoodpete

Senior Member
I was actually expecting the M2's to be slower than the X2 but I guess it comes down to exactly what configuration each does in preparing its hardware for a read. My 28X2 tests before trying a 20X2 were comparable.
The difference in speed is probably associated with the token size difference in M2s (5-bits) vs. X2s (6-bits).
 

AllyCat

Senior Member
Hi,

I think the OP's target is probably possible, but there are a number of potential "gotchas":

Firstly, I thought that the ADC used its own clock (divider), so its execution time didn't necessarily "track" directly with SETFREQ, but perhaps I'm mistaken?

Secondly, If you're storing a "list" of values, then you'd normally use @BPTRINC, but that can store only a Byte (8 bits), not a Word. Also, storing the two extra bits from a READADC10, into an additional byte might be considered rather inefficient.

Generally, the "overhead" associated in using a program loop is quite high, so really "fast"code normally employs linear code, e.g. READADC pin , w0 : READADC pin , w1 : ..... etc.. , (which will soon run out of Words, even in an X2), or better, @BPTRINC and then performs a "Post Processing" activity.

It depends upon the nature of the "sine wave", but mains "Power Meters" normally measure both Voltage and Current "dynamically", because they might not be in phase, unless it's a purely resistive load (i.e. a Unity Power Factor or Zero Phase Angle). So personally, I would probably "interleave" Voltage and Current measurements with a block of linear code. 8-bit (i.e. byte) measurements may be sufficient, because you could combine two (or more) consecutive measurements to interpolate a more accurate "peak" of a (or the) sine wave(s).

Finally, for the hardware, I would probably NOT use a series diode (or any capacitors), but a (10k) series resistor to the ADC input pin. Then a Reverse diode to ground (preferably Schottky) to prevent the pin being pulled too far negative. Possibly the on-chip "electrostatic protection diode" could perform that function, but there were reports that current flowing in this (substrate) diode can upset the accuracy of the ADC converter. See the ("obsolete") Enhanced Programming Interface in User Manual 1.

Cheers, Alan.
 

hippy

Technical Support
Staff member
It depends upon the nature of the "sine wave", but mains "Power Meters" normally measure both Voltage and Current "dynamically", because they might not be in phase, unless it's a purely resistive load (i.e. a Unity Power Factor or Zero Phase Angle). So personally, I would probably "interleave" Voltage and Current measurements with a block of linear code. 8-bit (i.e. byte) measurements may be sufficient, because you could combine two (or more) consecutive measurements to interpolate a more accurate "peak" of a (or the) sine wave(s).
Good point. My suggested solution was in respect of determining peak voltage as per the initial question.

As to what's appropriate to create a "crude energy monitor" that's beyond my knowledge and experience. Determining peaks of voltage and current over a few mains cycles then applying some fudge factor calculation may be enough, but it may need to be more involved than that.

If sampling then processing voltage and current, beyond having to read twice as much, one has to store that data and have a place to store it, any tricks used to maximise storage will impact on sample rate.

For the hardware, I would probably NOT use a series diode
I would use that because it guarantees the substrate won't be pulled negative, but I'm no expert on that.
 

AllyCat

Senior Member
Hi,
I would use that because it guarantees the substrate won't be pulled negative, ...
Yes, I must admit that I originally considered the "Enhanced Serial Download Circuit" (Manual 1 page 45) to be over-complex and would simply use a forward diode. But here, we are attempting to make an analogue measurement, and all diodes do have a significant (temperature-dependent) forward voltage drop, and some stray (parallel) capacitance:

Perhaps simply adding 600 mV to the (calculated) ADC value will be "good enough", but some caution may be required with the location (and values) of the resistors when combining a diode with a Potential Divider. The advantage of a negative "shunt" diode is that it doesn't influence any positive voltage that is being measured.

Cheers, Alan.
 

hax

New Member
Thankyou so much for your replies.

I think an 8 bit measurement should suffice. I'm aware that the system won't measure reactive power, but for my purposes that should be ok.

To explain a little more, I'm using this to measure the consumption in each of the 3 phases in my house, one of the phases has a solar system installed, amongst other regular loads, sometimes it is exporting to grid, other times it's not. So I need to sum all 3 phases to find out if I'm net exporting.

This info can then be used to switch the hot water heater on if there is enough sunlight.

Sounds like 3x 08M2 chips could be used. One for each phase, with a pwm output on each, reporting an 8 bit power measurement, with another pin signalling whether the phase is exporting or importing power from the grid. Or one 20x2 that does the lot.
 

tmfkam

Senior Member
Hi all,

For a crude energy monitor design, I'd like to capture half of a sine wave by using the readadc10 command, to measure AC voltage and AC current at 50 hz.

The voltage would be read with a single diode rectified transformer, with no capacitor, say a 20v transformer with a resistor divider to get 0 to 5v.
I used a very similar approach in my Grid Frequency Meter project, listed somewhere on this forum. I alternately read Voltage and frequency. For a close approximation it worked really well.
 

hax

New Member
That AD7755 looks interesting. Plenty available on eBay still. It was interesting to read that it has a frequency output plus a pin that goes high for out of phase current (exporting solar). That's basically what I was "inventing" with the 08m2 idea. Well it's time to heat up the soldering iron and test some code.

Hippy, I'll have to look at your code example more closely. I can't follow it just yet.

One other thought is that I might not need to measure the analog value of the voltage. I can just assume it's somewhere around 240v. All I need to know is whether the phase angle between the voltage and the current is more than 90 degrees. So I could set up the AC voltage input as just a digital input. This would save some processing time. I'd just look for the current peak value from the LEM current sensor.

Thanks again for your replies.
 

AllyCat

Senior Member
Hi,

Yes, for Export/Import detection you need only the sign of the Current and Voltage signals, which could be done with two digital inputs (e.g. a zero-crossing trigger and a polarity detector).

The timing of Zero-crossing is potentially much more accurate than of a "peak" voltage/current signal, but is not directly measurable with "sampled" signals. However, even a full analogue power measurement including Power Factor (phase) correction shouldn't be too difficult if you assume a sinusoidal line frequency (i.e. pure 50 / 60 Hz). That's a reasonable assumption for an Immersion Heater and Motor-based systems, etc., but probably not electronics based on (bridge) rectification circuitry, etc.. A pair of (matched) R+C Low-Pass filters could be used to "de-spike" the waveforms, if necessary (without upsetting the relative phase shifts).

For a pure sine-wave, 3 samples per cycle is "sufficient", but 12 samples (i.e. every 30 degrees) make the calculations much easier (and still with greater than a 1ms sampling period). Then, the peak sample value (voltage or current) will be within 2% of the true peak (strictly +0/-4%) and there always should be a sample between zero-crossing and the half-peak (i.e. 50%) value. Thus you could calculate the times of crossing the 50% levels (which are nominally 120 degrees apart) by interpolating between the values immediately above and below this threshold. Sine and Cosine are easily calculated by (any) PICaxe by using a lookup table method.

Then, the main design choice becomes how to achieve mains isolation: Capacitor-Coupling, Magnetic (e.g. Transformer of Hall Effect) or Optical (e.g. Opto-Isolator or LED+LDR), etc..

Cheers, Alan.
 
Last edited:

papaof2

Senior Member
"Pure sine wave" might not apply to your local power provider :-( The waveform from the pure sine wave inverter on my solar backup system is much cleaner than the power provided by the local power co-op - and I have the 'scope pictures to confirm that.
Would the difference affect the sampling? Possibly only if the sampling hit at a "bad" point on every cycle? Co-op power first, then the PSW inverter with a 440 watt load. Sorry for the image quality but this old body no longer does well with long handheld exposures.

co-op-AC-sm.jpg

psw-inv-440W.jpg
 

hax

New Member
OK I have ordered a few AD7755 chips and will be going with a circuit similar to Jeremy Harris' one. It's just so precise compared to trying to roll my own. I love the idea of keeping every single joule that I produce, and not exporting any more than I have to.

I have 3 phases to monitor, so the circuit and code will be a bit different to Jeremy's. I will have 3 channels of pulses to count (up to 1.5KHZ in my case, which corresponds to a 15KW load per phase), but when exporting solar (which is only on one of the phases), the catch is that one of those pulse trains will have to subtract from the other two (at up to 10kw or 1KHZ). Fortunately, the AD7755 has a pin that goes high when the voltage and current is out of phase (exporting) which can be used to signal the picaxe to start subtracting.

I wonder if anyone can get me started on the code, as I don't think the count command will work here. Are there any tricks to do this elegantly? I guess an interrupt should occur as soon as any counter is sensed. But I'm not sure if it will be fast enough. I'll go with the 20X2 for sure.
 

hippy

Technical Support
Staff member
I don't think the count command will work here. Are there any tricks to do this elegantly?
By measuring the high or low period of the pulse, or both, one can calculate what the frequency is.

f = count / time

f = 1 / (Thigh + Tlow)
 

hax

New Member
By measuring the high or low period of the pulse, or both, one can calculate what the frequency is.

f = count / time

f = 1 / (Thigh + Tlow)

Thanks Hippy, That will be enough for an approximation to get something going, and will be better than my original rough idea in the first post.

The holy grail would be for the picaxe to monitor all 3 pins for edge transitions, sum or subtract as required, till 3600 pulses are recorded, then turn on the triac, then wait till 3600 pulses are depleted, then turn off triac, repeat.

If the picaxe can't do it, a solution could be to run each pulse channel through a dual BCD counter, then poll the counters as fast as possible. Hmm I've got a month or so to ponder this.
 

hippy

Technical Support
Staff member
The holy grail would be for the picaxe to monitor all 3 pins for edge transitions, sum or subtract as required, till 3600 pulses are recorded, then turn on the triac, then wait till 3600 pulses are depleted, then turn off triac, repeat.

If the picaxe can't do it, a solution could be to run each pulse channel through a dual BCD counter, then poll the counters as fast as possible. Hmm I've got a month or so to ponder this.
I am not sure which pulses you would be counting, in what time frame, why 3600, or what triac you are controlling. It may help to detail the exact theory of operation of what you are wanting to do.

Some PICAXE have internal hardware timers which can be used as 16-bit counters so there should be no need to add external counters to detect how many pulses there have been.
 

hax

New Member
Ok I'll try to explain more clearly. The aim is to use every joule of my excess solar production by storing the energy in a large hot water heater, while at the same time not exporting any power. This maximises the financial gain, as the tariff for importing is much higher than exporting power.

The problem comes when much of the time the solar system might be only producing say 2kw. If the 3.6kw element was turned on, the balance of 1.6kw would be purchased from the grid. We don't want to purchase any power from the grid so we have to dynamically change the load from 0 to 3600 watts depending on what excess solar is available.

That sounds complicated! How do we change a fixed 3.6kw resistive heater element?

Well there are a few ways:

1. Have multiple elements in the tank and only energise the ones that will more-or-less equal the excess instantaneous solar produced. (Very complicated solution that involves quite a bit of hardware modification to the heater)

2. Have some sort of 3.6kw controllable sinewave inverter drive the unmodified element. (Still a very complicated solution that requires a lot of power electronics)

3. Turn the unmodified heater element on/off as required so that the average power use is equal to the excess solar production.

Now you might assume that option 3 above won't work because the power meter doesn't average the on/off times. It will just charge you for the consumption while the element is on, and will only pay you a low rate while exporting when the element is off. Well it turns out that's not exactly the case.... The power meter WILL average the import/export energy as long as it is less than 3600 joules.


Forum member Jeremy Harris explains it well
Here and there is more info with graphs Here
It's exploiting the fact that most domestic energy meters have a "bucket" to fill of 3600 joules before they increment the counter forwards or backwards. The "bucket" can be filled or drained during this time, for as long as you like, and the counter does not increment in any direction.

So in theory you can fill the grid with 3599 joules of solar, then turn on the element, deplete the grid of 3599 joules, turn off the element and keep repeating this as long as you like!!!! As long as you don't go over 3600 joules, the power meter won't increment.

I want to do exactly what Jeremy did but with 3 phases. Each of the 3 X AD7755 power monitor chips will have two pins connected to the picaxe. One of which goes high every time 10 joules are measured, and the other pin will indicate whether the energy is imported or exported from the grid.

The picaxe has to add all energy pulses imported, and subtract all energy pulses exported.

As soon as 359 pulses are counted (3590 joules or less) it needs to turn on the solid state relay (triac). The pulses will now be draining the "bucket" so when the bucket gets to close to zero, the picaxe must turn off the triac. The process repeats.

Does that make sense?

Basically we need the picaxe to be a pulse counter for 3 inputs, with the ability to increment and decrement the counters by way of 3 more logic pins. The maximum frequency of each counter is 1.5khz.
 

hippy

Technical Support
Staff member
Does that make sense?
Yes, that makes more sense - it's simply tracking the accumulator you can't get at so you can figure out if it's going to start charging you do you can stop using their leccy before it does.

Basically we need the picaxe to be a pulse counter for 3 inputs, with the ability to increment and decrement the counters by way of 3 more logic pins. The maximum frequency of each counter is 1.5khz.
It seems you would need to handle 3 signals, each rising edge indicating 10 Joules had passed through the system and 1 to 3 inputs which indicates whether each should be added or subtracted from your PICAXE equivalent of the meter's accumulator.

To handle the worse case scenario accurately you would need to do this all within about 60ms.

I guess the question is, can a PICAXE handle an optimised version of below in 66ms ... ?
Code:
Symbol now                  = b2
Symbol now.phase1.pulse     = bit16 ; b2.bit0
Symbol now.phase2.pulse     = bit17 ; b2.bit1
Symbol now.phase3.pulse     = bit18 ; b2.bit2
Symbol now.phase1.direction = bit19 ; b2.bit3
Symbol now.phase2.direction = bit20 ; b2.bit4
Symbol now.phase3.direction = bit21 ; b2.bit5

Symbol was                  = b3
Symbol was.phase1.pulse     = bit24 ; b3.bit0
Symbol was.phase2.pulse     = bit25 ; b3.bit1
Symbol was.phase3.pulse     = bit26 ; b3.bit2
Symbol was.phase1.direction = bit27 ; b3.bit3
Symbol was.phase2.direction = bit28 ; b3.bit4
Symbol was.phase3.direction = bit29 ; b3.bit5

Symbol acc                  = w4 ; b5:b4

Init:
  acc = 0
  now = Pins

MainLoop:
  Do
    was = now
    Do
      now = Pins
    Loop Until now <> was
    If now.phase1.pulse <> was.phase1.pulse And now.phase1.pulse = 1 Then
      ; Phase has passed 10 joules
      If now.direction = 1 Then
        acc = acc + 10 Max 3600 ; Exporting
      Else
        acc = acc Min 10 - 10   ; Importing
      End If
    End If
    ... Repeat for Phase 2
    ... Repeat for Phase 3
    ... Handle turning load on or off
  Loop
 

PhilHornby

Senior Member
I was wondering (not knowing a great deal about three phase and its metering) ...

If you could arrange for the Solar PV Inverter and the Immersion Heater to be on the same phase, couldn't you just go with the circuit as specified by Jeremy? [just monitoring a single phase]

A supplemental thought - does a three phase meter even do the "Energy Bucket" thing that he and Robin Emley came up with? - it would itself, have to track usage across all phases, in a similar manner to that which you are proposing. I suspect the answer to that question could even be different for different models of meter...
EDIT
This (rather old) web page seems to indicate that three phase meters do implement a 'shared Energy Bucket'.
 
Last edited:

hax

New Member
Thanks very much Hippy for the code. I will give it a go.

PHIL: it seems that 3 phase meters are no different. They just aggregate their measurements to a single counter, and a single bucket just like the picaxe will.

There are reports that some meters use smaller buckets of around half the 3600 joules, but that's no problem, it just means a tweak of the code and shorter on/off times. A common 3600 watt element happens to have a nice neat 1 second on period to use up 3600 joules, and that on time will always be longer when the sun is shining. So we are not pulsing very quickly at all.



It just so happens that I do have a single phase HWS and a single phase solar inverter, so I could put them on the one phase, but I also have an outdoor spa and pool, each single phase on a 30A circuit and each has another 3kw heater, as well as an induction cooktop and air conditioning. (No gas here) So the beauty of this 3 phase approach is that it's monitoring the whole house for consumption and dumping only the excess solar.

I just can't get past the simplicity of this approach.
 
Top