Tag Archives: microcontroller

PWM Dimmer for LED Lighting

Finished LED dimmer

I have recently moved to a new apartment and was looking for a PWM dimmer to control some 12V LED strips. I thought that should be easy enough nowadays but it proved more difficult than I thought. All I found either didn’t meet my requirements, were uggly or expensive. So I decided to build my own, tailor-made to my needs.

Finished PCB mounted below a shelf

 The requirements

  • Handle 100W @ 12Volts comfortably
  • Controlled by a simple on-board pot (no remote control or the like)
  • Affordable
  • No acoustic noise
  • Fine-grained control down to very low brightness levels

I’ll go through these requirements one-by-one.

Two LED strips below the shelf give a nice lighting on the desk

Handle 100W @ 12Volts comfortably

My LED strips suck up a bit more than 20 Watts per meter and there is a maximum of 4-5 meters of LED strips per dimmer so I need a power rating of around 100W. If you do the math you’ll find that there will be a maximum current of about 8.3 amps.

I don’t want this thing to get hot nor do I want to put a heat sink on it. So the total power dissipation in the dimmer should stay below, say, 1 watt. So if we use a single FET, we need a Rds-on of 14.5 milliohms. Thats not a lot but there are inexpensive MOSFETs that meet this requirement. And we can always parallel two or more of them if necessary.

And yes, there will also be some switching losses but they should be low given the modest switching frequency of an application like this.

PIC microcontroller with its power supply

 Controlled by a simple on-board pot

This is most likely the simplest way of controlling a dimmer but it’s surprisingly hard to find. A lot of commercially available dimmers come with IR remote controls nowadays. And some of the higher quality models expect a 0-10V control signal which means that you have to use an external pot which you have to mechanically attach somewhere. I would like everything on a single PCB to keep things simple.


I needed 3 of these things so cost was a factor, too. All the nicely-made dimmers I could find were priced at $50 and uppwards. Not that bad but I figured that I could make my own for a small fraction of this, perhaps $10.

No acoustic noise

We all know those dimmers that produce audible humming. Especially when dimmed somewhere half-way down. I hate it. Drives me crazy.

This proved to be more difficult to archieve than I thought. More on this later.

Since the power supply has 4 output leads, my dimmer has a 8x connector at its input

 Fine-grained control down to very low brightness levels

This is where most products fail miserably. Most of those remote-controlled things only have 8 brightness levels. And just about everything I found works linearly which makes very little sense if you ask me. We humans perceive brightness logarithmically, rather than linearly. So going from 1% to 2% seems the same as going from 50% to 100%.

Beefy mosfet and capacitor

Linear control will not give you fine control at the lower end. Ideally, you want to have an exponential transfer function from pot position to PWM duty cycle to compensate for the logarithmic nature of the human vision. I found the easiest way to do this was using a microcontroller. Furthermore, the ability to do all of this in software enables you to play around with it and find a transfer function that you’re happy with.

High granularity at the lower end also means that we need quite a bit of PWM resolution. The common 8-bit resolution translates to about 0.25% per step. Going from 0.5% (wich is about what I mean by very low brightness) to 0.75% is already quite a step. Many microcontrollers are capable of 10 bits which is 4 times better and probably good enough.

Yet another view

The design

At the center of my design is a 8-bit PIC microcontroller, a PIC16F1936. There’s not much special about this particular model, it’s just a type I’ve used several times before and still had some on stock.

A LM2931 provides the PIC with 5 volts from the 12 volts input voltage. I use the LM2931 as my standard 5V regulator. It’s pin compatible with the legendary 7805 but survives input voltages in the range of -50 to +60 volts making it very robust against transients.

A LM2931 generates 5V from 12V

The PIC controls a LM5111 dual FET driver that provides a powerful 12V gate drive to a pair of Infineon IPB136N08N3 N-channel MOSFETs. This is the same transistor that I’ve recently used for my Arduino Solar Charger Shield. Its an inexpensive (< $1), large SMD type with an exellent Rds-on of 11.5 mOhms.

There are several variants of the LM5111. It comes in inverting and non-inverting configurations as well as combinations of inverting and non-inverting. At Farnell, the the inverting ones were by far the cheapest so that’s what I’m using here. It doesn’t really matter since you can change the polarity in software as needed.

Pot and one of the output drivers

Why am I using two FETs despite the fact that one could easily handle the entire current? First, I’m driving two LED strips with this dimmer and using two transistors simplifies the layout so I have two outputs exactly where I need them. Secondly, the LM5111 is a dual FET driver anyway so I get the second gate drive for free.

Nice 2kOhm pot

I’ve provided each output with a generous 1.5mF capacitor in order to shield the supply from the ripple that is inevitably produced by the PWM. I’ve also taken care to use a cap with low serial resistance (ESR) and a high current rating. The Panasonic FR series fulfills both of these requirements while being good value for money. I thought this should be enough to avoid excessive ripple and therefore also acoustic noise.

Top side of the long version

The input to the PIC comes from a quite nice 2 kOhms pot that I’ve recovered from some scrap. There is also a voltage divider to measure the 12V input voltage. The idea was to only enable the output once the input voltage has stabilized but I found this to be a quite unnecessary feature when programming the PIC.

Bottom side of the long version

 The Layout

Top side of the short version

I’ve built the two different versions of this dimmer. The schematic is exactly identical for both of them, they only differ in their physical layout and board dimensions. I’ve just tailor-made them to their specific application so the pots are located in a handy position and the outputs are exactly where I need them.

Bottom side of the short verison

 Software and Testing

My first version of the software measured the voltage from the pot using the on-chip ADC and outputed an identical 2kHz PWM signal on both outputs. 2kHz should be enough to avoid visible flicker and seemed a reasonable choice. Everything worked but the power supply made quite a bit of noise over most of the brightness range. Worse than any commercial design. Even worse, there was an awful lot of flicker. Ouch.

Too much ripple producing lots of audible noise

Looking at the power supply output / dimmer input voltage on a scope if became clear that the two 1.5mF caps still allow too much ripple at this frequency.

The first thing I tried was running the two outputs out-of-phase. Since I’m using two FETs I have two independent outputs. So I can run them 180 degrees out-of-phase. Now, at  duty cycles below 50% it looks like I’m only driving a load half the size with a frequency and duty cycle twice as high. At precisely 50% duty the supply even sees a constant load at its output since exacly one LED strip is on at any point in time. At duty cycles above 50% the on-times overlap so the load only varies from 50% to 100% and with twice the frequency. As you can see from the scope screenshot below, this already helped a great deal but the problem was not yet resolved. So the natural thing to do was to increase the PWM frequency.

Running the outputs out-of-phase helps

At 8kHz, things already looked (and sounded) much better. Ripple and acoustic noise were much reduced but the supply was still audible at least in a quiet environment.

Increasing the PWM frequency to 8kHz almost solves the problem

So I moved the PWM frequency up as far as i could. Given the PIC’s 32MHz clock and a 10 bit resolution this was 31.25kHz. Now every last bit of audible noise was gone. Finally.

At 31.25kHz all the noise is finally gone

I then noticed that the phase shift was 176 degrees as opposed to the intended 180 degrees.

Phase shift is 4 degrees off

Not that this makes much of a difference in practice but I solved it anyway. I’ve implemented this phase shift by starting one PWM module at 128 and the other at 0 (we’re only talking about the 4 most-significant bits here, so the maximum is 255). The two instructions are on successive lines in my C code but 3 clock cycles are needed to process each of them so they are not enabled at the precisely same time. Starting the first PWM module at 131 has solved the problem as you can see below.

Now the phase shift is fixed

With these changes in place the flicker mentioned previously was also much reduced but had not yet disappeared. Looking at the voltages on a scope for a while the problem became clear. I was measuring the voltage from the pot at fixed intervals that had no connection with the switching frequency. So I was effectively measuring at random points in time.

I said that the input voltage now showed much less ripple but some ripple is inivitable. Some of that ripple is likely to somehow feed through to the voltage from the pot. That introduced noise in the value measured by the ADC which lead to variations in the duty cycle which was noticable as flicker.

I did two things to resolve this. First, I’m generating an interrupt signal (from the same timer as I use for the PWM) every 64 PWM cycles. In the corresponding interrup service routine (ISR) I read (and save) the ADC value and start a new conversion. This way I’m always measuring at the same point during the PWM cycle. So the effect of the ripple should be similar every time. I’m also averaging 32 measurements which further helps to smooth the value I’m using to calculate the duty cycle. So flicker is gone as well as you can see below.

After averaging the ADC readings, the duty cycle stays rock solid

Now for the transfer function. My first try was exponential. The problem with that was that it gave away too much of the pot range for very low brightness levels. I played around with this for quite some time and finally settled for a combination of linear (at the very low end of the range) and exponential (for everything above that). Also, two of my dimmers can be fully turned off by turning the dimmer all the way to the left. Their power supply is always on and the light is only controlled by the pot so I need to be able to really turn them off (not only down). The third one has a slightly different transfer function that only allows to turn it down to 2% or so. That one has its power supply controlled by a conventional light switch so I don’t want the pot to completely turn it off.

Same at lower duty cycles

 The result

After all, I’m very happy with the result. There is no noticable power dissipation on the board. There certainly is a bit of dissipation but the board doesn’t heat up noticably so I’d say its clearly below a watt.

The components have cost me around $10 per board. Some stuff like the connectors I have bought a flea markets, they can be surprisingly expensive through regular retail channels. The PCBs are home-made so they have cost me a considerable amount of time but not much in terms of cash.

LM5111-2M is the inverting variant

They are, furthermore, controlled by a simple pot, produce no audible noise and can be finely dimmed just as planned. So I can proudly state that all the requirements have been met.

If you’re in need of a dimmer and have a soldering iron and a bit of spare time I can only encourage you to build your own. It’s not too hard, needs only few components and is very doable on a prototyping board if you don’t want to etch or mill your own board.

As always, attached is a zip file with all the eagle files, board layouts, schematic as well as the software.

Arduino MPPT Solar Charger Shield – Testing

First tests are being performed on the Solar Charger Shield

In my last post I’ve introduced a proof-of-concept Arduino solar charger shield. I went through the hardware as well as the way it works – or at least is intended to work. It was prominently linked on dangerousprototypes.com as well as some other sites and got quite a bit of publicity as a result. Thank you all for sharing this post.

By the way: here’s an overview over all posts on this project.

DUT hooked up to my Constant Current Dummy Load

This time I’ll show you some results of the testing that I’ve done. The basic test setup is shown above: The solar charger is hooked up to my home-brew constant current dummy load, together with a pair of DMMs at the output in order to precisely monitor output voltage and current. For the input I’m relying on the lab supply to provide these measurements. And yes, the shield does its own measurements of both input and output currents and voltages. Once calibrated they are even quite accurate but I won’t rely on them for things as calculating the converter’s efficiency.

Vin=17V, no load

But first we need to see if our converter works at all. As the scope screenshot above demonstrates – it does. For all the tests shown in this post, the input voltage was provided by a lab supply set to 17 volts. So we’re not yet testing the software and its capability to draw just the right amount of current.

Vin=17V, no load

As you can see, since the converter can draw any (reasonable) current at the input, it provides the maximum voltage (set in software) of 13.8V at its output. In order to do that, the upper FET is on approximately 80% of the time. The signals all seem nice an clean and there is no noticable ripple at the output at 1V/div and no load. And the switching frequency is 62.5kHz (16MHz / 256) as expected.

Vin=17V, Iout=1A

At 1 Amp output current, the software has to increase the duty cycle somewhat to 82% (above) and even further to 84% at 2A (below). Besides that, everything still looks very similar under load conditions.

Vin=17V, Iout=2A

In my last post I’ve raised the question if the FET driver’s dead time of 540ns according to the datasheet is not a bit excessive. Well, let’s look at the dead time on the scope. First of all we can observe that the dead time of the IR2104 is in line with the data sheet. I don’t have it in front of me right now to check the min/max specs but the measured 522ns seem reasonably close to the theoretical 540ns.

The IR2104 has a built-in dead time of 540ns according to the data sheet. We’re measuring 522ns here – close enough.

From looking at the screen shot above, the dead time does seem a bit long. The reason dead time is introduced is to prevent shoot-through. If both FETs are on there is a short-circuit from the input to ground. Together with the input capacity and the FETs low Rds-on, very large currents could flow, possibly destroying the FETs and at least detoriating efficiency. So introducing a bit of time when both transistors are off seems reasonable. But too much of it also costs efficiency since current has to flow through the diode instead of the lower FET. The main reason for using a synchronous topology is to prevent this in order to gain efficiency. So obviously one has to find a balance. I think here we’re a bit far on the conservative side but never mind for now.

Let some current flow

So now that our converter is working, let’s take a look at efficiency. I’ve measured the efficiency at output currents ranging from 100mA to 2.6A in 100mA steps with the input voltage at 17V. I didn’t use the sense-wires connections on the lab supply so I had to compensate for the voltage drop on the input leads manually.

There was a drop of up to 220mV on the input leads so the voltage reading of the lab supply is not quite accurate

The results are quite impressive:

  • 95.5% @ 100mA (worst)
  • 96.9% @ 200mA
  • 97.9% @ 400mA
  • 98.1% @ 800mA (best)
  • 97.1% @ 1600mA
  • 95.7% at 2600mA

So the efficiency is constantly at a very high 95.5% and better over the entire current range of interest.

This little dummy load is really useful

The resulting loss is less than 1.6 Watts @ 2.6A out. As a result, the shield never gets hot, even when running at this power level for a while.

Note that this is quite a bit more power than the converter was designed for. 37W as opposed to the 30W I designed it for. The FETs could even handle much more. The limiting factor would likely be the coil reaching saturation. Unfortunately my lab supply doesn’t supply any more than 2.2A so I can’t push it any further.

Shield performs well even beyond 30W spec


One thing to note is that these efficiency figures don’t take into account the power consumed by the arduino, the display, the fet driver, current monitoring ICs and so on. This brings us to the last topic for now: The current consumed by the various components. I did these measurements mainly in order to understand how to limit power consumption in a later version. To me, this shield is only a proof of concept and so reducing power consumption was never an issue.

Basic test setup

Here are the results:

  • Arduino: 48.7mA
  • LCD backlight: 8.9mA
  • LCD excluding backlight: 1.148mA
  • FET driver (standby): 106.56uA
  • FET driver (62.5kHz, Iout=0): 2847uA
  • FET driver (62.5kHz, Iout=2.5A): 2937uA
  • Current sensors (each): 48.6uA

So the arduino itself is using up the lion’s share of current. Next comes the LCD backlight. Nothing unexpected so far. The LCD without backlight still consumes a considerable 1.15mA, no matter if it’s on or off. The FET driver uses around 2.9mA when on and only about 0.1mA when off. Output current only has a minor impact. The current sensors don’t use up much – less than 0.1mA for both.

Check out my next post for a closer look at the software or here for an overview over this project.

Arduino Ultrasonic Anemometer Part 11: Testing the new hardware

Today I’ll go through each part of my new Arduino shield to see if it performs as expected.

If you’re new to my Arduino-based ultrasonic wind meter project, you might want to click here for an overview: http://soldernerd.com/arduino-ultrasonic-anemometer/

When I first powered on the new shield, only two out of the four transducers worked. As it turned out, I had two different Direction signals on my schematic: one named DIR and one named DIRECTION. They should be one and the same signal but Eagle had no way of knowing about that so they ended up unconnected on the board as well. But luckily it was easy to fix with a piece of wire. After that, the circuit was quite ok. This was the first impression (with some comments of mine):

Overview of the circuit when first powered on

But let’s go through it step by step.


This was the main design flaw of the first version. Yes, it eventually worked but drew much more current than necessary. This one got the gain right the first time as can be seen from the screenshot above. Output amplitude was about 5.6V pp and the signal looked nice an clean.

So all I had to do was to tune the LC tanks to get them to resonate at 40kHz. The inductor has a 20 or even 30 percent tolerance rating and I can’t  measure it. So I had to start somewhere, see how it performs and adjust it from there. I started with a 15nF cap and used a signal generator to find the resonance frequency for each amplifier stage.

Amplifier stage 1 in resonance at 40.98kHz


Amplifier stage 2 in resonance at 38.78kHz

At resonance, the phase shift is exactly 180 degrees. Maximizing gain should give the same result but I found it easier to look at the phase shift. Above you see two screenshots: one with the first amplifier stage in resonance at 40.98kHz and one with the second stage in resonance at 38.78kHz.

From that you can calculate how much more or less capacitance you need. It took me 3 attempts to get it really right but the final result looks like this:

After some LC-tank tweeking the resonant frequency is at 40kHz now

Both stages are perfectly at resonance at 40kHz.

About the biasing: I’ve removed the 10k speed-up resistors R6 and R11. I guess they were unnecessary to start with and they lowered imput impedance too much. I noticed by the fact that there was a noticable voltage drop across the 100k biasing resistors R3 and R4. So while the emitter of the biasing transistor pairs was precisely 1V above ground as intended (I measured 1.015V), the actual amplifier’s darlington pair had it’s emitter only about 0.85V above ground. Not at all what I was looking for.

With the two resistors removed everything is fine. 1V emitter voltage for each of the four darlington pairs. And no measurable voltage drop accross the 100k resistors.

Zero Crossing Detector

Zero crossing detector at work

I had changed the comparator to a much faster type and this is the result.  Now it triggers exactly at the zero crossing, without any noticable delay.

Close up of the ZCD: Now it really triggers at the zero crossing

Before it triggered nowhere near the actual zero crossing because it always lagged behind so much. Now this problem is gone and the edges of the ZCD output are very clean and steep. If you zoom in even more you’ll see that  rise and fall times are only around 20ns and there is no overshoot and ringing.

ZCD: Nice, clean, fast edge

No excuses for the Arduino to not trigger accurately on them.

Envelope detector

The envelope before and after smoothing

I had changed the envelope circuit quite a bit. It has now two op-amp buffered low-pass filters. And this is what I get before the first stage (yellow), after the first stage (pink) and the final envelope (blue).

Envelope smoothing close-up

The first buffer has a gain of 2.5 set by the 15k and 10k resistors (R9 and R10). This has caused the op-amp to rail before the maximum amplitude was reached. I thought about reducing the gain but then decided to leave it as it is.

It doesn’t matter if we cut off the top of the envelope. All we care about is the rising edge, this is what we trigger on. We don’t care what happens after that. So the high gain gives us some more resolution in the area that we care about.

Capturing the rising edge of the envelope

I’m using the same fast comparator for the envelope detector as for the ZCD. And it works just as perfectly here. Above you see how it generates a perfectly clean output signal (pink) when the envelpe (blue) crosses the threshold (yellow).

As you can see, there is still a small amount of ripple in the envelope. I have set the -3db points of the filters quite a bit higher than in the first version: 15k plus 1nF results in about 10.6kHz. So I’m smoothing the envelope quite a bit less than I used to.

I might try increasing the 100k resistor at the input to maybe 150k. That would result in less saw-toothing at the filter input (ENV1 above). But for now I leave it as it is.

Signal routing / multiplexer

I’m now using the second, otherwise unused half of the 74HC4052 to route the PWM signal to the right buffer of the 74HC126. This works flawlessly.

What doesn’t work is routing the pre-biased received signals to the amplifier. Well, the signal does get to the amplifier but look at the shape of the amplifier input (yellow signal) in the overview screenshot at the very top. It gets pulled down to zero every time I change the input channel.

So I had to change that back to how it was in the first version. The unbiased signal goes through the multiplexer and  gets capacitively coupled into the amplifier where it is biased to the right level. But this time I don’t have the -5V supply at the multiplexer any more.

An unbiased 200mV signal passes the multiplexer without problem

Here I’m again using a signal generator to generate an unbiased sine wave with 200mV amplitude pp which is applied at the multiplexer input. As you can see above, it reaches the amplifier input in perfect condition.

Multiplexer_minus300mV 2
Biased to -300mV it still works

Even when I biased it to -300mV it passed almost unattenuated. Only when I increased the biasing to -700mV, the amplitude was cut in half:

At -700mV biasing we lose half the signal amplitude

So I’ve replaced the four capacitors at the multiplexer inputs (C16, C24, C25, C26) with zero-ohms resistors and placed one of them at between the multiplexer and the amplifier input. For this second part I had to do a bit of surgery on the board but nothing major.

Now the amplifier input looks ok:

Amplifier input looks ok now

Crosstalk / Mute signal

I’ve eliminated two of the three multiplexers in this design and was prepared to get quite a bit of cross-talk because of that. This is why I planned ahead and included a mute signal that lets me mute both the amplifier input and output.

Not much of a cross-talk problem

As it turned out, there was not much of a crosstalk problem. Yes, the received signal does pick up some (around 100mV pp) of noise from the transmitted signal but it doesn’t do much harm.

Cross-talk zoomed in

Most of the noise is high frequency spikes and they don’t make it trough the amplifier. Apart from that: We are never transmitting and receiving at the same time. Note that the screenshots above are with the mute signal disabled. So I probabely won’t use that mute functionality going forward. One singal less to worry about. And if I change my mind the circuit is still there.

Temperature sensor / Voltage reference

Not much of a surprise here. I’ve measured the voltage reference output at 2.4989 volts, very close to the rated 2.5V and well within specs.

The temperature sensor also works like advertised. But It seems to be significantly (several degrees) warmer than ambient. I’ve used a thermocouple to measure the temperature of the sensor and the board around it and really found it to be several degrees warmer.

I have placed it a bit close to the LED which heats it up a bit. The orange LED I’ve used turned out to be very efficient so it was very bright with the 330 ohms resistor. I’ve changed that resistor to 1k now and the LED is still quite bright and only consumes a third of the power. But it didn’t help much as far as the temperature sensor is concerned.

Seems the heat is not mainly coming from the LED. Which brings us to the next topic.

Power consumption

I’ve measured the current (at 12V) the arduino was pulling at its DC plug. Since the Arduino is using a linear regulator, current should be independant of input voltage. Anything above 5V is just disposed as heat.

These are my results:

  • Arduino + shield + display: 67.3mA
  • Arduino + shield: 61.0mA
  • Arduino only: 52.4mA

So the display is pulling 6.3mA and the shield another 8.6mA. Most of the current is used by the Arduino itself.

The power consumption of the shield makes sense: Every darlington pair is pulling 1mA, the LED uses about 3mA. Makes 7mA so far which leaves 1.6mA for everything else.

The Arduino is using quite a bit more power than I thought. At 12V this makes about 0.6 watts. Which is probably what’s heating up our shield and the temperature sensor with it.


I’m quite happy with the new shield. After a bit of soldering everything is working fine. So from now on, this will mainly be a software project. Here’s an update on that: http://soldernerd.com/2014/12/04/arduino-ultrasonic-anemometer-part-12-working-on-an-arduino-library/

Arduino Ultrasonic Anemometer Part 9: A new hardware

My first wind meter prototype is kind of working. The software will need improvement to make this wind meter into something really useful. But both hardware and software are basically functional and can be built up upon.

If you’re new here, you might want to check out the overview over this series of posts on the arduino-based ultrasonic anemometer: http://soldernerd.com/arduino-ultrasonic-anemometer/.

The new ultrasonic wind meter Arduino shield

The next thing I will do is re-design the entire hardware. Instead of two distinct boards with wires all over the place I will design a single, standard-sized Arduino Shield that can be stacked on an Arduino Uno. Just like any of those commercially available shields that add motor control, Ethernet or whatever. That will make the whole setup much smaller and simpler. And I hope this will also make it easier for others (like you?) who want to build their own.

This re-design is what I’m going to talk about today so I guess there won’t be much in the way of photos, just some schematics and board layouts. And I’ll put all the Eagle files on the overview page as a zip download. Here’s what I’ve changed and why:

Power supply

The first version used the (unregulated) Vin of the Arduino so it had a linear 5V regulator of its own. On top of that there was also a flying capacitor type inverter to generate a -5V rail for the analog multiplexer. Both of these chips have been eliminated. I’m now using the the 5V rail straight from the Arduino, there is just a 100uF tantal input cap. The -5V is no longer needed by the multiplexer. I’ll later explain why.

Signal routing / pulse generation / drive

The drivers are entirely new: I’ve replaced the two 74HC368 inverters with a single 74HC126 non-inverting line driver / buffer. It has four 3-state buffers, one for each transducer. The negative pin of each transducer is simply grounded in the new design. That costs us half the signal amplitude but simplifies things greatly. And our two-stage amplifier should have more than enough gain to make up for that.

As suggested earlier, there is only a single 74HC4052 left (instead of 3). We will get some crosstalk issues but we’re always transmitting or receiving, never both at the same time. Plus, the tuned amplifier filters out most of that high frequency stuff (such as square waves). And we have the option to mute the amplifier, this time both at the input as well as on the output. Not sure if we’ll need it, I’ll check once everything else is working.

Permanently grounding the negative pin of the transducers means we only have four signals to worry about. So I’m only using half of the 4052 to chose exactly one of the four signals. Y0, Y1, Y2, Y3 as inputs from the four transducers and Y as output that goes to the amplifier.

But why don’t I need the -5V anymore? Here is why. In my first design I routed the signal from the transducers straight through the 4052. Because this signal swings around ground, it will be negative half of the time and positive the other half. So I needed both a negative and a positive supply. Later, that signal was capacitively coupled into the amplifier where it was biased so somewhere around 2.3 volts. Now I already do the biasing before the 4052. So the signal will be positive at all times and hence there’s no longer a need for a negative voltage. I find this a really elegant solution, I just hope it will work 😉

There is still an Axis and Direction signal controlling a 74HC139 encoder generating the enable signals for the transducer drivers / output buffers. I had LEDs on these enable signals in the first version, these are no longer present. The software changes the axis/direction every 2ms so you won’t be able to see anything now.

The 74HC126 has active high enable signals (as opposed to the 125 which is otherwise identical). Since all but one enable signals are high, only one transducer can float freely. That’s our receiving transducer. That also means that the other 3 transducers are actively driven so only one of them must receive the PWM signal.

This is how I’ve solved this: As I said, I only used half of the 4052 for the tranducer signals. So the other half can be used to route the PWM signal from the Arduino to the correct output buffer. So the signal from the Arduino is connected to the input X and the outputs X0, X1, X2, X3 carry the signal to the different gates of the 74HC126. There is one potential problem: The outputs that are not selected are floating freely so there are 10k pull-down resistors on X0, X1, X2 and X3.

So from the 8 large ICs on the first version, only 3 are left. That saves plenty of board space so we can fit our circuit on a standard sized Arduino shield.

Same board from the other side


The basic design with two stages of tuned common emitter amplifiers with NPN darlington pairs has worked well so I’ll stick to that.

The main shortcoming of my first version was the 47uH plus 330nF LC tank (see part 4) so I’m changing that to 1mH plus 15.82nF. Same resonant frequency but much higher impedance. The inductor I’ve chosen has a dc resistance of a bit more than 16 ohms which will give a Q-factor of around 15 – comfortable for our application.

The main change is the biasing. A wind meter will be deployed outside so it is likely to see great variation in temperature. So the biasing of our amplifier and thus the quiscent current need to be stable over a wide temperature range. Two things make this a difficult task here: First, we’re using darlington pairs which means twice the variation in base-emitter drop. Second, our rather low operating voltage of 5 volts.

A common solution for difficult biasing situations is the use of a matched transistor to generate the base biasing voltage. And that’s what I’ll do here. Each stage has an additional darlington pair with collector and base connected for this purpose. So the collector will always be 2 diode drops (around 1.3V at room temperature) above its emitter. I want the emitter to sit 1V above ground and 1mA of quiscent current. So I add a 1k emitter resistor and a 2.7k collector resistor and get just that.

Base emitter drop will change by about -2mV per degree per transistor. So for a 50 degree increase in change in temperature, the drop accross our darlington pair will change from 1.3V to 1.1V – quite substantial. But quiscent current will only increase to 1.054mA and the emitter will then sit 1.054V above ground. A 5.4% variation for a 50 degree change in temperature. Not bad at all I think.

The last change to the amplifier is that I’ve put the gain limitting resistors (R7 and R12) in series with only the bypass caps (C5 and C10).  This will let me change the gain without affecting biasing which is given by R8 and R13.

Zero Crossing Detector (ZCD)

Almost no change here. I’ve only changed my comparator to be a Microchip MCP6561R. It has a worst-case propagation delay of only 80ns which is 100 times faster than the one I used last time. And it’s still cheap: CHF 0.43 at Farnell if you buy 10.

Envelope Detector

I told you earlier that I had some trouble with my last envelope detector which utilized a VCVS active low-pass filter. If I turned up the gain too much I got wild output swings. I found a screen shot of that:

Envelope going wild

Green is the amplifier output. We’re trying to get the envelope of that. But look what happens to the pink line when I turn up the gain. Nothing to do with an envelope. And I would like even more gain to make the envelope use (almost) all of the 0…5 volts range.

I haven’t really understood why that is. Suggestions anyone? The only thing I can think of is the rather narrow gain-bandwidth product of the op amp, 600kHz if I remember correctly.

So I’m using two op-amp buffers, each followed by a normal RC low-pass filter. So I can set any gain I want for the two buffers without affecting the signal shape. As an added benefit, I can now look at the signal after each buffer / filter. I’ve also changed the op-amps to be Microchip MCP601R. Less precise (we don’t need precision here) but fast (2.8MHz) and cheaper.

At the very input of the envelope detector I’m now using a second (not really matched but same type) diode (D2) to produce a bias voltage just a diode drop above ground to precisely compensate for the rectifying diode (D1) of the envelope detector.

The comparator at the output is now a MCP6561R as for the ZCD. Not that we need the speed here, just to use the same type.

Temperature measurement

Everything new here. LMT86 as a temperature sensor. Cheap, works from -50 to +150 degrees centigrade and is accurate to 0.4 degrees. Its output is between 1.5 and 2.5volts over the temperature of interest. It comes in a SC-70 package. That’s a bit small but still hand-solderable without problem.

There is no more op-amp to scale it up but I’ve added a rather precise 2.5V voltage reference, the ADR361. Quite an overkill maybe but I thought if you are measuring wind speed you are likely to also measure things like humidity, pressure, light intensity or something like that. So with the anemometer shield you get a precise and stable reference for all your measurements.


As you can see, I ended up changing quite a lot. When laying out the board I was surprised how easily everything fitted in. Not only did the fewer logic ICs save space themselves, it also greatly simplified signal routing. As you can see from the photos, I’ve already made a board. All the components have arrived as well so I’m ready to go ahead and build it up. I’m really looking forward to seeing how it will perform. I just hope everything works as planned.

All the board and schematic PDFs as well as the Eagle files can be found on the overview page as a .zip file: http://soldernerd.com/arduino-ultrasonic-anemometer/

That’s it for now, click here for the finished shield: http://soldernerd.com/2014/11/28/arduino-ultrasonic-anemometer-part-10-arduino-shield-ready/

Arduino Ultrasonic Anemometer Part 8: More Software

In my last post I talked about how to get the Arduino to output bursts of 40kHz pulses. Today I’ll go through the rest of the software so by the end of this post we’ll have a very rudimentary but working sketch for our ultrasonic wind meter.

Click here for an overview over this series of posts on the Arduino Ultrasonic Anemometer: http://soldernerd.com/arduino-ultrasonic-anemometer/

Overview over one round of measurements, i.e. each direction is measured once in turn.

If you’ve read part 7 of this series you will have noticed that all the key tasks are handled not in the main code but in interrupt service routines (ISRs). That’s fairly typical for an application like this one.

In this project, there are 2 ISRs:

  • TIMER1_COMPB Interrupt: It is triggered by Timer/Counter1. It sends 15 PWM pulses every 2ms and takes care of the Axis, Direction and Mute signals. Named TMR_INT on the screen shots in this post. This is what I’ve covered last time.
  • TIMER1_CAPT Interrupt: This is where all the measurement takes place. It is triggered by the envelope detector and zero-crossing detectcor. It reads the current value of Timer/Counter1. Named CAPT_INT on the screen shots in this post. This is what I’ve covered last time. This is mainly what I’ll be covering today.

The basic Idea of the software is as follows:

  1. Every measurement takes 2ms. It takes 375us (15 times 25us) to send the pulses plus 500us – 1500us for the pulses to arrive (assuming very extreme wind situations). So 2ms gives us plenty of time to finish our measurement.
  2. Shortly after sending the pulses we start listening and wait for the envelope detector to trigger TIMER1_CAPT interrupt. We save the current value of timer1, this is our coarse measurement of time-of-flight. We then set up interrupts to capture a rising edge of our zero-crossing detector (ZCD).
  3. A rising edge of our ZCD triggers TIMER_CAPT interrupt. We save the current value of timer1 and set up interrupts to capture a falling edge of the ZCD.
  4. A falling edge of our ZCD triggers TIMER_CAPT interrupt. We save the current value of timer1 and set up interrupts to capture a rising edge of the ZCD.
  5. Repeat steps 3 and 4 until we’ve captured 8 rising and 8 falling edges. Averaging these will give us a very precise measurement of the phase shift.
  6. After every measurement we change the direction we measure:  N->S, E->W, S->N, W->E, …
  7. We measure each direction 32 times until we calculate the actual wind speed. So one full measurement will take 4 x 32 x 2ms = 256ms. So we take about 4 measurements per second.
Overview over a single measuement

The screen shot above shows how a measuement proceeds: AXIS and DIRECTION are set depending on the direction to be measured. MUTE is driven high and 15 PWM pulses are sent. TMR_INT  triggers after every pulse in order to count them. After a short break, TMR_INT triggers again and turns MUTE off again. Eventually, the envelope detector (ENV_DETCT) triggers CAPT_INT. Shortly afterwards, CAPT_INT is triggered 16 more times by the zero-crossing detector (ZCD).

Close-up of the actual measurement.

There are 2 sets of variables to save all the measurements from the envelope and zero-crossing detector: At any point in time, one is in use by the ongoing measurements, i.e. they’re being updated. The other set represents the last set of measurements and is static. This second set can be used by software in our main loop to calculate the wind speed and direction. As I’ve said, capturing one set of measurements takes 256ms. So we also have 256ms to do all the calculations, send data (via USB or whatever), write the new measurement to the display, do some data logging or whatever else we have in mind. There is likely to be some floating-point math, square roots and tigonometric functions going to be needed to arrive at the wind speed and direction but 256ms should be pretty comfortable even for that.

A long series of measuements. Look at the cursors: It takes about 25ms to do our calculations.

This is what I’ve tried to show in the screenshot above: There is a signal named CALC which is driven high when a new set of measuements becomes available and driven low when the calculations are finished. So this signal shows you how much time the Arduino’s Atmega328 spends processing the data and writing to the display. As you can see, it’s less than 25ms so there is ample of room for more complex calculations or other tasks. We’ll definitely need some of that head room since the calculations performed so far are really just the bare minimum.

There definitely is still a lot to be improved, mainly how the raw measurements are evaluated to get the actual wind speed. But what’s more important to me at this time is that the basic idea/setup works. With no wind, my measuements fluctuate somewhere between plus/minus 0.3 meters per second without having done any calibration. It also reacts nicely when I blow a bit of air towards it.

I’ve changed the pinout many times while developing this software but I’m confident that I won’t have to change the pinout any more. So my plan is to now build version 2 of the hardware first. The entire setup will be much less complex (and prone to errors) without all the lose wires going back and forth between the different boards. Then, with the updated and hopefully final (or nearly final) hardware I’ll go ahead and finish the software.

Speaking of software: You can download the Arduino sketch from the overview page where you also find the Eagle files for both boards: http://soldernerd.com/arduino-ultrasonic-anemometer/. I’ll make it a habit to post all the download material for this project on the overview page so people don’t need to go through all the posts trying to find a certain file.

That’s it for today, continue here to my next post of this series: http://soldernerd.com/2014/11/25/arduino-ultrasonic-anemometer-part-9-a-new-hardware/

Arduino Ultrasonic Anemometer Part 7: Basic software

Today I’ll tell you how I got started with my software. If you’re new to my blog you might want to click here for an overview over my arduino-based wind meter project: http://soldernerd.com/arduino-ultrasonic-anemometer/

The first thing we’ll need to archive is to send a series of pulses at 40kHz which is the frequency the ultrasonic transducers work. They must be as precise and repeatable as possible since all our measurements depend on them. Any jitter and the like will affect our measurements. And the duty cycle should be 50%. So you really want to do them in hardware. The Atmega328 comes with a single 16-bit counter/timer (Timer/Counter1) as well as two 8-bit counters (Timer/Counter 0 and 2). We’ll need the 16-bit resolution so the choice is clear: Timer1.

Sending pulses using timer/counter1

Well yes, you could easily use one of the 8-bit counters to generate your pulses but you’ll still need timer1 for measurement. I’ve decided to do everything with just one timer so it’s going to be timer1.

How many pulses we should send is not so clear. I’m working with 15 pulses which works quite well but I’m not claiming it’s an optimal choice. But it is short enough to make sure we’ve stopped transmitting before the first sound waves reach the opposite transducer, even with heavy tail wind.

Since we have such strict requirements for our pulses, we can’t rely on any of those convenient high-level functions to set up our timer but have to study the Atmega328 datasheet and do it ourselfs.

This is what I have done:

pinMode(10, OUTPUT);
TCCR1A = 0b00100011;
TCCR1B = 0b11011001;
OCR1AH = 0x01;
OCR1AL = 0x8F;
OCR1BH = 0x00;
OCR1BL = 0xC7;

This is a short explanation of what it does: Set pin 10 as an output. Arduino pin10 is pin16 of the Atmega328. And that’s the pin connected to the output B of timer1. That’s line 1.

I then set up counter1 in FastPWM mode running at the full system clock frequency of 16MHz. Output B (that’s our pin 10 on the arduino) is set high when the counter starts at zero. It will be cleared (i.e. set low) when the timer reaches the value in output compare register B (OCR1B). The counter will be reset when (i.e.it will start at zero again) when it reaches the value in couput compare register A (OCR1A). I also enable an interrupt for when the timer overflows. More on that later. That’s lines 2 and 3.

Then comes the part where I actually set duty cycle and pulse with. I do that by setting the output compare registers. OCR1AH and OCR1AB are the high and low bytes of register OCR1A. So the final value in that register is 0x018F which equals to 399. That means counter 1 will count from 0 up to 399 before it starts again. That’s 400 steps. And here’s the math: The timer runs at 16MHz, our counter will overflow every 400 cycles. 16000000 / 400 = 40000. That’s exactly the 40kHz we’re looking for. The duty cycle is set to half that time by setting OCR1B to 199 or 0x00C7.

That’s it. We have a perfect PWM signal at exactly 40kHz and 50% duty cycle. Look at the screenshot above to convince you that this is exactly what we are getting.

But so far, the pulses go on forever. What we need is a way to turn the output signal off after 15 (say) pulses. One way of doing that is to count the pulses and turn the output off once the 15 pulses have been sent. That’s what the interrupt at overflow is used for.

In that ISR (interrupt service routine) I increment the variable pulse_count. Once pulse_count reaches 15 I know that all the pulses have been sent and turn the output off: TCCR1A = 0b00000011; The timer/counter will continue to run but the PWM output has been turned off.

For debugging/monitoring purposes, I set pin A5 high at the beginning of the ISR and low at the end. So I can tell when (and how long) the ISR is running by monitoring pin A5. Here’s what I get:

Pulses sent (yellow) and time spent in timer interrupts (blue)

The yellow signal is the PWM output (pin10) as before. The blue line shows the time spent handling the interrupt. I could then continue counting without sending any pulses and turn the output back on when I reach 80 for example. And at the very beginning that’s exactly what I did. But then the microcontroller has to handle an interrupt every 25us (microseconds) even when not sending pulses. That’s quite wasteful so I set a longer time period by increasing the OCR1A and OCR1B registers seen above.

Actually, I’m using this interrupt to do some other things as well such as setting Axis and Direction as well as the Mute signal and some other housekeeping. That wide blue pulse you see at the left side of the screenshot above does most of that, that’s why it is so wide.

Time consumed handling a regular timer overflow interrupt

Speaking of time consumed handling interrupts. It’s quite significant as you can see here: About 5 microseconds for a normal (just counting) interrupt. That’s 20% of CPU time while sending pulses (5us every 25us). That’s muuuch more than I ever imagined it to be. That’s about 80 instructions. I’m writing in C so I’ll have to check the assember code produced by the compiler to see what’s going on.

Click here for the next post of this series: http://soldernerd.com/2014/11/23/arduino-ultrasonic-anemometer-part-8-more-software/

Constant Current Dummy Load


This is a constant current dummy load. It’s controlled by a PIC16F1936 microcontroller. As you can see, it’s equipped with a 4×16 character LCD display and, less obvious, a rotary encoder with push button. It accurately sets the desired current via a 16bit DAC and reads both current and input voltage with a single-channel 16bit ADC each. Temperature is measured by the microcontroller’s internal 10bit ADC.


It needs a 6…16 volts supply for it’s own use. That’s what the upper pair of banana plugs is for. It can then burn up to 4.5 amps in the range of 0…22 volts. You can set any current from up to 4.5 amps in 1mA steps via the rotary encoder. By pressing the encoder you can set the ‘sensitivity’ of the encoder. There are 3 ranges: 1mA, 10mA and 100mA per (encoder) step. This way, you can quickly and precisely set any current you want.


There is a LM35 temperature sensor mounted directly to the heat sink. The temperature is shown on the display as well as used for protective purposes. The software automatically limits the current if the heat sink gets too hot. Using the temperature, current and voltage, it also calculates the die temperature of the two MOSFETs and makes sure their temperature rating is not exceeded. They have a temperature rating of 125 degrees centigrade and a die-to-heatsink thermal coefficient of around 4 degrees/Watt. So with higher voltages and currents it’s entirely possible to blow the MOSFETs even with moderate heat sink temperatures.


You might wonder what the Xilinx XC9572XL CPLD is doing on there. Well, this was my very first project involving an LCD display, my first project involving a rotary encoder, my first project involving external ADCs and DACs… My first project at a lot of things. So I appreciated having the flexibility to change some of the signal routing in VHDL. All the signals traveling from the rotary encoder to the microcontroller and from the microcontroller to the display travel via the CPLD so I can re-route those signals any way I want. Now the CPLD mainly takes care of the encoder

The 100mil header at the front is a I2C interface that let the dummy load communicate with the outside world. It was added later so i had to run some wires to get access to the I2C bus.

By the way, this is how I got the idea of building a dummy load: http://www.eevblog.com/2010/08/01/eevblog-102-diy-constant-current-dummy-load-for-power-supply-and-battery-testing/