Check your projects performance, setting or speed at a glance with this easy to build Arduino controlled duty cycle display.
BUILD TIME: 90 minutes
DIFFICULTY RATING: BEGINNER
THE BROAD OVERVIEW
Here's a simple project to provide a visual indication of the duty cycle of a waveform in your current project.
This project uses a 10 segment bar graph LED display along with a 328p microcontroller to give an indication of the duty cycle of the input signal.
HOW IT WORKS
While it’s true that the Arduino can generate 256 discreet PWM levels, this project shows these as 1 of 10 equal bands, IE 0% to 10%, 11% to 20% etc. The prototype uses an Arduino UNO, and a small breadboard to house a 10 segment LED bargraph with current limiting resistors.
Our Duty Cycle Indicator uses 1 of the 3 timer/counters of the Arduino CPU. There are 2 × 8 bit units (Timer/Counter0 and Timer/Counter2) capable of counting from 0 to 255 and a 16 bit unit (Timer/Counter1) that can count from 0 to 65535. The timer/counters can trigger interrupts based on a number of parameters. They are very versatile and quite complex. For further information, you can consult the 450 page datasheet on the Sparkfun website: https://www.sparkfun.com/datasheets/Components/SMD/ATMega328.pdf Timer/Counter1 is discussed from page 113.
The sketch uses Timer/Counter1 which is the 16 bit counter. The input signal is applied to pin D8 of an Arduino or pin 14 of a 328p, as used in the final build. The rising edge triggers the Counter/Timer2 to measure the pulse width. Internal counters are incremented once per clock cycle, which at 16MHz is each 62.5ns. Should the input signal be slow (less than about 250Hz) then internal overflow counters will automatically be used.
The sketch prints the input frequency, the duty cycle and illuminates the appropriate number of LEDs in the bar graph display.
WHAT MAKES A WAVEFORM?
If you are new to the Pulse Width Modulation (PWM) term or you are unfamiliar with different types of waveforms we will describe them in detail.
All waveforms have a number of defining characteristics such as frequency, period and amplitude. Regular waveforms such as sinewaves, triangle waves, sawtooth waves, and squarewaves can easily be described by these characteristics. A variation that we as makers encounter is a pulse stream or a Pulse Width Modulated waveform.
ANATOMY OF A WAVEFORM
If we observe the amplitude (the height) of a waveform over time we’ll see that it varies.
FREQUENCY: One of the most basic characteristics of a waveform is its frequency. i.e. how many cycles of the waveform occur in a given time, generally one second. The frequency of a waveform is defined in Hertz (sometimes referred to as cycles per second).
If our waveform repeats fifty times per second then it has a frequency of 50 Hertz or 50Hz. If this signal was electrical and amplified to a suitable level and applied to a speaker, we would hear it as a low bass humming sound. If the frequency was 10,000Hz (10kHz) we would hear it as an annoying whistle. Human hearing generally extends well beyond this point but deteriorates with age and other factors.
AMPLITUDE: The amplitude measures the height of the crest of the wave from the midline.
PERIOD: Can be defined as any point on the waveform to the same point on the next cycle. That could be from the maximum to the next maximum or from a minimum to the next minimum. As there is a maximum and a minimum, it follows that there is a middle point or that point where the waveform is heading neither higher or lower. A waveforms period can be considered as starting at this zero point, going to the maximum value, back down to the next zero point, to the minimum value then back to the next zero point.
WAVELENGTH: If frequency can be described as the number of complete cycles of a waveform per unit time, then the wavelength is the actual length of a one cycle and is measured in metres/second. A frequency of 20Hz has a wavelength of some 17 metres in air at room temperature and 1 atmosphere of air pressure.
The wavelength of visible light varies from about 700nm at the red end of the spectrum to roughly 400nm for violet at the higher frequency end.
PHASE: Refers to the position of one waveform compared to another. Let’s say we have a 1kHz sinewave. Its peak (maximum) occurs at a certain time. Now let’s add a second 1kHz sinewave and make it’s peak occur at the same time as the first sinewave.
These two waveforms are said to be in-phase. Now, let’s change the 2nd waveform such that the 2nd sinewave’s peak occurs at the time that the 1st sinewave’s minimum occurs.
This is referred to as the two waveforms being out of phase, and in particular, 180° out of phase. Phase difference is not restricted to 180° but can be any amount.
FUNDAMENTAL AND HARMONICS
The actual frequency of a waveform is its fundamental frequency. A sinewave of frequency 1kHz has a fundamental of 1kHz. Harmonics may occur at multiples of the fundamental frequency.
A sinewave of 1kHz would have a 2nd harmonic of 2kHz, a 3rd harmonic of 3kHz etc. Harmonics can be referred to as even or odd harmonics. In our example above with a 1kHz fundamental, harmonics at 2kHz, 4kHz etc are even harmonics. Harmonics at 3kHz, 5kHz etc are odd harmonics.
Harmonics are very useful when synthesising sounds and especially musical instrument sounds. Fundamental even.
WHAT IS A SINEWAVE?
Let’s consider the most basic waveform, the sinewave. Sinewaves are part of nature. Our 240V AC mains is transmitted as a sine wave. Both sound and light travel in sinewaves too although via very different mechanisms. We hear sound as variations in air pressure pushing on our eardrums. Light is perceived by the eye as a chemical reaction in the retina which then generates electrical signals interpreted by the brain.
A sinewave is generally represented as starting at a 0 point then increasing to its maximum value. From there, it gradually decreases its value, returning to the 0 point and progressing to its minimum value then rising gradually again to the 0 point. This represents one cycle. It recurs at a regular interval. This smooth transition follows the laws of trigonometry (trig). You may remember trig from school. Trigonometry uses concepts such as sine (sin), cosine (cos) and tangent (tan). Without going into too much detail, a sinewave can be drawn by computing (or looking up) the sin of angles from 0 degrees to 360 degrees. Refer to the figure below.
If you were to hear a sinewave played through a speaker it would sound smooth and clean. The human ear can distinguish various frequencies easily.
OTHER TYPES OF WAVEFORMS
Many other waveform types exist. For example, the triangle waveform has a steady linear rise from minimum to maximum and back to minimum again. The sawtooth waveform has a steady rise from minimum to maximum but then the amplitude drops quickly to minimum and repeats.
A squarewave by definition has an amplitude that varies from minimum to maximum instantly, stays at the maximum amplitude for some time (the mark interval) then instantly drops to the minimum amplitude for the same time (the space interval) as the mark interval. This is known as a 50% duty cycle.
In reality, squarewaves are not instant. The amount of time that is required to go from minimum to maximum is known as the rise time. Similarly, the fall time is the time required to go from maximum to minimum.
An ideal square wave would have a rise and fall time of zero. Depending on the use of the squarewave this may or may not be critical.
The part of the squarewave that goes from minimum to maximum is known as the leading or rising edge. The part of the squarewave that goes from maximum to minimum is known as the trailing or falling edge.
If you were to hear squarewaves reproduced via a speaker, they sound harsh to the ear.
As we know, a squarewave has the same mark interval as its space interval. If we have a waveform with say a mark interval of 1 second and a space interval of 2 seconds, then this is not square. It could be considered to be a rectangular waveform or a pulse stream. This is effectively what PWM means. We can vary the width of the mark interval compared to the space interval. The frequency doesn’t need to change to achieve this.
It can be shown that a square wave is composed of the fundamental and all odd harmonics. Similarly, other waveforms are composed of a fundamental and various harmonics.
In electrical terms, noise can be defined as a signal composed of random amplitude and frequency. Noise of this format is referred to as white noise.
Pink noise has less high frequency components. These various noise types can be used to test sound systems, to mask background noise and as sleep aids.
WHAT IS MODULATION?
We now know a lot about waveforms, pulse streams, pulse widths, duty cycle etc, but what is modulation? Modulation refers to putting some sort of data value into or onto a carrier waveform. The carrier amplitude or frequency is changed by various means to carry the data or audio signal.
When we tune our radio to one station or another we are selecting the carrier frequency of the radio station. Older readers will be familiar with AM (Amplitude Modulation) radio. The AM radio station transmits a constant carrier frequency (broadcast radio in Australia generally uses 526.5kHz to 1605.5kHz), which then has its amplitude varied (modulated) by an audio signal.
FM or frequency modulation uses a carrier frequency which is not fixed but varies depending on the applied audio signal.
Pulse width modulation (PWM) varies the pulse width of a fixed frequency signal in response to some input.
PWM is now very much a mainstay of digital electronics, but it has been used in many applications for some time.
HOW IS PWM USED?
Very basic use of PWM could be controlling the brightness of an LED. If the mark interval is long, the LED will be illuminated for a longer time than if the mark interval was shorter. This then changes the LED brightness.
Though we should clarify, it actually changes the "apparent brightness" of the LED, rather than the LED brightness itself. For that, we would require adjustment of the current.
The reason the LED appears to vary in brightness is a combination of behaviours between our eyes and brain.
If you were to film an LED with an ultra high-speed camera then playback the footage at normal speed, you would see it switching on and off.
PWM is used in switching power supplies where it is used to vary the on time of a transistor. A longer on time will provide more power, whereas a shorter on time will provide less power, but the peak voltage remains the same.
Appliances with large DC motors such as cordless drills use PWM to provide variable speed, while retaining torque. The humble DC motor and PWM have long been friends, and will likely remain so for some time.
There are many other types of modulation too, which we'll discuss another time.
More sophisticated uses of PWM would be to encode a data value. An Arduino can generate a squarewave with a duty cycle of 0% (always off) to 100% (always on).
In digital electronics, we often deal with byte values, that is 8 bit values. These have a minimum of 0 and a maximum of 255. These values could be directly used to produce a PWM signal that would convey this value.
A corresponding PWM decoder could reproduce the received data stream. This system could use one wire (and a ground) to transmit 256 different values.
But alas... we're getting a little far afield from our project.
The Fundamental Build:
|Parts Required:||Jaycar||Altronics||Core Electronics|
|1 × Arduino UNO||XC4410||Z6240||CE05629|
|1 × Bargraph LED (or 10 × LEDs)||ZD1704||Z0966||ADA1921|
|10 × 330Ω 1/4W Resistor||RR0560||R7040||COM-11507|
|1 × Breadboard||PB8820||P1002||CE05102|
* Quantity required, may be sold in packs. Prototypying hardware may also be required.
We used a breadboard to make the build straightforward. Follow the Fritzing diagram shown above to wire up the circuit, along with the following step-by-step instructions.
Start by running two wire links to join the top and bottom power rails on the breadboard together.
Next, insert the LED bargraph across the channel that runs left to right across the middle of the breadboard. LEDs only work in one direction, so you need to install the bargraph in the correct way. The anode (+) side of the bargraph is usually indicated by a beveled edge on the display, as shown in the Fritzing diagram above. If your bargraph doesn’t have the beveled edge you can insert it in either direction, then turn it around if it doesn’t illuminate when we get to the testing section below.
You can now insert the 10 × 330 Ω current limiting resistors. These can be inserted in either direction, and you can trim their legs shorter to make them sit flush on the breadboard. Insert one end into the positive (red) power rail at the top of the breadboard and the other leg inserted into the breadboard opposite each LED in the bargraph display.
Power to the breadboard is provided by your UNO, which you need to power up from a USB port or power bank. Run a jumper wire from the positive rail on the breadboard to the pin on the UNO marked as 5V. Next, run a jumper wire from the GND pin on the UNO to the negative rail on the breadboard.
Run the ten jumper wires from the LED bargraph to the corresponding pin on the UNO.
Finally, we’ll run the input wires between the breadboard and the UNO. The positive input wire goes to pin D8 on the UNO and the ground wire to the negative rail on the breadboard.
You will need to download the DutyCycleIndicator.ino file from the Resources section on our website and upload to the UNO using the Arduino IDE.
If you are interested in learning how the code works then read on, otherwise you can skip to the following Testing section.
Firstly, you will notice that we decided to use the built-in timer/counter hardware of the 328p instead of using the Arduino pulseIn() function. In a previous project we found the pulseIn() unreliable.
We use interrupts to start the timing because the input pulse stream can be unpredictable, Initially, we get an interrupt on the leading edge of the pulse. When this is detected we set up to be interrupted again on the trailing edge.
The time between these two edges is the mark time. We get another interrupt on the next leading edge which signifies the end of the first pulse and initiates another timing cycle.
Internally, the 328p has 3 counters all clocked at 62.5ns intervals. When the interrupts occur we read the value of the appropriate counter which will be some multiple of 62.5ns, and do some maths to determine the duty cycle. Now that we have the width of the mark, and the space, we can easily determine the ratio and hence the duty cycle.
Some simple maths determines how many of the 10 GPIO pins to pull low to illuminate the correct number of LED segments.
Apply power to the UNO by connecting it to an available USB port on your computer or USB power adaptor.
The LEDs should perform a self test at power up. They cycle on 1 at a time then cycle off again.
If the LED bargraph doesn’t illuminate you may need to switch it the other way in the breadboard.
The Complete Build
PWM Duty Cycle Indicator
|Parts Required:||Jaycar||Altronics||Core Electronics|
|Atmel 328p Microcontroller (with Crystal and 2 × 22pF Capacitors)||ZZ8727||Z5126||CE05190|
|1 × LM2940CT-5 Voltage Regulator||ZV1560||Z0592||-|
|1 × 5.1V Zener Diode||ZR1403||Z0614||COM10301|
|1 × 1N5819 Schottky Diode||ZR1020||Z0040||-|
|1 × Bar Graph LED||ZD1704||Z0966||ADA1921|
|1 × 5mm Red LED||ZD0150||Z0800||COM-09590|
|1 × 100Ω 1/4W Resistor||RR0548||R7034||-|
|11 × 330Ω 1/4W Resistor||RR0560||R7040||COM-11507|
|1 × 390Ω 1/4W Resistor||RR0562||R7041||-|
|1 × 10kΩ 1/4W Resistor||RR0596||R7058||COM-11508|
|1 × 68kΩ 1/4W Resistor||RR0616||R7068||-|
|1 × 100kΩ 1/4W Resistor||RR0620||R7070||-|
|1 × 1MΩ 1/4W Resistor||RR0644||R7082||PRT-14494|
|1 × 1uF 63V Electrolytic Capacitor||RE6032||R4718||CE05268|
|1 × 220uF 16V Electrolytic Capacitor||RE6158||R4847||CE05149|
|1 × 100nF Ceramic Capacitor||RC5360||R2865||CE05188|
|2 × 22pF Ceramic Capacitors||RC5316||R2814||(CE05190)|
|1 × 16MHz Crystal||(ZZ8727)||V1289A||(CE05190)|
|1 × 28 pin IC Socket||PI6510||P0571||-|
|1 × Prototyping Board||HP9558||H0719||003-PROTO777|
*Core have a resistor pack (CE05092) with values to suit this project, except 390Ω.
Breadboards are great for testing the theory, but this build really needs a PCB to be truly useful. For this, we have developed a custom PCB. We've milled ours using the Bantam Tools Mini Desktop PCB Mill, but as a single sided board, so you can create it however you like. The gerber files are in the digital resources also.
The PCB differs from the prototype in that it will work on 12V systems too. This is a very useful feature, since many motors, H-bridge drivers and such, are also 12V compatible. So you'll notice some extra hardware on the PCB that isn't on the prototype.
This extra hardware is key to ensuring the longevity of the project, but often the same considerations aren't required for prototyping where power supplies are often current limited, and the build is usually kept for a fraction of the time a full project would be.
Building the PCB
We milled the prototype using our Bantam Tools Desktop PCB Milling Machine, which we created as a single-sided board and manually created the three top-side links. If you’re having your PCB commercially produced, you won’t have to do this (and you’ll benefit from solder masking and overlay too).
Check your PCB for broken tracks, corrosion, or other manufacturing defects. Give it a good clean with some isopropyl alcohol or circuit board cleaner, to help remove any grease or residue that may exist. This will help reduce the incidence of dry joints and other problems.
Use the lowest temperature possible for the solder you’re using, to help avoid overheating the PCB and components, which can be easily damaged with excessive heat.
As with all PCB builds, we follow a hardware, passives, semiconductors type construction pattern. This means you should start with the pin headers and IC sockets. Then move to the resistors and capacitors; take care with the orientation of the electrolytics. Next, install the diode and the voltage regulator. Install the crystal flush with the PCB.
Now is a great time to run some tests to check for any major issues before we install the ICs and microcontroller.
Before we install the microcontroller, the most fundamental test is to check that we have power where we expect it, and not where we don't.
Apply power to the DC socket on the PCB, anything between 5-15VDC is catered for. Take care of the polarity.
Using your multimeter, test to ensure that you have 5V between pin 7 (Vcc) and pin 22 (GND). There is a ground on pin 8 also, but sometimes it's difficult to get multimeter probes on to IC sockets one pin apart.
This step is especially important if you're using a power supply higher than 5V, which can easily and rapidly smoke your microcontroller.
Once you've verified you have 5V and only 5V on your IC socket, you can install your ATmega. If you completed the prototype, you can use the coded chip from that.
Take care with the pins and the orientation of the chip. While they're fairly robust chips, you should take reasonable static precautions when handling, to avoid damage.
Even touching a grounded appliance such as a metal computer case, lab power supply, or water tap, will discharge the majority of static charge on your hands.
You may like to build a case for this project. We haven't tackled one here, since it's likely to end up in all sorts of different applications.
A good step in finishing is to create a reliable way to connect your input to the PWM signal. Depending on your preference you may like to use an RCA or BNC socket, allowing you to make your own cable for easy connection to whatever circuit you're testing.
You may actually like to install the project on to a large motor to check loads visually. If you're planning a permanent installation, omitting the signal input connector for a hard-wired connection would be prudent.
WHERE TO FROM HERE?
We have kept the display simple with a 10 LED display, but you could modify the circuit to display the duty cycle on an LCD or OLED screen. However that brings us to an interesting point... our design considerations.
You may actually wonder why this project is based around a 328p? After all, it does feel a little excessive sometimes. In reality it came down to cost. We could have used a simpler microcontroller, and produced a binary or serial output.
We reviewed all of these options, and once factoring the cost of another IC to drive our LED bargraph, we quickly found ourselves exceeding the cost of the microcontroller we were trying to work around in the first place.
At the very least, the few dollars saved using something simpler were quickly eaten up with a discrete chip, and there was little to gain.
That said, we do have an entirely discrete version which produces a similar output. There is no cost advantage in not having the microcontroller on board, which we may publish at a future date.
One benefit however of the microcontroller approach, is the ability to instead use an LCD or other display without much change. Especially if you're using an I2C type display, you can break out to the display with a few connections, and update the code to accommodate. Using something such as an intelligent display from 4D Systems, you could also create a stunning visual display from the results.