Monday, May 16, 2016

Designing a Mains Frequency Monitor, Part 1

This is the first in a series of posts about designing a mains frequency monitor using the Microchip PIC 16F1619 microcontroller. Today we will talk about the features of this device that make it a good choice for such a project. We will also start to piece together our circuit, program, and test a prototype on the breadboard.

Prototype of a mains frequency monitor using the PIC 16F1619.


Many people assume that the mains frequency is exactly 50/60Hz, but in fact that is rarely true. Accuracy and stability of the mains frequency is an interesting topic to research. No two points on the grid will have exactly the same characteristics, so collecting data at your location can reveal some interesting findings. This is especially true if you have (or are interested in building) a mains-referenced clock. There are many industrial applications as well for such a project.

Numerous circuits and methods have been published for monitoring the mains frequency. Recently, I came across the PIC 16F1619 microcontroller and thought it would be a great device to design my own solution around. It is a very inexpensive chip that comes in a DIP package, making it breadboard-friendly for prototyping. This PIC has an interesting set of features including a Zero Crossing Detector (ZCD), a Signal Measurement Timer (SMT), and an Angular Timer. It also includes several 16-bit timers, configurable logic cells, a PID math accelerator, a hardware USART, and lots more. Check out the datasheet for this device to learn more.

Pinout of the 16F1619 in a 20-pin PDIP/SOIC/SSOP package.

Zero Crossing Detector

The first peripheral we will examine in more detail is the ZCD. It allows the detection of both the positive- and negative-going zero crossings of the input signal. Additionally, the output of the ZCD can be used as an input to another peripheral such as the SMT for gating and windowing. Externally, it requires only a single series resistor to limit the current into the module. Additional pull-up and pull-down resistors can be added to correct the offset on the comparator reference voltage or intentionally set an offset from true 0V. Check out this Technical Brief to learn more about the capabilities and setup of the module.

Block diagram of the ZCD module.

Scope capture of an AC input signal (blue) and ZCD output signal (yellow).
The output is also accessible in an internal register for triggering other peripherals.

Signal Measurement Timer

The SMT is a flexible 24-bit timer with many options for clocking, windowing, and gating. Check out the Technical Brief to learn more about it. We can use it to measure the relatively long cycles of the mains signal at full system clock speed and still not overrun the timer. Combined with the ZCD it gives us a means for measuring the mains frequency to a suitable level of precision. With the core functionality needed for our project handled by integrated peripherals, we save our code space for processing the data and feeding it out to another device for monitoring and logging.

Block diagram of the SMT module.

Angular Timer

Another really cool peripheral in the 16F1619 is the Angular Timer. It locks onto the input signal and allows the instantaneous phase angle to be determined at any point during the cycle. It can also be used for missed pulse detection. This peripheral relies on several registers and configuration bits, but once set up it is easy to use. You simply read out the value of the phase clock during a cycle to calculate the angle. This peripheral has many potential uses for mains applications and motor control. Microchip has a webpage on it with more information, documentation, and a video.

Designing the Circuit and Firmware

With the above three peripherals in mind, I started working on my circuit design for the project and building a prototype on the breadboard. I added a 20MHz TCXO to generate a stable, accurate clock for the microcontroller and timers. For the mains input, I used a 12V AC wall adapter. This goes into a half-wave rectifier and then a voltage regulator to generate VDD. The mains signal to be measured is tapped off before the rectifier, bringing it into the ZCD with a common ground reference. I might explore upgrading to a center-tapped full-wave rectifier in the future.

Below is a partial schematic for the circuit thus far.

The beginnings of a mains frequency monitor circuit.

The firmware came together quickly in MPLAB X IDE. I set up the various peripherals and put the SMT into Windowed Measure mode. The window is triggered by the internal ZCD output bit. When a positive-going zero crossing is detected, the SMT beginning counting at the full 20MHz system clock speed. At the end of the cycle the count is latched into a register and then stored. Once measurements for 60 cycles are accumulated, the average frequency during the second is calculated and printed via USART to an LCD display.

I didn't actually need the Angular Timer in my project, but it's such a cool peripheral I wanted to find some way to include it. I decided to use it to verify that the negative-going zero crossing occurs at the correct phase angle. That angle is of course 180 degrees (assuming a symmetric waveform). The ZCD generates an interrupt at the zero crossing and the program checks the count in the phase timer. If the phase angle is not correct, an error flag is set. Currently I just use this to set a status LED, but there is a lot more that could be done with it. In the future I might use it to detect erroneous measurements and automatically remove them before they get ingested into my data.

This hardware and firmware setup also gives us the basis for a mains-referenced clock, where the time is incremented every 60 cycles. That doesn't actually provide very good timekeeping (over short intervals) due to the instability/innacuracy of the mains frequency. For now it's an interesting addition to the project though. We will revisit this later and implement a much better solution for our clock.

The prototype on the breadboard works well, and you can see a picture of it at the top of this article. My initial testing against proper frequency counters shows that the design so far meets my expectations.

Lots More To Do

The project is coming along well, but we have a lot more to do before it is done. In Part 2, we will finish the firmware, finalize the schematic, and design a PCB for it. We will also need to do a lot of testing to verify the performance of the counter.

I have uploaded the program in its current state to a new Github repo. Please check it out if you are interested in seeing what the code looks like. This repo will also house the PCB design files and other documentation in the future.

If you have feedback and suggestions on this project, please post them in the comments below. A post on Part 2 of the project will be coming in a couple of weeks.

Thanks for reading!

- Dan W.

Saturday, May 14, 2016

Quick PCB: TCXO Breakout

I'm back with another Quick PCB. This one is a little breadboard-compatible breakout board for inexpensive temperature-compensated crystal oscillator (TCXO) modules commonly found on eBay.

Need a TCXO frequency reference for your breadboard project?
This might be a good option for you.


There are some good, inexpensive TCXO modules on eBay that come in the slightly unusual package shown above. This breakout board allows you to mount one of the modules onto the small PCB and adapt it to standard 0.1" breadboard-compatible headers. I have also included a few optional SMD components. There are spots for a power LED, a bypass capacitor on the supply rail, and a capacitor on the control voltage input.

Some of these modules don't actually have a control voltage input on pin #1. Typically they have a small trimmer on top for adjusting the frequency, which is probably more useful for how these are commonly used. If you have access to a disciplined frequency reference such as a GPSDO, you should allow the module to warm up for 24 hours and then trim the frequency.

I have tested this board with two such TCXO modules from eBay. One is a 20MHz Raltron unit that is quite useful for microcontroller projects. You could also use a D flip-flop to divide it to 10MHz. The other is a 14.4MHz Rakon unit. Other modules in the same package will work. I honestly don't know what the package is called, so if YOU do please let me know in the comments below.

Assemble Your Own

Eagle Files: Shared on Github
TCXO Breakout Board: Order PCBs on OSHPark!

TCXO Breakout Board Schematic

TCXO Breakout Board Layout
Sharp-eyed readers will note this has been updated from the boards shown above.
The circuit is the same but the layout is much cleaner.

Parts List:

TCXO Module: Raltron RTX0230LC, Rakon VTX0525-14.4MHz, or similar
C1: 100nF 0603 SMD
C2: 10nF 0603 SMD (Only necessary if your module has VFC on pin #1)
R1: 1k 0603 SMD (or adjust value to change brightness of LED)
PWR LED: 0805 SMD (color of your choice)
Headers: Four 2x1 0.1" standard male headers (snap off from breakaway strips)

Note: The outer-most pins on each header are not connected to anything. They are just there for stability on the breadboard.

Sine to Square Wave?

Many of these modules output a relatively weak sine wave. However, you probably need a logic-level square wave for your project. You can use the circuit shown below to convert the sine wave output to a square wave. Note that you may need to adjust the resistor divider values based on the output signal of your module and the inverter you use. The peak-to-peak output from the TCXO needs to extend past the High and Low logic thresholds of the inverter to successfully trigger it. The divider also adjusts the duty cycle of the output.

Use a schmitt inverter chip with TTL-compatible inputs. I use 74LVC chips exclusively for my projects. 74ACT is another good series. If you want to be really old school, find those 74Fs in the junk box.

A typical circuit for converting a sine wave signal to a logic-level square wave. 

Wrap Up

I hope this little breakout board is useful to you! Tweet me a pic @sync_channel if you build one into a project.

Thanks for reading!

- Dan W.

Monday, May 2, 2016

Learning Embedded Electronics with the ATtiny104 XNANO

In this post I will document a small add-on board that I designed for the Atmel ATtiny104 Xplained NANO. I have also created a series of lessons that use the ATtiny104 XNANO with the add-on board to provide a basic introduction to embedded electronics and programming.

The ATTiny104 XNANO next to the small add-on board I designed to
enable a series of lessons on embedded development.


In a previous post I examined the new ATtiny104 microcontroller from Atmel and checked out their evaluation board for it, the ATtiny104 Xplained NANO. I was very impressed by this little board. It has a programmer/debugger built in, allowing it to integrate seamlessly with Atmel Studio 7. You simply connect it to your computer with a USB cable to power the board, develop programs and connect to the USART. It is a great bargain at less than $5 USD.

It is not only suitable for evaluating the ATtiny104 but also for learning and teaching embedded electronics and programming. Certainly there are numerous Arduino and Arduino-like boards available for that task as well. This is just one more option that might be interesting if you need a very low-cost board that integrates with Atmel Studio for programming in standard C.

I designed a small add-on board for the ATtiny104 XNANO that includes a 5mm LED, a trimpot, and a photoresistor. The LED goes to one of the PWM-capable pins on the microcontroller, and the outputs of the trimpot and photoresistor circuit can be read using the ADC. These components combined with the on-board push button and LED allow for many lessons and projects to be completed. It's a very small and low-cost combo for learning or teaching embedded development.

The add-on board connected to the ATtiny104 Xplained Nano.


To support the use of the add-on board, I have created a 28-page guide with eight lessons on basic embedded programming. The lessons walk you through using various features of the microcontroller and add-on board, including: digital inputs and outputs, the ADC, PWM output, USART, and interrupts. They are designed for someone that knows a little about electronics and programming, probably with an Arduino, and wants to get a feel for programming in Atmel Studio in standard C.

The guide to support the add-on board includes eight lessons on basic embedded development.

Add-On Board Kits

The add-on board makes for a very nice first soldering kit. The PCB is cheap ($6 USD for three copies from OSHPark) and the parts are very common, through-hole components. You probably already have all of this stuff on hand. The part outlines and resistor values are shown in the silk screen of the board so you don't even need to consult a schematic while assembling it.

ATtiny104 Xplained NANO boards can be acquired from distributors such as Digikey and Mouser. The PCBs can be ordered from OSHPark. Finally, the parts can be ordered from an online vendor such as Sparkfun

Lesson #1 in the guide is soldering together your add-on board kit!


Let me say now that this is not a Kickstarter or anything like that. I'm not planning to sell these kits or make any money off of the guide. The add-on board is Open Source Hardware, and the guide is released under the Creative Commons Attribution-Share Alike 3.0 license. I hope that the board and guide are useful for learning a little bit about programming microcontrollers and embedded design, whether that is for an individual reading this blog or someone that might use the board for a workshop or class. Feel free to modify and redistribute the guide to suit your needs, as long as you attribute and share it back to the community under the same license. I have also shared the Eagle files for the add-on board if you'd like to customize it.

Check out the guide to learn more about the lessons and what you can do with this add-on board.

Shared as Open Source Hardware (OSHW)

ATtiny104 Xplained NANO Add-On Board: Order PCBs on OSHpark!

Eagle Files and Lesson Guide: Shared on Github

Schematic for the ATtiny104 XNANO Add-On Board

Parts list:
  • 10kΩ trimpot with knob
  • Small photoresistor (5mm width)
  • 5mm LED (color of your choice)
  • 470Ω resistor, 1/4 watt, 5%
  • 10kΩ resistor, 1/4 watt, 5%
  • (2) 12-pin 0.1” female headers (snap off from a strip of breakaway headers)
  • (2) 12-pin 0.1" male headers for the XNANO board

Note: There are no component IDs in the silkscreen, but the outlines and resistor values are shown to clearly indicate where the parts go.

Headers on XNANO: I have noticed that one of the capacitors on the ATtiny104 XNANO board is a little too close to the header pins. Male headers might not seat all the way flush against the board. Luckily there is an easy fix. Use a file to slightly round the bottom corner of the header where it hits the capacitor. Just a few swipes with the file will allow it to seat fully. Also, I used male headers on the XNANO board and female headers for the add-on board, but you can reverse that if you like.

After you finish the lessons and remove the add-on board, many additional
projects can be completed with the ATtiny104 XNANO.

Wrap Up

I hope that you find this small add-on board for the ATtiny104 XNANO and the lesson guide useful. If you assemble one and work through the lessons, or use them in a class or workshop, please let me know. Also, please post any questions and comments down below.

Thanks for reading!

- Dan W.