Accurate powerline frequency meter.

premelec

Senior Member
I've seen small commercial loggers use a method of recording start actual time and then when reading the eventual PIC recorded elapsed time compare it to the start time and reading _real_ read time and simple apply a proportioned correction derived from actual read time to all the logged readings.. a close approximation to time correction over reasonably short intervals. That assumes the internal oscillator doesn't change a lot from environmental factors, voltage etc...
 

fernando_g

Senior Member
Thanks!
This Elektor project may be exactly what I require. Unfortunately PE6 doesn't run on an IPhone to allow me to examine the code. :(
 

Dartmoor

Member
Somewhat off topic - but fun?
Photo is our local power station, which is almost completely original 1930's installation. The two precision clocks in the case on the wall are the way to check if frequency is fast or slow. One is electric & the other is pendulum. I suspect, from the dials, that someone had forgotten to wind it up when I took the photo! Enjoy!

Mary Tavy Power Stn 006 - Copy (710x800).jpg
 

Buzby

Senior Member
Thanks!
This Elektor project may be exactly what I require. Unfortunately PE6 doesn't run on an IPhone to allow me to examine the code. :(
Can't you just rename .bas to .txt, then use a text viewer ?.

( I don't have an iThingie )
 

BillBWann

Member
Fernando_g’s interest in measuring the frequency of his local mains supply piqued my interest in knowing how well our own mains frequency was maintained.
Way back in 2007, I’d built a timer devised by Hippy which incorporated an 08M picaxe and a 32kHz crystal. It worked well at the time but in recent years, it had found its way into my junk box. I thought that this module could form the basis of a quite accurate mains frequency monitor if its 32k crystal oscillator could time 50 mains pulses and report its count.

So I built a simple mains interface incorporating:-
• A 9 volt AC plugpack
• A full bridge rectifier, smoothing capacitor and resistor divider to bring the rectified DC voltage down into the 5 volt range.
• and a diode connected before the bridge rectifier to supply base current to a transistor so as to square up the sin wave into an asymmetric square wave.

The smoothed DC, resistor divided supply voltage was fed to pin c.2 while the square wave was connected to pin 1 of the 08M2 which would replace the 08M that was originally installed in Hippy’s timer module.

The following program was externally programmed into the 08M2 as it cannot be programmed in the timer module because the normal “serial in” pin forms part of the 32k oscillator. I’ve included Hippy’s original circuit diagram into this program for information. My part of the program also owes much to the efforts of Hippy, Jeremy Leach & others for a timer program also written about that time which used Timer1 to time the length of pause commands .


Code:
; *****************************************************************************
; *                                                                           *
; *     Hippy's Circuit Diagram for 08M Timer module                                                       *
; *                                                                           *
; *****************************************************************************

;              .----------------------------------.
;       TX O<--'        ___                       |
;       RX O-------.---|___|---.--|>|-- +V        |
;       0V O--.   .|.   22K    |                  |
;             |   | |          |                  |
;             |   |_| 10K      |                  |
;            _|_  _|_          |                  |
;                              |    PICAXE-08M    |
;       32.768kHz XTAL         |   .----------.   |
;        _______               |   | +V    0V |   |
;       |       |----.---------|---| SI    O0 |---'  Plaintext Out    4800 baud
;       |_______|----|----.----|---| X4    X1 |--->  Binary Out       4800 baud
;                   _|_  _|_   `-->| I3    X2 |--->  Square Wave Out  0.5Hz
;         2 x 33pF  -.-  -.-       `----------'
;                   _|_  _|_
;
;       Note that the PICAXE-08M must be programmed out of circuit as it is
;       not possible to program the 08M in-circuit in this configuration.



#picaxe 08M2
#no_data

Symbol T1CON = b0
Symbol T1ConOff=b1
Symbol Timer1ValueW = w1
Symbol Volt = w2
Symbol AccVolt = w3
Symbol Temp=b8

Symbol RAM_T1CON = $18
Symbol RAM_TMR1 = $16


'T1CON:
Symbol TMR1CSH_Bit = bit7	'Timer1 Clock Source Select bits
Symbol TMR1CSL_Bit = bit6	'Timer1 Clock Source Select bits
Symbol T1CKPS1_BIT = bit5	'Timer1 Input Clock Prescale Select bits
Symbol T1CKPS0_BIT = bit4	'Timer1 Input Clock Prescale Select bits
Symbol T1OSCEN_BIT = bit3	'LP Oscillator Enable Control bit
Symbol T1SYNC_BIT = bit2	'Timer1 External Clock Input Synchronization Control bit
Symbol Unimplemented_BIT = bit1
Symbol TMR1ON_BIT = bit0	'Timer1 On bit;1 = Enables Timer1;0 = Stops Timer1 Clears Timer1 Gate flip-flop

Initialise:
	SetFreq M32
	Gosub InitialiseTimer1

Main:
pause 4000	'wait 0.5 secs

do
	AccVolt=0					'Initialize cumulative voltage count
	do: loop until pinc.1=0	'Wait for positive part of waveform to end
	do: loop until pinc.1=1	'Wait for negative part of waveform to end
	Gosub ResetAndStartTimer1	'Start the clock
	For Temp=1 to 50				'Repeat for the next 50 cycles
		do: loop until pinc.1=0
		readadc10 c.2,Volt		'Read the resistor divided DC voltage on the capacitor
		AccVolt=AccVolt+Volt		'and accumulate it
		do: loop until pinc.1=1
	next Temp
	Gosub GetTime					'Stop the clock and read the timer
	Volt=AccVolt/5					'Divide by 50 & multiply by 10
	Volt=Volt**31360				'Convertion factor based on transformer voltage & resistor divider

	sertxd (#Volt,", ",#Timer1ValueW,CR,LF)	'Print Mains voltage*10 and Timer Value
loop														'Freq=50*2^15/Timer Value (done in Excel)
	
	'------------------------------------------------------------------------------------------
InitialiseTimer1:
	'Sets the T1CON control register. Only needs to be called once, before
	'using Timer1.
	
	Peeksfr RAM_T1CON,T1CON
	
	TMR1CSH_Bit =1	'Timer1 clock source is 32k crystall oscillator
	TMR1CSL_BIT = 0	'Timer1 clock source is 32k crystall oscillator
	T1CKPS1_BIT = 0	'Divide by 1 Pre-Scaler
	T1CKPS0_BIT = 0	'Divide by  Pre-Scaler
	T1OSCEN_BIT = 1	'Dedicated Timer1 oscillator circuit enabled
	T1SYNC_BIT = 0		'Synchronise to System Clock
	Unimplemented_BIT =0
	TMR1ON_BIT = 0	'Timer 1 Disabled

	Pokesfr RAM_T1CON,T1CON 'Set T1CON
	T1ConOff=T1CON
Return
'-----------------------------------------------------------------------------------------
ResetAndStartTimer1:
	'Set both LSB and MSB of Timer1 to 0
	Pokesfr RAM_TMR1,0,0
	'Start Timer1
	Peeksfr RAM_T1CON,T1CON
	TMR1ON_BIT = 1		'Enables Timer1
	Pokesfr RAM_T1CON,T1CON
Return
'-----------------------------------------------------------------------------------------
GetTime:
	'Stop Timer1
	Pokesfr RAM_T1CON,T1ConOff

	'Load result
	Peeksfr RAM_TMR1,Word Timer1ValueW

Return

The printed output from the module was logged and fed into Excel.

If the mains frequency was exactly 50Hz, then 50 cycles should take exactly 1 second which would result in a timer count of 2^15 or 32768. If it was a bit less, the time period would be a bit longer resulting in a count that was greater than 32768. The formula in Excel for converting the period count to frequency is therefore 50*2^15/Timer Count.

Plot1.jpg

The Excel chart shows a frequency plot of our mains supply over a 5 hour period earlier today. I’ve also included a cumulative time error between the crystal and a count of the mains pulses. This suggests that the max error between the two during this period was about 3.5 seconds whereas our local standard sets an upper limit of 5 seconds. I say suggests because, the program only monitors the mains for 98% of the time (it misses a single pulse each second while it prints out the results) and the 32kHz crystal may not be perfectly accurate. Of course, it also assumes that the two times were in sync when I first started monitoring at about 3:15pm.
 

tmfkam

Senior Member
A really interesting way of measuring the frequency there, and crystal referenced too. Ingenious.
 

BillBWann

Member
Minimized Mains Frequency Monitor

It turns out that you don’t need many components if you simply want to measure the instantaneous frequency of the mains supply. In my house at least, all you need is an 08M2, a 32kHz clock crystal with their associated capacitors and some hookup wire to act as an aerial as shown in the picture below.

IMG_6155.JPG

I had thought that maybe my original mains interface could be simplified to a simple 22k resistor in series with the 9 volt AC supply from the plugpack and let the protection diodes on pin c.1 do the rest. I tried this out with the count command and it returned the expected result so I then tried it in the 32kHz oscillator circuit but it didn’t work. It appeared that the 9V AC supply via the 22k resistor was affecting the 32 kHz oscillator circuit. I thought that maybe a higher value resistor may solve the problem but just after I’d taken the 22k resistor out of the circuit, the frequency value being sertxd by the program appeared to look like the real thing.

I then programmed up another 08M2 with the same program to put back into my original circuit as described in #46 and let both run for some time.

Mains Comp.jpg

As you can see from attached Excel chart, both lots of results are in lock step – the only difference being that the circuits aren’t exactly synced so each is seeing a slightly displaced set of 50 mains cycles.

I’d be interested to hear any suggestions as to why the 9V AC input via the 22k resistor didn’t work and appeared to stop the oscillator. If the resistor was increased to 33k or higher, then the oscillator worked as expected (assuming the 9v plugpack was powered, of course). Adding a 0.1 capacitor across the Vcc supply didn’t appear to make any difference – which is what I would have expected given that the circuit was driven by 4 NiMH cells with short leads.

In the absence of any other explanation, all I can assume is that the mA or so being added to Vcc each mains cycle was enough to upset the oscillator but I'm surprised that the 4 NiMh cells and 0.1 uF bypass capacitor couldn't have absorbed that sufficiently.
 

AllyCat

Senior Member
Hi,

22k resistor in series with the 9 volt AC supply from the plugpack and let the protection diodes on pin c.1 do the rest.
I'm not sure exactly what you mean by an "ac plug pack", nor c.1 (which appears to be used as an output), but allowing a current to flow in the negative protection diode is a known issue with PIC(axe)s. The current flows into the substrate (they may well be substrate diodes) and upsets some of the analogue circuits such as the ADCs.

Try adding a Schottly diode (eg BAT85) to earth as was used with the "Enhanced Serial Download Circuit" on page 45 of the old Manual 1. That diode was used to clamp the negative voltage from "real" RS232 COM ports, but is no longer considered necessary with (most) USB-serial adapters.

Cheers, Alan.
 

fernando_g

Senior Member
What Allan said.
A "9V" plugpack may go up to 11 or 12 volts RMS if it is not fully loaded.
Let's assume 11 volts RMS...this means about 15.4 peak volts.

Which across 22k means essentially about 0.7 peak mA injected into the pin during the negative cycle....not a good engineering practice!
Add the schottky diode.
 

hippy

Technical Support
Staff member
Which across 22k means essentially about 0.7 peak mA injected into the pin during the negative cycle....not a good engineering practice!
Most PICmicro clamping diodes are rated for 20mA max current so 0.7mA should be well within spec.

I tried this out with the count command and it returned the expected result so I then tried it in the 32kHz oscillator circuit but it didn&#8217;t work.
It is not entirely clear how you mean by "tried it in the 32kHz oscillator circuit". Using your current limited signal into C.1 and using that to start and stop the timer I would have expected to work.

Perhaps show your full circuit including PICAXE power supply and how the AC psu is wired. It could be that it is floating so not giving a reliable signal.
 

BillBWann

Member
Perhaps show your full circuit including PICAXE power supply and how the AC psu is wired. It could be that it is floating so not giving a reliable signal.
Thanks everyone for your thoughts.

I’ve modified Hippy’s original diagram for his timer to show what I thought might work as a mains frequency monitor when the 08M2 was programmed with the program listed in #46 (where pinc.1 is an input).

Code:
;              .----------------------------------.
;       TX O<--'    Plaintext Out    38400 baud   |
;                                                 |
;       0V O--.  5V Battery O--.                  |
;             |                |                  |
;             |                |                  |
;            _|_               |                  |   ,----.
;                              |    PICAXE-08M2   |   |   _|_ 0V Battery
;       32.768kHz XTAL         |   .----------.   |   | 
;        _______               '---| +V    0V |-------'-------<O  
;       |       |----.-------------| SI    O0 |---'              9V AC Plugpack
;       |_______|----|----.--------| X4    X1 |-----/\/\/\/\--<O
;                   _|_  _|_       | I3    X2 |        22k
;         2 x 33pF  -.-  -.-       `----------'
;                   _|_  _|_
;
When it didn’t work, I initially tried inserting a signal diode in series with the 22k resistor but it didn’t improve things. To be precise, if the input to pin c.1 was only the aerial wire, then everything appeared to be stable and it delivered consistent good results that tallied with my original circuit. When pin c.1 was connected to the 9V AC source via the 22k resistor, the oscillator seemed to become unstable and erratic with the timer count dropping until after about 10 or so seconds it could reduce to zero. If a signal diode was also added in series with the 22k resistor meaning that only positive voltages were being applied to pin c.1, then the whole 08M2 became unstable and it printed garbage and a quick look at the signal coming from pin c.0 looked more like an oscillator output than a serial output.

Sometimes, when only the 22k resistor was in circuit, the 32kHz crystal oscillator appeared to stabilize at 50 Hz rather that stop completely which did suggest that the protection diodes on c.1 was causing the upset and presumably that can only occur via a variation to the voltage on Vcc. But as I said previously, I would have thought the low impedance of the battery supply would dampen out a mA or so of current.
 

hippy

Technical Support
Staff member
Your diagram looks okay to me, is exactly how I would have done it myself. You could try using a voltage divider to get the voltage below the PICAXE supply voltage ...

Code:
               |   .----.
 PICAXE-08M2   |   |   _|_ 0V Battery
.----------.   |   | 
| +V    0V |-------'---.--------<O  
| SI    O0 |---'      .|.
| X4    X1 |-------.  |_|
| I3    X2 |       |   | 
`----------'       `---{      9V AC Plugpack
                      .|.
                      |_|
                       |
                       `---|<|--<O
 

AllyCat

Senior Member
Hi,

The diode will have some stray capacitance so I would try holding down the c.1 input with a capacitor or resistor as hippy shows above.

But if you want a "minimal" design, there is an "optional" internal pull-down resistor on c.1 . It's the DAC reference pin, so if you enable the DAC to use its external reference pin (but do not enable its output to c.0), then there should be around a 160k pulldown on that pin. Not tested now, but I think the command would be: dacsetup $84 .

Cheers, Alan.
 

BillBWann

Member
But if you want a "minimal" design, ...........
I think the minimal design is a simple bit of hookup wire 300 mm or so long to act as an aerial. From my testing, this seemed the most reliable and stable configuration but presumably you can’t be too far away from some 240 volt wiring and I haven’t investigated that at all.

If you want to involve a plug pack, then I’d suggest the circuit I showed in #52 but replace the 22k resistor with 33k or higher.

I also tried Hippy #53 circuit with a 22k/10k voltage divider and diode and that worked for most of the time but still seemed a bit unstable and often needed to be coaxed into action by switching the battery supply on & off a few times to get it oscillating at 32kHz or to stop the 08M2 from going into convulsions and printing garbage (although consistently the same garbage - here's an example "€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€300, 0"). Again, it seemed to be more reliable if the 22k resistor was replaced with a higher value.
 

hippy

Technical Support
Staff member
I also tried Hippy #53 circuit with a 22k/10k voltage divider and diode and that worked for most of the time but still seemed a bit unstable and often needed to be coaxed into action by switching the battery supply on & off a few times to get it oscillating at 32kHz or to stop the 08M2 from going into convulsions and printing garbage (although consistently the same garbage - here's an example "€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€300, 0"). Again, it seemed to be more reliable if the 22k resistor was replaced with a higher value.
I would guess it's got something to do with Download Serial In effectively floating and something causing the PICAXE to believe it is receiving a download and resetting.

Looking back it seems there is no DISCONNECT command in the code which could cause problems.

It would be better to use an M2 which doesn't have the LPOSC crystal pins on Download Serial In.
 

AllyCat

Senior Member
Hi,

Isn't it only the 18M2 that doesn't have the LPO on the programming input pin (Leg 2)?

Maybe an exceedingly week pull-down (say 10 Mohms) would keep the PICaxe "happy" but allow the oscillator to run? However, I believe that crystals (particiuarly the 32kHz type) have an really high effective impedance and unfortunately Leg 2 is the oscillator input not output.

Cheers, Alan.
 

hippy

Technical Support
Staff member
Isn't it only the 18M2 that doesn't have the LPO on the programming input pin (Leg 2)?
That does seem to be the case. The 08M2, 14M2, 20M2 and 20X2 require the use of the Download Serial In leg when using LPOSC and that relies upon the pin being seen as low at power-on reset and once the oscillator has been enabled. I did not include a DISCONNECT in my code because I did not experience any problems but it would, with hindsight, be best to include that.

Only the 18M2 ( using B.6 and B.7 ), 28X2 and 40X2 ( both using A.0 and A.1 ) have the LPOSC on I/O pins. It might be possible to run the 28X2 and 40X2 on internal oscillator and connect a watch crystal to the normal resonator pins but I have never tried that.

When I first experimented with the LPOSC ( back in 2007 ), I used an 18X and it also seemed to work with an 08M. I am not sure what else I have tried it with since or how well it works with anything other than those.

When otherwise using the on-chip internal timer, driven from the system clock rather than LPOSC, on M2's I have noticed some occasional oddities which I put down to the 'time' variable handling in the M2 firmware which seems to still be handling overflow interrupts to increment 'time' and resetting / presetting the timer when it does, even with DISABLETIME.

Care therefore has to be taken with the M2's to avoid erroneous readings, though as long as the timer doesn't overflow before being read there should hopefully be no issues, but I cannot guarantee that. I think all of my recent on-chip timer experiments have involved the 20X2 which is not affected by the M2 firmware issue.
 

BillBWann

Member
Thanks Hippy & Allycat. Very interesting discussion.

The combination of functions on the Serial In pin c.5 is an interesting theory and another example of Hippy’s out of the box thinking.

I inserted a Disconnect command to be the first executable command and it did seem to improve the stability of the 08M2 when operating using Hippy’s #53 circuit. Interestingly though it still sometimes printed out the same garbage for a couple of iterations before the 08M2 settled down. If the Disconnect command was having an effect, surely it should occur before the program reached the Sertxd command.

Replacing the 22k resistor with a higher valued one again reduced the number of program iterations before the crystal oscillator settled at 32kHz but the thing that seems to guarantee stability of the 08M2 is NOT using the series diode.

The higher resistance values make some sense to me, as does adding the 10k resistor, in that in both cases, the current through the protection diodes on pin c.1 is reduced. But omitting the series diode to improve stability makes no sense to me at all. It’s hard to see why adding the diode and stopping the negative voltage reaching input pin c.1 would make the 08M2 unstable. If including the diode was going to have any effect, I would expect the opposite. Looking at the voltage on c.1 with the CRO, the waveform changes is as you would expect – adding the diode cut off the small negative voltage while the positive part of the waveform looked unchanged.
 

hippy

Technical Support
Staff member
it still sometimes printed out the same garbage for a couple of iterations before the 08M2 settled down. If the Disconnect command was having an effect, surely it should occur before the program reached the Sertxd command.
Being garbage suggests the data isn't coming from the SERTXD but from the firmware. That would be the case if the PICAXE believes there is a download initiation when it powers-up, before it executes the DISCONNECT. The PICAXE will enter its download mode, see there isn't actually a download, and may keep repeating that until it doesn't seem there is a download and manages to reach the DISCONNECT.

Because Download Serial In is effectively floating it is relying on good fortune that at some point the PICAXE will make it past turn-on to executing the DISCONNECT.

Put the program's serial output for data on a pin other than Download Serial Out and it should be corruption free. How quickly one gets to data output will depend on how quickly it gets past the turn on and executes the DISCONNECT command ... if it ever does.

The problem here is trying to prove a proof of concept on an unpredictable set-up. The PICAXE getting to execute DISCONNECT is not guaranteed though in practice it seems it eventually will. Adding things to the set-up could disrupt that.

Unpredictable set-ups are by their nature difficult to analyse. It would be best to start with an 18M2 which would be a predictable set-up. Prove the concept works with an 18M2 and then see how well it works for an 08M2. It may be that it simply doesn't, that there is some difference in silicon which prevents it working as well as it should.
 

AllyCat

Senior Member
Hi,

Because Download Serial In is effectively floating it is relying on good fortune that at some point the PICAXE will make it past turn-on to executing the DISCONNECT.
Perhaps you could add a "switch" (typically a capacitor to ground, charging resistor and a diode) to hold the Serin/oscillator pin low (< 1.4v) for long enough for the DISCONNECT to activate. Actually, you could omit the resistor by activating the internal weak pullup (needs an SFR command) for a brief time. The crystal is basically a capacitance and shouldn't affect this starting sequence much. Once the capacitor is charged to near the supply rail, a "fast" (small signal) diode should be sufficiently reverse biassed to present neglible residual capacitance on the pin. Pause the program for a few seconds and then the 32 kHz oscillator should be running good to go. ;)

Cheers, Alan.
 

fernando_g

Senior Member
Project's conclusion

You may want to know how all of this ended.

Firstly, the company which had the original problem went ahead and purchased the very expensive VFD. Yet the problem was not solved. A melee has ensued and I'm so glad that I wasn't involved anymore.

But my curiosity was sufficiently piqued that I continued with my work. I completed tested and debugged a prototype, which by the many means which I've tested it, it is perfectly capable of the 0.01 Hz resolution with at least 10X margin.

I will post the details in the Complete Projects later;
suffice to say is that there are two significant requirements: the first, intuitive, is that many individual readings must be averaged. I'm averaging 2400 readings (details on how and why in the coming post). The second, surprising, is that the zero-crossing detector is really, really critical and the source of many inaccuracies. To have an accurate and isolated zero-crossing detector, a semi-discrete approach proved to be the most robust and reliable. Again, details later.

The results? The frequency measured at my home, has never deviated more than 0.05 Hz. I have not measured in the middle of the night, which I suspect the lightly loaded generators may be running a little fast.

The second part of the project is to integrate the cumulative errors over a period of time. So far, the best approach I've though is to simply store in EEPROM the averaged values in 15 minute increments (utilities standard time period), dump them later and then perform all the required maths and plotting in Excel.

Thanks everybody who gave valuable ideas to this project.
 

hippy

Technical Support
Staff member
The second, surprising, is that the zero-crossing detector is really, really critical and the source of many inaccuracies.
That was one of the things which had me wondering about how feasible it was. A 0.01Hz change in frequency is just a few microseconds change in mains cycle length so any small variation in the switching point of the sensor would change the perceived cycle time and the frequency. And the perceived mains cycle time potentially changes if the mains voltage drops or increases.

Nothing wrong with averaging but I did wonder how limiting that would be. One can monitor longer periods, frequency changes over minutes and longer, but shorter term variations where being fast and then slow may cancel out longer term will be missed. Ideally per cycle determination is best, but then it is back to that not necessarily being easy.

Looking forward to the details.
 
Top