Category Archives: Arduino Ultrasonic Anemometer

My main project at the moment. I’m building a ultrasonic anemometer (wind meter) based on an arduino uno.

Ultrasonic Anemometer Part 20: Standalone Anemometer Design

Last time I outlined my reasons to ‘go digital’ by adding a powerful on-board microcontroller and designing a standalone wind meter.


In the weeks that followed that decision I tried to find a suitable microcontroller and to design a prototype. Today I’ll show you the result of that work.


I looked at various series of microcontrollers from different manufacturers and finally decided to go for the Microchip PIC32 series. It offers everything I could possibly ask for: 32 bit architecture, inexpensive, vectored interrupts, integer division, any interface you want (depending on the model of course) , available in large, low pin count, hobbyist friendly packages and so on.


As you can see above, the model chosen for my prototype is a PIC32MX220. This is low to mid-end representative of this series but even so the specs are quite impressive. CPU clock up to 50MHz, one instruction per clock cycle, full-speed USB 2.0, 32kB flash, 8kB RAM and all of that in a SOIC28 package at a price of CHF 3.58 in single quantities.


After having chosen a chip the next task was to come up with an actual design. I took my anemometer driver design and tried to integrated the new PIC32. That driver circuit had performed extraordinary well so I changed very little. I left away the RELEASE signal since my tests had shown it to be unnecessary. I also replaced the LM5111-1M mosfet drivers by LM5111-2M. The difference is that the 2M is inverting while the 1M is not. The reason for changing this is because the 2M is available at a significantly lower price of CHF 1.35 vs CHF 2.25. Not a big deal if you just build a single prototype but I thought it might be smart to change this anyway. This also required some resistors to be changed from pull-downs to pull-ups. Except these details everything stayed the same with the drive circuit.


I also had to re-design the power supply since the PIC needs a 3.3 volt rail as opposed to 5 volts in the driver test circuit. Since I had to re-design it anyway I also downsized the power supply somewhat. I’ve otherwise resisted all temptations to use smaller components but the power supply was just a bit too big with the two  SOIC8 chips and four size C tantalum caps.

The prototype now uses an MCP1755 linear 3.3V regulator in a SOT23-5 package with a 33uF size B tantalum cap at its input and a 10uF 0805 size ceramic cap at the output. A TCM829  (also in a SOT23-5 package) and two more 10uF caps produce the -3.3 volts output. So there is a total of three supply rails: +12V, +3.3V and -3.3V.


A major challenge was to make do with the very limited number of I/O pins on the PIC. 28 pins seem like a lot for the task at hand but plenty of them are already used for things like supply voltages and the like.

In the end I managed to still get three independent interfaces to the outside world: USB 2.0, I2C and SPI. All these interfaces as well as just about any other signal of interest is easily accessible from one of the numerous 100mil headers along the edges of the board.


The amplifier still uses a LMC6482 dual op amp , now running on a+/- 3.3 volt supply. The first stage amplifies the ground-referenced input signal by a fixed factor (currently 11 but this might change). The output signal is then biased to 1.65 volts and amplified once again. This time the gain can be adjusted digitally via a MCP4561 I2C digipot.


Before I forget: The PIC gets its system clock from a 8MHz crystal. That might seem low but there are two (variable)  PLLs inside the PIC that (together with a number of pre- and post-scalers) let us produce the 48Mhz signal needed for USB as well as a reasonable clock speed to run the CPU and peripheral bus on (probably also 48MHz but we’ll see).


The board layout proved to be a bit tricky because there isn’t that much space on the board and I had quite clear ideas where I wanted certain headers to be. So I was more than happy when all the traces were finally laid out.

As you can see, the PCB is already milled and the vias soldered. I can’t wait to build this thing up and start to do some programming. That will be the topic of my next post.


As always, a zip file with the eagle files and PDFs of the schematic and board layout can be found on the overivew page.

And here‘s the finished board.

Ultrasonic Anemometer Part 19: Testing the Analog Circuit


In my last post I went through the design of the analog part of the ultrasonic anemometer. Today we will see how the circuit designed last time performs in practice.


Active Full Wave Rectifier

Let’s first look at the active full-wave rectifier. As a first test I fed the input with a 40kHz sine wave from the scope’s signal generator. Here’s what I got to see on the scope.


The input signal is shown in yellow. The pink signal is calculated as the absolute value of the input and is what we are trying to archieve. Finally, the blue signal shows what we actually get on the rectifier’s output. What do you think? The basic wave form is obviously right but the precision leaves quite something to be desired.  So I tried the same setup with an input signal 10 times slower, i.e. 4kHz.


As you can easily see, things look much better at 4kHz. That doesn’t make it much better for us since we need it to operate at 40kHz but there doesn’t seem to be anything fundamentally wrong with the design per-se. I think a faster op amp might be that is needed to make this thing work properly at 40kHz, too.

Zero-Crossing Detector


The zero-crossing detector is by far the simplest element of this circuit and has hardly changed since the Arduino anemometer shield. It’s output is shown in blue above. It works just as expected, no surprise here. Well, in the end it’s just a comparator so the sources for error are limited.

Peak Detector Sample And Hold

The input to the peak detector is the rectifier’s output so we should expect to see at least some inaccuracy carried over from the rectifier.

Below is what I got. Again, yellow is the 40kHz sine wave input. Blue and red are the peak detector of the positive and negative half-wave, respectively. Green is the output, i.e. either the blue or red singnal as chosen by the 2:1 multiplexer.


The good news is that the circuit basically works as designed. Each peak detector gets zeroed at just the right time. From the screen shot above one might even conclude that the peak detector is fairly accurate. Both half-waves show very similar amplitudes and the output is nicely held stable during the hold period. No droop is visible at least at this level of magnification.

Once you zoom in, things start to look less pretty. There is in deed no droop but the opposite. The output signal rises during the hold period. If you look closely in the screen shot above you can even see it – the segments of the green signal are slightly rising. We’re talking  maybe 10mV here, far from dramatic but still.



My conclusion is as follows:

  • Zero crossing detector: perfect
  • Active rectifier: poor performance as is but can probably be fixed with a faster op-amp.
  • Peak detector: ok but not good enough. might need lots of trial-and-error to improve it.

I have mentioned in a previous post that I’m still unsure if I should stick to the predominantly analog signal processing or if I should make the switch to a more contemporary, digital, DSP like approach. After having spent an evening or two testing and tweeking this circuit the answer became clear – go digital.


If you’ve followed my blog for even just a short while you have likely noticed that I enjoy designing and building hardware.  Probably more than I enjoy writing software. But there are several good reasons to to more in software and less in hardware when it comes to this project.

  • The circuit as described above works kind of. But it might take a loooong time to improve it until it really performs well. Chances are that it will never perform as well as I’d like it to.
  • Board space. All this circuitry takes up considerable board space. A later version might use smaller components but this thing will always take up quite a bit of space – maybe a third of the total board area.
  • Even with most of the heavy lifting done in hardware the Arduino is likely not fast enough. We’d need to sample the amplitude at 80kHz which is out of reach for the Arduino’s Atmega328 even when sacrificing some resolution.
  • Further development. Chosing a digital approach enables users to actively contribute to the further development and improvement of this project.
  • Versatility: Eqiping the anemometer with a dedicated microcontroller makes this project much more versatile. It no longer has to be Arduino specific. If you’re an Arduino lover I promise you it will always be Arduino compatible. No need to worry. But equiping it with a easy-to-use SPI or I2C interface makes it useful beyond the Arduino community.
  • Cost.  My analog design uses two op amps among other things. Precision op amps are relatively costly components. It’s not an expensive circuit but it will always cost several dollars for the components alone. And improving the circuit is unlikely to make it cheaper.
  • Processing power is cheap. You might rightly say that a few bucks is not a lot of money to spend on some nice analog circuitry. I fully agree. But one can buy a lot of processing power for far less money nowadays.


Let me elaborate on some of these points:

Versatility: Arduino Only vs. Anyting, including Arduino

The arduino is a great platform with a great user community. But the Arduino Uno might not be the best choice for this project. A on board microcontroller gives user the option to use this anemometer from whatever platform they chose. Besides: An arduino is a very expensive device even when compared to a quite high-end microcontroller.  32-bit microcontrollers running at frequencies of 40MHz and higher are available for less than 2 or 3 dollars even in small (say, 10 pieces) quantities.  More advanced models might cost, say, 5 dollars.  In comparison, an Atmel Atmega328 as used on the Arduino currently costs CHF 3.10 (USD 3.18 at the time of writing) at Farnell. Not really value for money if you ask me.

Community Driven Developement

There are lots of creat coders out there. I can write decent code but there are plenty of people way better at that than I ever will be.  I see this as an opportuinity to greatly improve this project. Once I get this thing up-and-running I’d like to build a small series and let users share their experience and contribute to the code. Have an idea on how it could be improved? Try it yourself if you have the skills. Share your code if it works. Or share your thoughts and ideas if writing emedded softwar is not for you. So the anemometer could get better and better without having to get new hardware. Just update the firmware.

Next steps

In the weeks to come I will work hard to find a suitable microcontroller and to design and build a board with all that is needed for a stand-alone ultrasonic anemometer.

It’s now ready, click here.

Ultrasonic Anemometer Part 18: Analog Signal Processing

20160320_AnemometerAnalog_001Recently, I’ve sucessfully tested the new driver ciruit for my ultrasonic anemometer. It performed even better than I expected and I will be happy to use it pretty much as it is.

By the way: If you want to get an overview over how this project has developed over time check out the overview page. If you’re more interested in my latest design, this link will take to my new attempt.


So we have a circuit that can send powerful ultrasonic pulses from the right transducer, receive the signal from the opposite transducer and route it through an amplifier. The next task is to tell the time-of-flight from the received signal. A contemporary  approach would probably involve some sort of DSP and software. My last approach used some analog circuitery to detect the zero crossings as well as the envelope of the received signal. Since most of the heavy lifting was done in hardware, a simple 8-bit microcontroller like the one on the Arduino UNO could be used to do the measurements.

For my new approach I haven’t quite decided which route to take.  To me they both have a certain appeal. And over the last year or so I’ve had quite some ideas on how to process the signal in hardware so I’ll give it a try and see how it works out.  In this post I’ll go through this new circuit and explain how it works (or is supposed to work) step-by-step.


The zero crossing detector (ZCD) is almost identical to to my last design. The amplifier output is biased to half the positive supply voltage and fed into a fast comparator (Microchip MCP6561R). On the comparator’s output we get a precise digital signal indicating if we are currently looking at the positive or negative half-wave. Right at the logic edge we observe a zero crossing which can then be used to very precisely determine the phase shift relative to the transmitted singal.

The more challenging part is to tell the absolute phase – this is where my last project was only partly successful. It used an active low-pass filter to get the envelope of the received singal. This envelope was then compared to some threshold and the time from the transmition of the singal to when the envelope exceeded the threshold was measured. With plenty of averaging this gave a usable but far from perfect indication of absolute phase. So this time I’ll try something entirely new.


The amplified singal is first run trough an active full-wave rectifier as found on page 257 of Horowitz and Hill’s 3rd edition of Art of Electronics. It uses two op amps as well as some resistors and diodes to produce a singal that corresponds to the absolute value of its input. The two op amps come in a single package. It’s the same type as for the amplification stage of the driver circuit – a Texas LMC6482.

Now the rest of the circuit is a bit more adventurous. It attempts to produce a signal that corresponds to the peak of the previous half-wave. So it is steady during each halv-wave period and should give a (hopefully precise) indication of the amplitude of the received signal. This singal can then sampled by an ADC at 80kHz triggered by the zero crossing detector. 80kHz is not that fast for a (say) 10-bit ADC and definitely much slower than what we’d need if we sampled the amplified signal directly.


The advantage of measuring the amplitude is the following: We can find the peak of the amplitude in simple software and use the time when the peak occured to find the absolute phase. So we are no longer dependant on the absolute amplitude (as we were with the envelope detector approach) but only care about when the peak in amplitude occured. I think (hope) this is a much more reliable approach.

In order to find the peak of each half-wave I use a pair of simple diode-plus-capacitor peak detectors. One is held stable (“hold”) and fed through an op-amp buffer to minimize droop while the other is looking for the next peak (“sample”). At the beginning of the sample period the capacitor is discharged through a n-channel mosfet that is turned on for just an instance.


The whole mechanism is controlled by the output of the zero-crossing detector so absolutely no software intervention is needed to produce it. The microcontroller can just wait for the ZCD to trigger an interrupt (as before) and take a sample of the output.

The circuit is not that complex and used an inexpensive and readily available 74HC4053 multiplexer at its center. I don’t have any idea yet how this thing will perform but I must say this little circuit was a lot of fun to design.


Until my next post I will have built and tested this cuircuit and will let you know how it performs. Until then I leave you with the eagle files as well as PDFs of the schematic and layout as a zip file.

Here’s how the final circuit looks and how it performs: Part 19.

Ultrasonic Anemometer Part 17: Lasercut Mechanical Design


In my last two posts I have gone through my new anemometer circuit both in theory and practice. Click here for an overview over my ultrasonic anemometer project.


This will be a short post. Unlike most of my other posts, this one will not cover electronics but the physical design of this wind meter. As you can see, the new design all laser cut. At the Zurich Fab Lab I have access to a 75 watts Epilog laser cutter and I recently started playing around with OpenSCAD, an open-source CAD software.


I immediately liked the OpenSCAD approach of designing a 3D part in code as opposed to a graphical interface with menus and buttons and the like. Using OpenSCAD is much like writing software. If you’re more familiar with coding than you are with classic CAD tools you will instantly feel at home with OpenSCAD. But it’s pretty much love it or hate it. At least with all the people I’ve talked to.


I’ve seen some quite cool boxes  that were just laser cut and then screwed together. I found it quite compelling how you can laser cut your parts, stick them together and maybe use a few screws to hold everything in place. So I decided to give it a try myself.


The design is not too complicated with just 6 wooden parts. The material is 5mm in thickness so I looked around for screws and bolt that would be appropriate in size. I also thought that it would be nice to use square bolts both from an optical as well as a mechanical point of view. I learned that square bolts are specified by DIN562 and that M2.5 square bolts measures 5x5x1.6mm – exactly what I needed.


So the next thing to find was M2.5 screws. I found nice ones in stainless steel and especially with a Torx (T8 size) head as specified by ISO14580 as well as some matching washers (DIN125).


All the tubes are recycled from my last model. Just standard 16mm plastic pipes intended to hold electrical wiring.


As you can see in the photo above, I’ve tried two different versions for the side parts. The one at the bottom takes the path usually followed: There are cuts that can later fit the screws. The one at the top doesn’t have those cuts and relies on holes being drilled by hand.


Drilling those holes turned out to be really easy. After the parts are ready, just stick them together and drill the holes using a drill press. At the fab lab we have such a drill press and the holes were drilled within minutes. I never liked those cuts so for me this was the way to go.


The new design gives me a lot of space to mount any PCBs and hides all the wiring between the bottom and top plate. The bottom includes a large square hole so everything inside stays accessible. There are also two small drill holes to mount a 12 volts power supply. This way I can just plug it into the wall which I think might be handy.


The OpenSCAD model as well as the Adobe Illustrator (Ai) and PDF files are available as a download from the overview page. Keep in mind that this is one of my first attempts at OpenSCAD, laser cutting and solid CAD modelling alltogether. I’ve tried to keep the CAD model clean and modular but I’m not sure if I succeeded.


If you have any questions, suggestions or just your experience with this kind of thing please just post them as comments below. I’m quite new to most of this so I value your feedback and I’m always glad to help if I can.


Click here to continue to my next post where  I  talk about the second, analog part of the circuit.

Ultrasonic Anemometer Part 16: Testing the new driver circuit


Last time I’ve presented my new design for the ultrasonic anemometer driver circuit. So now it’s time to see how it performs. If you’re new to this project you might want to check out the overview page or at least my last post.


By now I had the time to build up the board and to do some testing. My main struggle was with the power supply. The linear regulator LM2931 comes in both fixed and variable voltage configurations. Unfortunately there is absolutely no way to tell them apart from their markings. So I accidentially used the variable voltage variant resulting in an almost 12 volts output voltage blowing up half of my circuit. I later noticed that I was out of 5V parts alltogether and had to use a LM7805 in a TO-92 package as you can see from the photo below.


After having fixed the blown-up components, the circuit worked quite well. The first thing I did was to write some basic software for the PIC16F1936 to output a burst of40kHz PWM pulses every 2 milliseconds. After every burst the Axis and Direction signals are changed so the transducers take their turns in a clockwise order (North-East-South-West-…). The screenshot below shows part of such a burst sent from the South transducer. Note that the signal is a precise 40kHz with a duty cycle of 50% as it should be.


Below you see a full burst of 10 pulses. The number of pulses to send will be something to optimize in software once the hardware is finalized.


From the following screenshot you can nicely see how the transducers are selected by means of the Axis and Direction signals.  The microcontroller always outputs its PWM burst from the same pin. All the signal routing is controlled by means of these two signals so there is not much of a software burdon.


So sending pulses is easy and works well. But that’s the easy part. Now let’s see how the circuit performs in receiving and amplifying singals.

Below you see a complete send-receive cycle. A number of pulses is sent (red) and somewhat later received (yellow) and amplified (green). Notice the different scales. Despite being only slightly larger in amplitude on the screen, the ampified signal is about 15 times larger in amplitude. Remember from the last post that the gain is controlled by a pot so this is just a temporary setting.

The distance between the transducers is 230mm so the time delay should be roughly 700us. Looking at the screenshot below this seems to be the case.


Note that I’m sending much more pulses this time and that there is a larger-than-usual gap after the 18th pulse. As mentioned, I’m still experimenting with how many pulses should be sent and how. Here I’ve sent 18 pulsed plus 7 more pulses 180 degrees out-of-phase. My hope was that the received signal will decrease more rapidly in amplitude after reaching its peak which would make the peak easier to identify. This is still work in progress but I think this might be a simple way to improve the reliability of this wind meter.

Below you see an overview over a round of measurements. Note how different transducers produce different patterns. There seems to be quite a bit of manufacturing spread between them even though they are presumably from the same production lot.SendReceiveOverview

Now let’s look at these signals in a bit more detail. There is a significant amount of noise present in the received signal but it seems to be largely gone after the amplifier stage. The amplifier is a single op amp with a DC-coupled input and a pot acting as resistive divider setting the gain. That’s about as simple as it gets. There are no filters or anything up to this point. But the output looks nice and clean.ReceiveAmpoutCloseup2

Here’s a close up making this even easier to see. There are narrow spikes present in at the input but the limited slew rate of the op amp seems to filter them all out. So the output is clean as a whistle without any filtering. Much better than expected. Wow.


If you’ve read my last post you know that there is a second op amp which I intended to use for a active band pass filter. But there seems to be no need for that at all. Simplifies the circuit, saves an op amp as well as quite a bit of board space. Great.

Nevertheless you might have noticed that there is a wider and much larger spike in the received signal every time the axis and direction signals change. The cause of this is most likely charge injection through the p-cannel Mosfets that are used as switches between the Mosfet drivers and the transducer. ReceiveSpikeCloseup

Being much slower and wider than the noise we’ve looked at so far, this spike makes through the amplifier with only slight attenuation. The good thing is that this spike occurs when we switch from one transducer to the next. That’s a time when we won’t want to look at the received singal anyway. We haven’t even sent any pulses yet. The spike abates long before the received singal starts being of interest. So I’m confident that this spike causes no real harm and can savely be ignored.


All in all I’m positively surprised how well this design has performed. I’m obviously getting a much stronger gate drive of 12 volts as opposed to 5 volts with my old design. And not only that. The Mosfet drivers used can source and sink several amps so there is reason to hope that the signal is not only larger in amplitude but also cleaner and more square. I’ll have to look at the shape of the wave form at the transducers in more detail to verify if this is really the case.


But I’m most surprised of how well the simple op amp performs. Using this super-simple setup I’m getting an output signal that’s just as clean as what I got from the rather complex two-stage tuned common emitter amplifier. No need to tune this thing making it much more production friendly. And it saves plenty of board space as well.


So this is the way to go I think. The next step will be to come up with some circuitry to process the received and amplified signal. I have some ideas in my mind and will elaborate on them shortly. But first I’ll take a closer look at the new lasercut mechanical design.

Ultrasonic Anemometer Part 15: A new attempt

It’s been about one and a half years since I started out with my ultrasonic anemometer project. Like others before me I had to notice that this a much more demanding project than it appears to be at first. After countless hours of development and testing I have built this Arduino shield. It worked but the reliability of the measurements was never what I had aimed for. The problem was mainly how to figure out the absolute phase of the received signal. So the measurements were always precise – but sometimes off by a full wavelength.  Then I was more or less inactive for most of 2015, mainly due to personal reasons. So the project was kind of stuck but i kept (and keep) getting a lot of encouraging feedback from you folks. I came up with new circuit ideas and decided to pretty much start with an entirely new design and to re-think each and every design choice I had made back then.


I will now outline and explain my new design for the send/receive circuit. So the board we are looking at today will handle the signal routing from the microcontroller to the individual transducers and from the transducers back to the amplifier where it is cleaned-up and amplified. There’s the circuit explained step by step.


Powerful 12V drive

My last design drove the transducers from a 74HC126 line driver / buffer. This chip has tri-state outputs which made it easy to switch to receive mode by releasing the respective transducer. It also has a strong (for a logic IC) output drive of up to 125mA to switch the capacitive load that the ultrasonic transducers present.

Unfortunately, the drivers only provided a 5V amplitude. Even worse, a more contemporary design would probably operate from a voltage of only 3.3 volts potentially making things worse in the future. So I decided to use a pair of Texas Instrument LM5111 Mosfet drivers. They can handle up to 18 volts so I can run them at a 12 volt input voltage directly. Mostet drivers are designed to drive large capacitative loads so they typically have powerful outputs. Specifically, the LM5111 can sink and source 5 and 3 amps, respectively. Thats more than any logic chip could ever provide. They also share a industry standard pin-out so they are easy to replace should the LM5111 not be readily available from your preferred supplier.


Discrete Mosfet Switches

The downside of using a Mosfet driver is that they lack the handy tri-state output. So I had to find another way to release the transducers for receive mode. Readily available  integrated switches and multiplexers don’t have the low Rds-on that we need here. And they are definitely not happy if you’re trying to pass 5 amps through them. So I decided to use a discrete p-channel Mosfet for each transducer. With the gate at -5V the Mosfets conduct in the 0 to 12V range of the driving signal with a on-resistance of far below 1 ohm. So the  strong drive of the LM5111 is not forfeited. With the gate at +5V the Mosfet is not conductive for signals a few volts around ground. So the receiving transducer can swing freely, unaffected by the LM5111.

Op-Amp Amplifier and Filter

The last design used a tuned two-stage common emitter amplifier. I found the design quite beautiful with nice biasing and everything but there were severe drawbacks. Mainly, the LC tank had to be tuned carefully to have it’s center frequency at 40kHz. Coils especially have large tolerances, plus/minus 20% is quite typical. This makes it at least difficult to produce any quantity of these things efficiently. It also takes some test equipment to see if your resonant frequency is correct so the design is not really suitable if you want to distribute it as a kit.

So this design uses a dual op amp at its center. I’ve decided to use a Texas Instrument LMC6482. This is an affordable precision OpAmp with rail-to-rail inputs and outputs that can run from a wide range of supply voltages. One of its main advantages for this application is its slew rate of 1.3 volts per microsecond. This is not especially much or especially little. But it’s just right for us. And this is why: A 40kHz signal with a peak-to-peak amplitude of 10 volts needs a maximum slew rate of 1.25 V/us. So 1.3 volts is enough when operating from a +/- 5V supply. And because it is just enough it will quite effectively block any high frequency noise/spikes that might be present at the input. This is a trick I’ve learned from Horowitz & Hill’s classic Art of Electronics. It’s my first time to use it so I’m exited to see how it works.

For now, the gain of the amplifier is controlled via a pot. Future designs will probably have a fixed gain once I’ve figured out how much gain we need.


Active Bandpass Filter

Just in case the slew rate limitation of the op amp isn’t enough to get a nice, clean output signal I have planned ahead and used the second op amp from the dual LMC6482 for an active band pass filter.

I’ve played around with an Excel spreadsheet and LT Spice for a few hours trying to find suitable values for the various resistors and capacitors. I’ll do some more experimenting once I can test the results on the real circuit. So don’t pay too much attention to the compoent values of this filter for now.


Signal Routing via 74HC4052 Dual 4-Channel Multiplexer

This is something that hasn’t changed much. The 74HC4052 has already been part of my last design. I’m now using two of them, one for transmitting and one for receiving.

The first half of the transmitting multiplexer  (IC2 in the schematic) takes the PWM signal from the microcontroller and sends it to the correct Mosfet driver according to the axis and direction signals that control which transducer is sending and receiving. The second half of that IC releases the receiving transducer located opposite of the transmitting one. It does so by providing +5V to the corresponding p-channel mosfet. Pull-down resistors to the -5V rail ensure that the mosfets are conducting when not actively turned off. The +5V release signal can be controlled from a microcontroller pin. Not sure if we need this functionality so a future version might just connect this signal directly to the positive rail.

The first half of the receiving multiplexer (IC1 in the schematic) routes the signal from the receiving transducer to the amplifier input. Note that there are 10k pull-down resistors on the floating leg of the transducers so the received signal is centered around ground. In order to avoid cross-talk, the second half of IC1 actively grounds the transmitting transducer’s signal. In order to make this possible, there are 10k resistors in the signal path before the multiplexer. Given the very hight input impedance of the op amp this should not have a negative effect.


Power Supply

This circuit runs from a 12V input voltage that is directly used for the mosfet drivers. For everything else, a linear regulator generates a +5V rail. An ICL7660 inverts this voltage to generate a -5V rail. The multiplexers and the op amp then run from this +/- 5 volt supply. This is somewhat of a complication compared to the sleek plus-five-volt-only approach that I took with the Arduino shield. But this gives us a much stronger 12V drive on the transducers even if a future design will run on +/- 3.3 volts. And the split supply allow for easy control of the discrete p-channel mosfet switches and ground referenced signals in the receiving circuit.


On-board Microcontroller

I’ve included a PIC16F1936 on the board. No, I don’t have any plans to use a PIC16 in my final design. I just thought it is convenient to generate the singals necessary for testing right on the board. I do consider using a dedicated on board microcontroller in my final design. I see several advantages of doing so. The design would no longer be Arduino specific. You could still interface it to an Arduino using a  standard I2C or SPI interface. But you could also interface it to a Raspberry Pi or just about anything else. That would make it much more flexible and versatile. And even if you interface it to an Arduino the Arduino is free to focus on other things than handling the technical details of running the wind meter. With the shield one had to pay close attention not to upset the timing by running other code. So a design with an on-board chip would be easier to use as well.  Cost would not really be an issue since powerful microcontrollers are available for around 2$ even in modest quantities.  Feel free to share your thoughts on this. I’m currently looking at different architectures but no decision has been made yet.

This is it for now. In my next post I’ll share my test results with this circuit. The Eagle files and PDFs are available as a download on the project overview page.  As always I very much appreciate your comments and suggestions.

Arduino Ultrasonic Anemometer Part 14: Wind Tunnel Testing

It’s been a while since I posted the last update on the anemometer project. The reason for this is that I’m struggling with the aerodynamical design.

By the way: Click here for an overview over the ultrasonic anemometer project:

For my very first tests I had misappropriated my wife’s hair dryer to generate some wind. Of course the results wereneither reliable nor repeatable so I built myself this ghetto wind tunnel:


It’s basically a 120x120mm square tube, made of cardboard and about 1.4m in lenght.


It’s powered by a powerful 120mm size brushless fan drawing some 2.25 amps at 12 volts. I don’t know about the air throughput but it generates a loooot of wind for a fan this size.


The legs put it at the right height for the anemometer prototype. There are two holes at the bottom through which the anemometer’s arms can be inserted. The transducers are then nicely centered inside the cardboard tube.


I can regulate the fan speed using a simple LM317-based regulator. It might look familiar to some of you, it has it’s own post here:

Unfortunately, the LM317 is only good up to 1.5A so I have to connect the fan directly to my 12V supply in order to run the fan at maximum speed.

As you know, the main indicator of wind speed is the phase shift between the transmitted and received signal. The distance is 0.21m and speed of sound is approximately 340m/s so with no wind, the signal travels about 618us. Signal frequency is 40kHz so one full wave corresponds to 25us. So a full wave (or a phase shift of 360 degrees) translates to a wind speed of around 14m/s or 50km/h.

Note that we usually calculate the difference in phase shift measured forth and back.In that case, the signal already repeats at half that wind speed or 7m/s.

Now my impression was that I don’t get nearly as much phase shift as I should. What makes this difficult is that I don’t know the true wind speed so maybe the wind is just not as strong as I think it is.

I went back and checked my code but didn’t find any bugs there. So I attached the scope to the transducers and looked at the signals directly. And the scope confirmed what I saw on the LCD display. So if there’s a good news it’s that both the electronics as well as the code seem to do what they should: They faithfully report what they get from the ultrasonic transducers. So maybe it’s just the physical design of my prototype that poses too much resistance to the wind and therefore causing too much of a dead wind effect.

I have done some more testing and will follow up on this shortly. Maybe some of you have a piece of advise for me…

Arduino Ultrasonic Anemometer Part 13: Arduino library finally ready

It’s been a while since the last post of this series. As so often, the task turned out to be more demanding than I first thought. And then I was also entirely new to assembly language, got distracted by my Inductance Meter Project ( and went on a skiing holiday. But finally, the promised library is ready.

If you’re new to my Arduino-based ultrasonic wind meter project, you might want to click here for an overview: This is also where you find all the various downloads, including the new library.

Using the new library is easy:

#include <anemometer.h>
extern volatile anemometerResults_t *anemometerCalculationSet;
extern volatile uint8_t anemometerStatus;


You can then access the results as follows (replace NORTH_TO_SOUTH with SOUTH_TO_NORTH, EAST_TO_WEST or WEST_TO_EAST as needed):


I’ll go through the meaning and usage of these one by one:


This function has to be called once before the anemometer can be used:

void setup()


anemometerStatus notifies your when a new set of measurements has been completed and is ready to use. Every time a new set is ready, anemometerStatus will be set to 1. You have to set it back to 0 once you’re done with your calculations.

/* use the results */
anemometerStatus = 0;

A new set of results is made available exactly every 250ms or 4 times a second.


anemometerCalculationSet is a pointer to the ready-to-use results.

Internally, the library uses a ping-pong buffer. Every time a new set of results becomes available, anemometerCalculationSet is updated to point to the last completed set of results.

The result set pointed to by anemometerCalculationSet is a

anemometerResults_t anemometerResults[4];

where anemometerResults_t is a struct defined as

typedef struct
uint32_t timeOfFlight;
int16_t sine;
int16_t cosine;
} anemometerResults_t;

The following #defines may be used as array subscripts:

#define NORTH_TO_SOUTH 0
#define EAST_TO_WEST 1
#define SOUTH_TO_NORTH 2
#define WEST_TO_EAST 3


This is easy to understand. It is the time it takes for the envelope detector to trigger. It is averaged over 32 measurements. Reference point is the rising edge of the first pulse sent. The unit is nanoseconds (ns).

Time of flight explained graphically

sine, cosine

sine and cosine indicate the phase shift between the transmitted and the received signal.

This was by far the most challenging part of library. For each of the 32 measurements, 4 rising and 4 falling edged of the zero-crossing detector are evaluated. So the phase shift indicated by sine and cosine is an average over 256 measurements. But phase shifts wrap around, casually speaking. A phase shift of 359 degrees is almost the same as phase shift of 1 degree. The average should be zero degrees, not 180. Now you could try to solve the problem by constraining your phase shift to the range of -180 to +180 degrees. But that only moves the problem to the other side of the circle: -179 and +179 degrees are almost the same and their average should be 180 degrees, not zero.

I spent quite some time thinking about this and came up with increasingly complex alogrithms that still failed when some unlucky combination of angles was encountered. Remember, we are trying to average n (currently n=256) angles, not only 2.

But of course, many people smarter than me have encountered the problem before and have come up with a perfectly elegant solution: If phi is your phase shift, then calculate sine(phi) and cosine(phi). Sum up all the sines and all the cosines. Then use the arctangent function to convert the summed sines and cosines back to an (averaged) angle. [If wordpress had something like LATEX support, one could state this as a nice-looking formula]

So there is an elegant solution. But there’s also a tight time budget: The zero-crossing detector triggeres every 12.5 microseconds (us). In order to not miss the next zero crossing, we need to calculate both sine and cosine and add them to their respective sum in less time than that. And then there is some overhead like context switching. Plus we also have to do some housekeeping during that time.

sine and cosine are expensive functions, even more so on a 8bit microcontroller. So the only way was using a lookup table. With this approach I managed to stay within budget (around 10.8us). Besides, missing the next edge is not the end of the world – the edge after that is almost as good.

Zero-crossing interrupts are just fast enough not to miss the next edge

So we now have summed sine and cosine values – how do we use them?

atan2(cosine, .sine) gives you the phase shift in radians. Multiply this by (180/PI) if you prefer degrees. My preferred approach is:

(12500.0/PI) * atan2(cosine, sine)

This also gives you the phase shift but with nanoseconds (ns) as unit which makes it directly comparable to the timeOfFlight which is also in ns.


There’s also another function returning the temperature. It returns a int16_t containing the temperature in 0.01 degrees centigrade. So if the temperature is 23.45 degrees, it will return 2345.

It’s currently implemented using floating-point math and does not account for the sensor’s (slightly) non-linear nature. It’s there mainly as a placeholder. I’m planning to implement it properly using a lookup-table with interpolation which will make it much faster and will allow it to include the non-linear effects.

Arduino Sketch

The .zip file with the library also includes a very basic arduino sketch using that library. I’m still evaluating what is the best way to calculate the actual wind speed and direction taking into account issues such as calibration and the like.

But my preliminary results look quite promising and I’m confident that most if not all the heavy lifting has been done.

As always, I highly appreciate any feedback and suggestions. Click here for the next post on this project:

Arduino Ultrasonic Anemometer Part 12: Working on an Arduino library

This is just a very brief update on what I’ve been working on the last few days. By now, this blog has caught up with where the project currently stands so the blog posts won’t be quite as frequent as they used to be. When I just started this series I had already worked on this my wind meter project for two months so I had plenty of material I only had to post.

Arduino Ultrasonic Anemometer Shield waiting for software

By the way: If you’re new to my Arduino-based ultrasonic wind meter project, you might want to click here for an overview:

As you can see in my last post, all the hardware is working really beautifully now so I can focus entirely on the software. So far, the software was really basic, just enough to show the hardware is working. That’s changing now. I’m working on a library to handle all the low level stuff, like setting up Timer1 and handling the interrupts.

One advantage of putting all that stuff in a library is that I can write in native assembler (as opposed to inline assember which I find a pain in the arse). Not everything will be written in assember. But the two I interrupt service routines (ISRs) will be. Everything else will be regular C code I guess. told you in an earlier post that my ISRs were surprisingly slow: around 5us for the most trivial tasks. The TIMER1_COMPB ISR is now re-written in assember and performs about four times faster. For simple tasks, the interrupts take only around 1.2us now.

It took a while but it’s finally ready. Click here for the next post:

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:

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: