Mains Clocking A Microcontroller

[Lujji] is playing around with the STM8 microcontroller. In reviewing the official documentation for this chip, he read the external clock can be a sine wave, a triangle wave, or a square wave with a 50% duty cycle. The minimum CPU frequency is 0 Hz. [Lujji] doesn’t have a signal generator, and presumably, he’s all out of crystals. He does have mains AC, though, so why not clock a microcontroller with wall power?

Using mains power as a frequency standard is a concept a hundred years old. Synchronous motors turn at a rate proportional to the mains frequency, and this has been used in clocks for decades. If you’re really clever, you can clock digital circuits with mains AC, but we’ve never seen someone replace a tiny crystal in a microcontroller circuit with mains power.

After an experiment to prove the concept, [Lujji] went on to construct a circuit that wasn’t as dumb as connecting the microcontroller directly to a wall socket. The direct approach didn’t work that well anyway — the STM8 didn’t like low frequency clocks with slow edges. [Lujji] needed a clock with cleaner edges, and a 555 configured as a comparator fit the bill.

The completed circuit sends mains power through an optocoupler to drive a 555 configured as a comparator. The output is a clean 50Hz clock that is connected to the OSCIN pin on an STM8. This is now a chip running at 50Hz, and yes, it works. [Lujji] set up a circuit to write ‘Hello World’ on an old Nokia LCD. That took about three minutes. It works, though, even though it’s completely useless. Maybe this can be applied to some novel timekeeping similar to that one-instruction-per-day clock we looked earlier in the year.

34 thoughts on “Mains Clocking A Microcontroller

  1. Mains AC Utility Frequency is a one way of clocking digital devices, but up-conversion of the mains frequency is typically required. Without up-conversion (as stated in the OP), clocking a micro-controller at 50/60Hz typically has little value (although I can see some applications with very cheap modern micros with micro-amp sleep drain acting as simple state-machines).

    For micro-controllers, the mains frequency is typically converted to a higher frequency. You can do this externally using a Phase-Locked-Loop (PLL), that uses the line frequency as a reference (example the venerable CD4046 PLL chip). Also it is possible that the micro-controller’s internal clock generator PLL can use low frequencies. We see this in specialized controllers for the likes of residential power-meters.

    But externally up-converting the line frequency isn’t as simple as it sounds. The typically large difference in line frequency (e.g., 50/60 Hz) versus the PLL output frequency (e.g., KHz to MHz range) requires special attention. The PLL lock time will be slow and and the cost of dividers in the PLL feedback loop add-up for higher output clock frequencies.

    Also note that the Mains AC line frequency varies over time with the total load to the system. In-fact the frequency variation is closely monitored by the utility provider as a metric of load over time. The variation happens daily as loads change between peak and off-peak demand periods.

    Theoretically over long time periods, the utility provider will adjust the line frequency so that the average frequency is reasonably accurate. The utility provider uses a precise frequency reference (often GPS-referenced these days) to discipline this process. But in-reality (especially in developing countries, like where I live), you cannot depend on this. See more here:

    There is a lot of information about the use of the Mains AC frequency as a real-time clock reference on the Web.

    1. “For micro-controllers, the mains frequency is typically converted to a higher frequency.”
      I have never seen this, can you give an example?
      The way it is normally done is that the micro runs from some higher speed, internal and not precise clock, like an integrated RC oscillator. The 50 Hz in then just used to count pulses to measure the time.

      1. I explained this right in my post: “You can do this externally using a Phase-Locked-Loop (PLL), that uses the line frequency as a reference (example the venerable CD4046 PLL chip). Also it is possible that the micro-controller’s internal clock generator PLL can use low frequencies. We see this in specialized controllers for the likes of residential power-meters.”

    1. I think the problem is at the output side …. those cheap optocuplors have at least 50% transfer rate, so with 1.8mA to start on the LED side, the 100K on the micro side is way too large. I suspect that is also why the glitches are there – the clock pins normally have Schmidt triggers, it should not be an issue that requires the whole 555.

      1. Last winter, I used the 60Hz (US) mains for timekeeping. The instantaneous frequency accuracy is pretty poor but the long term average is quite good. Anyway, I tried using a simple comparator to square up the edges before feeding into an interrupt input. I was getting many transitions around the comparator transition points. I think that the power line communications that utilities are using now were the source, as the glitches that were triggering the comparator were visible on a scope. I used an LM555 set up as a one shot to insure that you only get one transition per power line half cycle. The phase accuracy stinks, but who cares in a wall clock application. The timekeeping accuracy is fine now.

        1. I agree about the source of the problem, and that’s one perfectly good fix.

          Of course, if you wanted better phase accuracy (for whatever reason) or were looking for an excuse to not use a 555, one solution is a filter — even a simple RC lowpass will go a long way when you’re separating 60Hz from multi-kHz. You can be particularly clever, and combine the RC filter and the means of reducing mains voltage to comparator-friendly levels — the R is just a resistor but the C is two capacitors in series; they act as a capacitive voltage divider, e.g. with 10uF & 1uF (equivalent to 0.9uF), the 10uF sees 1/11 the total voltage, and the 1uF dumps the other 10/11. (I think the caps, or maybe just the smaller-valued one, need to be X-rated for this to be legit.) Of course it’s usually smarter to just use a transformer.

          (You should probably have your comparator set up as a Schmitt trigger with or without filtering; a Schmitt trigger alone may solve the problem, with an appropriately selected hysteresis, but without a low/bandpass filter to select 60Hz it will face the same phase issues as your one-shot.)

          1. The setup that I used has a transformer for isolation and step down. I thought about using a filter, but it would have had to be a pretty aggressive one, so I just opted for the 555. I have no problems with using a 555 in an appropriate situation.
            The original comparator setup had 40 or 50mV of hysteresis, and still had issues.

  2. Once upon a time, the guys doing field measurements just loved 300 baud modems because the lower frequencies allowed long runs of cable and (apparently) good rejection of noise. Would a supremely slow system like this be even better for small data sets (such as temperature or soil moisture ever few minutes) under certain circumstances? Of course you could goose up a 8266 etc. etc. but it’s an interesting thought experiment.

    1. If you look at right now, and lick antenna 43, and click the communication “details” (bottom right) of the Voyager 2, you see it is currently using 160 b/sec.
      Another example is the satellite positions in the GPS signal, which are send with only 50 bit/s.
      There is also Extremely low frequency (0 to 30 Hz) used for submarines, works well under water, but the data rate is similar to Morse code.
      In any situation with a very bad signal to noise ratio, sending bits very slowly helps a lit.

    1. That’s why we Europeans prefer our RISC processors to your Intel CISC ones, we can get more done in fewer cycles…
      /me steps back and waits for the ARM/Intel flame war.

  3. Many many years ago I tried clocking a CPU board that I was working on at a very slow clock rate. I wanted to see the bits rattle through it. It did not work. Any parts that used a dynamic memory topology need some minimum clock rate to function. I recall in the hundreds Khz working but not anything in the audio range.

  4. I made one circuit that had a mains crossover reference and it didn’t work as well as I expected so I have to fix it in software by creating a software bandpass filter which isn’t that hard to do.

    Anyway, if your connecting the mains you *could* possibly use that as a power source!! Stating the obvious.

    I used a cheap PCB mount mains step down transformer with a secondary or about 7 volts and an op-amp to detect zero crossing. The problem I fixed with software is the lack of a band pass filer for the op-amp. It just had a bit of positive hysteresis feedback that wasn’t enough to get rid of the higher frequency noise on the mains.

    The transformer provides very good isolation from the mains voltage which is always going to be the safer option.

  5. 50Hz is not bad, is expected to run at maybe 20 or 25Hz :-D

    Now this gives me the idea that I could run the clock from the mains, just direct driving of the clock signal from a 12V coiled trafo… This would totally solve the fanout problem ! But even in Europe the frequency is too high and I doubt I can reach 50Hz… if I have to divide the frequency, it will amount to the same thing I wanted to do before, with long fanout lines…

  6. If you’re thinking in terms of electronics, yes, 50-60 Hz is like watching lichen grow. But for Charles Babbage’s computers, smoke and powdered metal would appear long before a clock speed of 50 Hz was reached. And yet these machines WERE useful, for creating trigonometric and logarithmic tables both faster and orders of magnitude more reliable than (human) computer-generated tables.

    When faced with a problem of insufficient computing power, and speed is limited by the technology, the answer is parallelism. Your fancy modern electronic computer can do 5 trillion data transfers per second? Well, a mechanical computer running at 50 Hz can match this, and it only needs 100 billion transfer registers to do the trick. If you can build the registers in a 1 micron-cube volume, that can fit in a 5 mm cube, if I’ve done my math right. Routing the data into and out of that is left as an exercise for the student.

    1. unless its a complicated program with lots of instructions per LED flicker, then for proper lightshow you might actually need 50hz

      or its a sequencer (with a bug) that outputs too fast for your analog scope…

Leave a Reply

Please be kind and respectful to help make the comments section excellent. (Comment Policy)

This site uses Akismet to reduce spam. Learn how your comment data is processed.