Tag Archives: soldernerd

USB Mass Storage Device Bootloader

Let’s start with a video. It will tell you most of what I’m going to write about today.

That Hackaday Prize final has passed and unfortunately for me, the solar charger didn’t make it into the top 5. The good news is that there are plenty of projects and stuff that I would like to share. Things that I did over the last one or two years but never had time to write about. I’m trying to catch up with all that now.

First of all, I have completed the USB bootloader for the solar charger. This part of the project will enable the non-technical end user to easily and reliably update the firmware in the field.

Unlike a USB HID (Human Interface Device) bootloader that requires some application to run on the host computer, this USB MSD (Mass Storage Device) bootloader requires absolutely nothing in terms of host software. It’s entirely independent of the OS used. Windows, Linux, Mac, it all doesn’t matter. As long as they can deal with a USB drive, they’re good to go. Just copy the new software (in the form of an .hex file) to the Solar Charger drive and follow the instructions on the display.

It might even be that this bootloader is the world’s first of its kind for the PIC18 platform. To be sure, this kind of bootloader has been around for years for more powerful 32-bit microcontrollers like ARM Cortex and the like. But in my online research I have been unable to find any other such project for the PIC18 family (or any other 8-bit microcontroller). So I had no choice than to write my own. If you know of any other implementation, please let me know.

Once the file has been found and the user has pressed the button, the file is checked. If all those checks pass, we can be confident that we have a valid hex file. Of course, it doesn’t tell us anything about the quality of that code, that’s an other issue. But technically we should be fine.

Once the checks have passed, the user is once again requested to press the push button to confirm that this file should be programmed onto the chip. While it’s programming, it keeps displaying the current hex file entry it is processing to give the user an idea of the progress. It also keeps track of the number of flash pages it has written. One page corresponds to 1024 bytes on this architecture.

Once all the new code is flashed onto the chip, a message is displayed and the user is asked to once again press a key to re-boot the device into normal operating mode.

There are two different ways to enter bootloader mode. One is to press the push button at power-up. The other one consists in writing the value 0x94 (an arbitrarily chosen value) to the EEPROM address 0x100. In this case, the device will start up in bootloader mode no matter the state of the push button. The bootloader then overwrites this value (to 0x00) in order to start up normally next time.

After the reboot, you should be greeted by the startup screen of the solar charger firmware as shown above.

While I wrote this bootloader specifically for the solar charger, the code is rather universal. It can be ported to other PIC18 projects with relatively little effort. As always, the code’s on github: https://github.com/soldernerd/PIC18_USB_Bootloader.

RaspberryPi Robot

It’s been almost two years since I did (or at least started) this project but I never sat down to document it. That’s what I want to do today. As the title says it’s about a little robot based on a RaspberryPi. Like many of its kind it is driven by a pair of stepper motors each driving a wheel directly attached to the respective motor axis. At the back there is another smaller, pivotable wheel to keep the robot in balance.

Here’s a video of the finished robot in action, running a simple demo program demonstrating the various functions.  By the way, I’ve started a youtube cannel to share these kind of videos. I’m not really a video guy so this text and photos blog will stay my main medium but some projects like this robot, videos are a welcome addition.

Yes, I’m well aware that many similar designs already exist out there I could just go out and buy a kit like this. But making my own sounded more interesting so when I was looking for a Christmas present for my godson of sorts I did just that.

Above is a close-up of the main PCB that I’ve designed and built for this project. The idea is simple: There is a PIC16F1936 microcontroller that communicates with a RaspberryPi over I2C. The PIC then handles all the low-level details of controlling a pair of Allegro A4982 stepper drivers. These work at up to 35 volts, handle up to 2 amps of current and can hence drive much more powerful motors than the relatively small NEMA 17 size motors I’ve used here. They are easy to use and feature microstepping up to 16th steps.

Besides the two stepper drivers there is a ULN2803 providing 4 power outputs capable of driving up to 1 amp each. The ULN2803 includes free-wheeling diodes so these outputs could be used to directly drive somethingn like a relay or a DC motor. But at least for now these outputs drive some RGB LEDs at the front as well as a buzzer.

The original idea was to power the RaspberryPi  from the 5V linear regulator on the board and then draw the power for the PIC from the RaspberryPi’s 3.3 volt rail. Since the PIC uses only a few milliamps that’s entirely possible.

Unfortunately I haven’t given that setup a lot of thought before building the board. Of course, when powered from something like 12V, the LM2931 regulator gets way too hot when powering a RaspberryPi that pulls a few hundred milliamps. So I’ve sacrificed one of my solar charger RevC boards that includes two very powerful USB charging outputs.

During testing and debuggin I’ve used a small 12V AC/DC converter screwed to the bottom side of the robot. Once more or less completed I’ve changed the power supply to an old 3-call (11.1V) LiPo battery from a RC helicopter. It’s no longer fit for flying but still adequate to power this thing for a few hours.

The entire structure is laser-cut from 5mm medium-density fiberboard and held together with M2.5 torx screws with square nuts. M2.5 square nuts measure precisely 5x5mm so that goes together rally nicely. I’ve added and changed a few things as I went along, drilling extra holes to mount the blue PCB for the power supply, the LEDs, to hold the battery in place and some other things. But the structure as such works very nicely. It’s relatively simple if you have some place to do laser cutting (try your local fab lab…) and is inexpensive and sturdy.

The weels are laser-cut from the same material and are sized to measure precisely 200mm in circumference. That’s handy since the steppers feature 200 steps per rotation. 

 

That’s about it, most of the relevant files are on github. The OpenSCAD files for the laser cutting are not so just let me know if you’re interested in them. I’m happy to share them, too. Here are the links for the software and hardware, respectively.

As always, I welcome any thoughts or comments.

MPPT Solar Charger Testing II

It’s time to follow up on the MPPT Solar Charger project. Progress has been slow since I’m currently working full time and doing a master’s degree at the same time. Given that this blog has previously been something close to a 50% job at times things will necessarily slow down a bit. But all the projects, including this one and the ultrasonic anemometer are alive and well and I’m working on them whenever I find some time.

20161012_userinterfacereva_014

User Interface

So what’s new with the MPPT solar charger? First of all, it got this nice user interface. Unfortunately there were still some issues with the first version so there is an identically looking but much-improved and bug-free Rev B.  I’ll do a separate post on that documenting all the things I’ve changed.

I re-used the white-on-blue display from the initial version for the Rev B. as opposed to the black-on-white used with the Rev A. They are pin compatible so you can use whichever you prefer. I more and more start liking that black-on-white look. It’s about 10 bucks cheaper as well. What’s your opinion on this?

img_4334

Solar Panel drains Battery

My intention with this design was to just leave the solar panel connected to the input of the buck converter. There’s a problem with that, however. The input of a buck is always at least at the output voltage minus a diode drop. With a 12V lead-acid battery at the output the input (i.e. where the solar panel is connected) the voltage never drops much below 12 volts.

That’s a serious problem since even a small solar panel like the monocrystalline 30W panel I have here sinks around 10mA at that voltage. So whenever the panel is not providing any power it considerably drains the battery.

Try a Diode

Obviously we need a way to avoid that. The first solution that comes to mind is a diode. But there’s a problem with that, too. To keep the power loss in the diode acceptable, the diode needs to have a low forward voltage. However, any diode with a low forward voltage also comes with a high reverse leakage.  Physics seems to dictate that.

Leakage can easily be in the range of milliamps for a diode that can handle, say, 4A like needed here. And that reverse leakage is also highly temperature dependent. It may be ok-ish at room temperature and then detoriate by an order of magnitude at 50 degrees centigrade.

To get an acceptable reverse leakage one needs to tolerate at least half a volt of forward drop which is something like 3% in efficiency. Since our converter operates at around 97% efficiency that would mean doubling the energy dissipated.

P-Channel or N-Channel Mosfet

So the next obvious thing to try is a mosfet acting as a switch.  Yes, a mosfet also has a body diode that also has a reverse leakage. But the body diode is a bad diode in terms of forward drop and has a correspondingly low reverse leakage.

A nice way of solving our problem would be to use a p-channel high-side switch disconnecting the battery from the converter whenever the panel is not producing. That not only disconnects the panel but powers off the entire buck including the input and output caps and everything. Where there is no voltage no power can get wasted. Perfect.

img_4342

Unfortunately, powerful (i.e. low Rds-on) p-fets are relatively large,  rare and expensive. As a rule of thumb a p-fet needs twice as much silicon area for the same performance compared to a n-fet. Besides that, that would be another type of component and I’m trying to not use too many distinct components.

So the other solution is to use an n-fet as low-side switch just disconnecting the panel. We already have 6 powerful n-fets in our design and they are cheap, too. So this is what I’ll do in the next version.

For now I’ve used one of the power outputs to connect the panel. I’ve cut some traces and soldered in some wires so that the fet is on whenever the buck is powered on.

Buck Software

During early testing of the buck converter I managed to kill the bottom fet several times. Since I was able to run the buck at relatively high power levels for prolonged periods of time without any issues (and without getting hot) I suspected that this was caused by carelessly written software. This seems to have been the case indeed. Whenever I killed a fet it happened at startup or shutdown, usually the latter. In the mean time I’ve written well-defined startup and shutdown routines and never had any issue since.

bootstrapcapacitorcharging

Synchronous converters are dangerous in this respect. It is very easy to short the battery to ground via the bottom fet. All it takes is a duty cycle that’s too low or a timer is running too slow or not at all. Or you stop the PWM module at a time when the bottom fet is on and it will stay on forever.  Or at least a few milliseconds until it’s dead.

Asynchronous topologies are much more forgiving in this respect since you can’t short anything. So an easy solution would be to start up and shut down in asynchronous mode. We can easily make this an asynchronous converter in software by just not utilizing the bottom fet. The diode in parallel with it will then automatically take over.

Unfortunately we cannot start up in asynchronous mode. Why? To enable the upper fet we need a bootstrap voltage above the input voltage. And we don’t have that unless the converter is running. It’s a chicken and egg problem, really. So we need to start up in synchronous mode at least for a few switching cycles for the bootstrap diode to charge up.

That’s exactly what the startup routine does. It completes 16 cycles in synchronous mode at a neutral duty cycle. What do I mean by neutral? Simple: Duty Cycle = Output Voltage / Input Voltage. That means no current actually flows on average. So this is a nice, soft way to start up. After those 16 duty cycles the buck enters asynchronous mode. As the screenshot above shows, the bootstrap capacitor is fully charged after just one full duty cycle so that number is more than sufficient.

This routine is critical. If it doesn’t do precisely what it should chances are high that the buck is destroyed. So I’ve checked it carefully by both looking at the code and the scope. I’ve run it many times and observed closely what it does just to be sure it starts up nicely very time.

Why run in asynchronous mode? Because it’s more efficient at low power levels. Once the current rises above a software-defined threshold the converter will change to synchronous mode. If the current later falls below a second (lower) threshold, the buck changes back into async mode.

The optimal values for the two threshold will have to be determined experimentally but will likely be in the range of a few hundred milliamps.

buckturnoff

The shutdown sequence is simple. The buck is shut down if the current falls below a very low threshold (say, 10mA) below which it cannot run profitably. If the current falls even lower we are better off shutting down the buck and entering a low-power mode. Since the current is low when we shut it off, the converter is already in async mode. So shutting it down is now easy and uncritical. We just turn off the top fet and can then also turn off the timer and supply voltage to the buck. The screenshot above shows an example of that.

Conserving power

A main feature of this solar charger is it’s ability to (hopefully…) run at a very low (<100microamps) current when not in use. So we obviously need to turn off everything we don’t need and run the PIC at a much lower frequency as well.

The PIC’s maximum operating frequency is 48MHz. This is the frequency it runs at when the buck and/or USB (not yet implemented) is on. These two features need that clock frequency to perform their task.

If both the buck and USB are off we can clock the PIC down to 8MHz which already saves a great deal of power. At 8MHz we can still do everything else, including running the user interface. Updating the display and particularly calculating the display content consumes quite some computation time and so we need a few MHz to do this.

If the user interface is not used for a certain time (say, 10 seconds), it is turned off. We can then lower the board voltage to 2.3 volts and lower the CPU frequency even further to 32.768kHz.  This is the frequency of the real-time clock that is running anyway. At such a low frequency the PIC’s computational power is low but still sufficient to do some housekeeping tasks.

One can wake up the user interface at any time by pressing the push button. Turning the encoder won’t help because that, too, has been powered off.

While in this low power mode every 6 seconds the board voltage is raised to 3.3 volts and all temperatures as well as the input and output voltages are measured. That all happens at 32.768kHz. After the measurement is complete the PIC decides if the panel voltage is high enough to start harvesting energy or not. If this is not the case the board voltage is lowered again and a new set of measurements is captured 6 seconds later.

img_4336

Despite all those efforts the board consumes something like 530 microamps which is much more than it should. About 100 microamps comes from the voltage divider used to measure the panel voltge. That’s an easy to solve design problem that I’ve described earlier already. But that still means that something is drawing 400 microamps. Not much at all but still way too much.

I’ve spent an evening trying to find the problem but I still don’t know. I’ve suspected the capacitors but when I measured some spare caps of the same type they hardly drew any current at 12 volts. I also un-soldered the buck’s mosfet driver but that made hardly any difference so that’s also not the problem. It may even just be some near-short on my board homemade board. So I leave that for now and check again once I have a revised design with a proper PCB.

Buck testing

I’ve saved the most interesting part for last 😉 I’ve established before that this converter has a similarly high efficiency than the Arduino version published some time ago. But at that time I was only able to test up to 35 or so watts.

This solar charger is capable of handling much more power than that. Testing how much was a bit more difficult than expected. Unless the battery is very empty it won’t draw as much as this charger is able to provide. And you don’t want to discharge a lead acid battery too much, they don’t appreciate it at all. So once again my constant current dummy load came to the rescue.

img_4339

With the dummy load at one of the power outputs I was able to draw some serious current. I set the dummy load to 4 amps and the battery absorbed (or provided) whatever was left. Obviously, I can only do that for a limited amount of time until the dummy load gets too hot. It automatically shuts down once the heat sink reaches 70 degrees centigrade which is soon the case at 4 amps.

I let the charger draw 4.5 amps at a bit more than 17 volts for as long as I could. The coil got quite warm, slightly hot even, maybe something like 60 degrees. The mosfet only got lukewarm and I’m not sure if this was because of their own power dissipation or due to their proximity to the coil.

img_4341

So from this test I’d conclude that this was about the power which the charger can handle for a prolonged period of time. So I think something like 75 watts is a realistic power rating.

I’ve also had another look at the datasheet of the coil and it pretty much confirmed my findings. 75 watts at (say) 13 volts output corresponds to 5.8 amps through the coil. The datasheet states that the coil starts saturating at 8.2 amps which means we’re still safe with 5.8 amps plus the ripple current. The datasheet also states a 40 degree temperature rise at 5.3 amps. So thermally the coil is pretty much at its limit at 75 watts. That, too, seems realistic to me having touched it after some time at that power.

The road ahead

So how to continue? As we have seen, there is a number of design issues but the general concept works. During testing and debugging I’ve cut and re-soldered many traces and also made some modifications like the one with the n-fet described above. I’ve unsoldered and changed many components as well. All of that doesn’t improve the reliability of the board. At some point it makes sense to design a new version, build it and take it from there. A clean slate kind of.

I think this point has been reached here. So I will work on a new revision from now on. The concept won’t change at all but I’ll try to apply what I’ve learned so far. I also hope to reduce the number of different components, reduce the size and total cost while not sacrificing performance. In other words move a step towards a design that may one day be built as a small series. Let’s see.

Ultrasonic Anemometer Part 27: Ready to take pre-orders

20160903_StandaloneAnemometer_001Good news: the boards from dirtypcbs.com have arrived and look great. I also got all the components for the 11 boards. Why 11? I ordered about 10 (they call it a protopack) and was lucky enough to get 11. Thats dirtypcbs.

Last week I also upgraded my hobbyist Eagle license to a proper Premium LS license which means I can now legally start selling stuff. So I’m basically ready to ship the first kits.

20160903_StandaloneAnemometer_002

Today I assembled one of the boards and it at least looks great. All the footprints are correct and it was a pleasure to solder. Now what I want to do is to run some tests with it just to make sure it works as intended. I didn’t change much since the last version but I want to be sure first.

20160903_StandaloneAnemometer_003

About the kit

There’s one thing I want to be absolutely clear about. At this stage of development the wind meter is not yet ready to be deployed. While I think the hardware is final now, a lot more work is needed to get the software ready. So for the time being this kit is intended for people who want to join the development and testing. I’ve done most of the low-level, register-fiddling stuff but much remains to be done at a higher level. I know there are a lot of people out there with much more experience in signal processing than me and I’m looking forward to work on this challenge together. And a challenge it is. But the PIC32 still has plenty of RAM, Flash and CPU time left to try out new ideas and approaches until we find one that works well.

20160903_StandaloneAnemometer_004

The kit contains the board and all the necessary components. Details can be found in the BOM linked on the overview page. Once assembled it should look precisely like on the photos on this page. But as the name suggests, it comes as a kit, i.e. as components that you have to solder yourself. Most components come in relatively large SOIC packages but there are a few smaller MSOP and SOT-23 packages as well. They can all be soldered with a conventional soldering iron and strain solder just like I’ve done today.

20160903_StandaloneAnemometer_005

The microcontroller is not yet programmed so you will need a suitable programmer. Microchip’s PICKit3 (USD47.95) is the obvious choice here. This is also what I’m using and matches the board’s pinout. All the software (MPLAB X IDE and XC32 compiler) are available for download from Microchip free of charge.

Taking pre-orders now

I’ll start taking pre-orders now but as mentioned I won’t ship the kits until I’ve done some tests with my own board. Once that’s done I’ll let you know and if you’re still interested by then I’ll give you my PayPal details and ship the kits.

Some have mentioned that they already have some ultrasonic tranducers and/or want to try some specific model so you are free to order your kit with or without the transducers.

20160903_StandaloneAnemometer_007

There’s no online shop or anything like that so just use the contact form on the about me page.

Pricing

Now it starts getting interesting. I’ll quote all prices in USD, EUR and CHF.  Choose what’s cheapest or most convenient for you.

  • Kit without transducers: USD 70 / EUR 63 / CHF 69
  • Kit with transducers: USD 95 / EUR 85 / CHF 93

The prices above include worldwide shipping. The kits ship by Swiss Post Priority Mail in a padded envelope.  I’ve used this service before to locations like Brazil or India and never had problems. However, there are no tracking numbers.

Any other questions? Just ask.

20160903_StandaloneAnemometer_006

 

MPPT Solar Charger Design

I’m currently waiting for the boards for my Ultrasonic Anemometer Rev B to arrive from Hong Kong and this gives me some time to write about the MPPT Solar Charger design that I did quite some time ago. I published a series of posts on a Arduino MPPT Solar Charger Shield and got a lot of encouraging feedback. But that shield was more of a proof-of-concept than a finished product.  While it generally performed well it drew way too much current when idle to actually be deployed unless you can count on plenty of sunshine every day.

SolarChargerEagleTop

Aiming for very low power consumption

While I like the Arduino platform I had to admit that it’s probably not ideal for a low-power design. Yes there are some things you can do to reduce the 50mA or the Arduino draws but it will never be truely low power. So I designed a stand alone version with plenty of extra features that I hope to draw only a small fraction of the current. I particularly care about the idle current, i.e. the current it pulls when the solar panel is not producing any energy. In winter, the panel might be covered by snow for weeks and you don’t want your charger to drain the battery during that time. With this new design I’m aiming for an idle current in the tens of microamps. Even if it ends up being 100 microamps that is still 500 times less than an Arduino uses just by itself. And that means it draws less than 1Ah (ampere-hour) per year so you will never drain the battery no matter how little sunshine there is.

SolarChargerSchematic1

PIC18 series microcontroller

At the core of the design is a PIC18F26J50 in a 28 pin SOIC package. It’s capable of running at down to 2.15 volts and consumes extremely little power when running at lower clock speeds. And apart from that it features USB so we can have all the benefits of USB without any external components except, of course, a USB socket.

The PIC has two crystals at its disposal. A 8MHz crystal which will be boosted up to 32MHz by its internal PLL. That’s what the PIC will run on when there is work to do. And then there is a 32.768kHz crystal that will be used to run its real-time clock (RTC). When there is little to no work to do this low-frequency clock will also be used to run the CPU which will greatly reduce power consumption. Power consumption is approximately linear in frequency so this should cut power consumption by a factor of about 1000 compared to full-speed operation.

SolarChargerSchematic2

Switch mode power supply

Now we can run the microcontroller at only a few volts but our power supply is a 12 volt battery. So one of the most straight forward things to do in order to save power was to use a switch mode step-down regulator aka buck.

I looked around and found the Texas TPS62120. It’s only capable of providing 75mA but that’s more than enough for us in this case. It works at a switching frequency of 800kHz and only consumes a bit more than 10 microamps with no load at its output.

It needs a 18uH inductor as well as some ceramic capacitors to work. The output voltage is set via a pair of resistors acting as a voltage divider. I’ve added a n-channel mosfet that allows the PIC to increase the output voltage from 2.2 volts to 3.3 volts when needed. Because while the PIC can run on down to 2.15 volts the display can’t. And even the PIC needs 3.0 to 3.6 volts for USB operation.

Synchronous / asynchronous operation

The actual MPPT converter has changed only little. I’ve changed the mosfet driver to a MIC4605.  Unlike the IR2104 used last time, this model has adaptive dead-time (as opposed to the longish 540ns fixed) and separate inputs for each mosfet. This will allow us to either operate in synchronous (using both mosfets) or asynchronous (only using the upper fet and relying on the diode) mode. Asynchronous operation has a certain efficiency advantage at low power levels so this might come in handy.

The MIC4605 consumes quite little quiescent current for a mosfet driver, only 100uA typical. But that’s still too much for our purpose. So the PIC can power the whole thing off via a NPN transistor and a p-channel mosfet. That BUCK_ON signal also serves as the supply voltage for the INA213 current sensors already used in the last version. So the entire converter can be powered off and should consume precisely zero current when not in use.

What about the voltage divider necessary to measure the battery voltage? That’s been taken care of, too. That divider is interrupted by a (low threshold voltage) n-channel mosfet unless a signal from the PIC turns on the mosfet and closes the circuit.

SolarChargerSchematic3

Port expansion

I soon ran out of GPIO pins with that PIC so I had to add an I2C port expander (MCP23008) to gain another 8 I/O pins. I’ve also added a PCA9546 I2C switch in order to translate between different voltage levels.

It’s probably not the most elegant solution and a future version might trade these 3 chips for a higher pin-count PIC. But I had all components here already so that’s what I’ll use for now.

Precise measurements

In order to precisely measure input and output voltages and currents there is now a MCP3424 4-channel 18-bit ADC. To be sure, we don’t need 18 bits of precision here but we’ll trade some of that precision for speed and work with 14 or 16 bits.

The ADC has its on-board voltage reference and PGA with gains up to 8.  Since it only consumes a maximum of 1uA in standby mode it is always powered on.

There are also a total of 3  LMT86 temperature sensors, one on the board and 2 external ones. The external ones are intended to measure the temperature of the panel and battery, respectively. The maximum voltage for a battery is quite dependent on temperature so that’s a useful information to have. The inputs from the temperature sensors are measured directly by the PIC.  For that purpose there’s also a ADR361 2.5V voltage reference.

Measuring temperatures requires the board voltage to be high, 3.3 volts nominally. So both the voltage reference and the temperature sensors are only powered on when then VCC_HIGH signal is set.

User interface

To communicate with a human user there is a 4×20 LCD display that is controlled via I2C in order to save some I/O pins. There are quite a few external components needed to run it at 3.3 volts so it has its own PCB and connects via a 5-pole wire. There is 3.3 volts and ground for power, SCL and SCD for I2C communication and a PWM singal in order to control the display brightness. Because that’s a rather universal board I will document that as a separate post.

As an input device there’s a rotary encoder with push button. Together with the display (and some decent software) that should allow for a pleasant user experience.

The inputs from the encoder are debounced in hardware via a 74HC126 that serves a double purpose. With its 3-state outputs it allows us to use the pins that are otherwise used for in-circuit programming of the PIC.

Both the rotary encoder (except the push button) and the entire display unit can be powered off when not in use. The push button is always powered on so the user can wake up the user interface at any time by pressing the button. When the user interface is not actively powered on the 74HC126’s outputs are in high-impedance mode and the PIC can be programmed without being affected by the rotary encoder.

SolarChargerSchematic4

Data logging

One might be interested how much energy has been harvested by the solar charger over the last hours, days, weeks or months. So there’s some non-volatile storage as well. The 24FC256 connects via I2C and offers 256kBit of memory. It consumes only 100nA in standby so it can stay powered on at all times.

Fan control

As mentioned, there’s a temperature sensor on the board. If it gets too hot, a fan can be powered on via the FAN_ON signal controlling an n-channel mosfet.

Outputs

There are 4 power outputs, each controlled by a separate signal from the PIC. There should be some PWM modules left on the PIC so some (two I think) can be PWM controlled. A typical application would be LED lighting which can be controlled and dimmed directly from the solar charger via the rotary encoder. Each output channel has a beefy  mosfet of the same type as the MPPT switcher (IPB136N08N3).

Each has its own FAN3111E mosfet driver. They have a separate input for the reference voltage so the PIC can easily control them when running at only 2.2 volts. The FAN3111 should only draw 5uA (10uA max) when idle but there are 4 of them so they can be powered off (all togeher, not individually) when not in use.

SolarChargerSchematic5

USB charging ports

One of the first thing one wants to do when there is power is to charge one’s cell phone or similar device. So there are two USB charging ports capable of delivering some 2 amps of current at 5 volts in total.

They are powered from the 12V batter via a TPS54231 buck converter. So there are a total of 3 buck converters on this board… It is always connected to the 12V rail but the PIC can turn it off when not in use. The regulator’s shutdown current consumption is only 1uA typical (4uA max) so that should be adequate.

Manufacturers of mobile devices have all come up with nasty ways of making their devices incompatible with other manufacturer’s chargers. They basically abuse the otherwise unused (for charging purposes) data lines to recognize their own chargers and discriminate against any others. That might mean they won’t charge at all or only at a slow rate.  So there are two charging ports on this board, one emulating an iPad charger and the other one a popular Samsung scheme. So pretty much any device should be able to charge on at least one of these ports at a reasonable speed.

Summary

As you can see, there’s a lot of functionality in this new design just waiting to be unlocked by some clever software.  I’ve already milled a board and I’m looking forward to populating it and bringing it to life. I guess that will be quite a bit of work but I think its well worth it. Thanks to all of you who have kept asking about this project – I very much appreciate all your feedback.

There are only Eagle files (including PDFs of the layout and schematics) at this point. They can be downloaded on the overview page. There’s now also a prototype. First test results are presented here.

Ultrasonic Anemometer Part 26: Rev B Board ordered

I recently ordered my first PCB at dirtypcbs.com and the result was promising. So there was nothing stopping me from finalizing the Rev B of my standalone Ultrasonic Anemometer and ordering a protopack. I’ve placed the order a few days ago and expect the boards to arrive here in 2 to 3 weeks. This should be good news for all those of you who have been asking for kits and want to contribute to the further developement of this project. I’ll build up one or two boards as soon as they get here and do some testing. If everything works as planned I can order some more components and ship some kits soon after that.

EagleSnapshot

So today I’ll go through the changes I’ve made compared to the previous version. All in all the changes are quite minor and only require minimal changes in software. But let’s go through them one by one.

Non-volatile memory

This is the biggest change from a functional point of view. The PIC32MX250 doesn’t have any EEPROM memory of its own. So in order to be able to save some settings an the like I’ve added a Microchip 24AA16 I2C EEPROM providing 16kbit (2kB) of non-volatile memory. That should be more than enough to store any settings and calibrations one might want to make. For example, this gives the user the possibility to calibrate the filter kernels to the transducers used. Of course, the software first needs to make use of that memory but I think it’s great to have the possibility to durably  store a reasonably large amount of data.

dirtypcb_top

Support for 5V I2C communication

I’ve hinted at this in a previous post. On the Rev A board the I2C signals were pulled up to the 3.3 volt rail. This was great as long as one didn’t want to interface to a 5V device such as an Arduino. The microcontroller pins are 5V compatible so you want to be able to pull those lines up to 5V whenever you interface to a 5V device. So I’ve added a diode to allow the SDA and SCL lines to be pulled higher than 3.3 volts. The I2C reference voltage of 3.3 volts minus a schottky diode drop or about 3.1 volts is accessible from the I2C header at the bottom. So just connect that to the external device’s 5V operating voltage and you have a fully compliant 5V I2C bus.

dirtypcb_bottom

Physical layout and connectors

There was a rather large 8-pin connector on the last version to connect to the transducers. Now all the connectors along the edges of the board are standard 100-mil headers. This also allowed me to slightly shrink the physical size of the board to 60x70mm.

The pinout has also slightly changed. The board is now powered from a header on the right-upper side and all three voltage rails are now externally accessible from a newly added header on the right side. The pin order on the I2C and SPI headers on the bottom side of the board has changed, mainly to accomodate an exteral I2C reference voltage.

GerberViewerScreenshot1

Power supply

The tiny (SOT23-5) 3.3 volt linear regulator on the last version worked well but got rather hot when providing close to 50mA from a 12V input voltage. I never had any issues with it at room temperature but decided to be cautious and upgrade to a LD1117 regulator in a much larger SOT223 package. This should be more than sufficient any reasonable ambient temperature..

GerberViewerScreenshot3

Miscellaneous changes

I changed the digipot used to set the amplifier gain to a Microchip MCP4531. This model only has 128 steps but this is still more than sufficient for its task and it’s quite a bit cheaper than the 256-step version.

I also had to change the crystal because the model previously used became unavailable.

GerberViewerScreenshot2

That’s it for now. I’ll let you know as soon as the boards get here.

Ultrasonic Anemometer Part 25: I2C Interfacing and more

20160706_StandaloneAnemometer_023

It’s been a long six weeks since my last post but that doesn’t mean that I haven’t done anything since. Among other things, I wrote some code to get the I2C interface working and hooked the anemometer up to an Arduino Uno with an LCD display attached. Apart from demonstrating the I2C interface this also nice for testing. For the first time I can see what this thing is measuring in real time without hooking it up to a PC over USB.

20160710_StandaloneAnemometer_025

I2C Interfacing

But let’s look at the setup in some more detail. The PIC has a total of two I2C interfaces and I’ve made both of them accessible via the 100mil headers along the edges of the board. One of them is primarily intended for internal purposes like controlling the gain via the I2C digipot. The other one can then be used to interface to some external logic without having to worry about any internal communication. This external I2C interface also comes with 5V compatible pins which means we can interface to 5V devices like an Arduino without any further logic level translation. All we need is a pair of pull-up resistors pulling the SDA and SCL lines up to 5 volts. The Arduino’s Atmega328 already has built-in (weak) pull-up resistors so that’s not a problem. I didn’t think of interfacing to a 5V device when I designed the board and pulled the I2C signals to the anemometer’s 3.3V supply. So for proper 5V operation I’d have to unsolder the two 10k resistors. Luckily, 3.3 volts is enough to almost certainly be recognized as a logic high by the Arduino so the setup works anyway. But I will think about how to improve this in the next version. I might add a diode to allow the lines to be pulled higher than 3.3 volts.

The I2C interface can be configured to act as a master or as a slave device. For now I’ve only implemented slave mode so the wind meter behaves just like a I2C temperature sensor or external ADC. The Arduino acts as a master and asks the slave for its latest measurement every 250ms. The anemometer then returns 8 bytes of data consisting of 2 status bytes, north-south wind speed, east-west wind speed (both in mm/s as signed 16-bit integers) and temperature (0.01 degrees centigrade as signed 16-bit integer). It’s also possible to send data to the anemometer. That data is then saved to a buffer is otherwise ignored.  In a future version of the software one might use this functionality to set the data format to wind speed and wind direction or to change the temperature unit to kelvin or fahrenheit.

20160710_StandaloneAnemometer_027

It would not be difficult to implement master mode as well but so far I haven’t done it yet. A lot of code could be copied from the module communicating with the digipot where the PIC acts as a master. The anemometer could then push data to an external device whenever a new measurement becomes available. Definitely something I’d like to implement at some point but no priority right now.

Bug fixes

I’ve found (and fixed) a number of bugs while testing. Among other things, the axis and direction signals were not always properly set and so the measurements did not always correspond to the direction they should. So take with a grain of salt some of the test results reported earlier. Some of them were almost a bit too good to be true and this bug might have been the cause. I suspect I might have compared two successive measurements in the same direction when I actually wanted to compare measurements taken in opposite directions. But I’ve fixed the code and I’m confident that now all the directions are set and reported correctly.

Individual filter kernels

EqualAmplitudes

As can easily be seen from the scope screenshots above, the shape of the received signal varies quite a bit from transducer to transducer. Note that the amplifier gain is dynamically adjusted to make sure the peak amplitude is the same for all of them but the shape still differs quite substantially. So the kernel for the matched filter has to be some compromise to suit them all. I have now modified the software to use four individual kernels, one for each direction. This gives us the flexibility to calibrate the kernel to each transducer and so get more reliable results for the absolute phase.

Revised board

20160710_StandaloneAnemometer_026

My main priority at the moment is to complete the revised version of the board and to order a small series of boards. Until recently I never ordered a board from a professional board house so there are quite a few things for me to learn. For the first time I have to worry about silk screen, for example. Or solder mask. On the other hand, a board house can do a lot of things I can’t. Plated-through holes for example. Or smaller vias. Or place vias under an IC. This means a lot more flexibility in my layout that I first have to get used to. But I’m making progress. I got a simple design of mine produced by dirtypcbs.com and got a batch of very usable boards. More on that in a future post.

Wind tunnel

If you’ve been following this project for a long time already you might remember my simplistic wind tunnel made of a 120mm brushless fan and a cardboard tube. I got a number of suggestions from you guys on how to build something better than that and I also found some useful material online. So I’ve started to build a much improved wind tunnel that will hopefully allow me to perform more meaningful tests. That’s also for one or more future posts.

20160706_StandaloneAnemometer_021

Software ideas

I’ve also played around with some software ideas that I believe to have potential. One is dynamically adjusting the frequency. I’m now only working at the transducer’s nominal frequency of 40kHz. But the individual transducer’s resonance frequency might be somewhat different and might change with temperature or age. So I might try to adjust the frequency dynamically using some perturbation and observation algorithm.

I’m also thinking about measuring at two slightly different frequencies (say, 39.5kHz and 40.5kHz) and using the two phase shifts to figure out the absolute time-of-flight. I’ve given it a try and was not very successful but I haven’t given up on that idea yet.

So that’s it for now. The code for the Ultrasonic Anemometer as well as the Arduino are available for download. See the overview page for the respective links.

Ultrasonic Anemometer Part 24: New Microcontroller and Software Controlled Gain

It’s been almost three weeks since my last post and some further progress has been made. I’ve upgraded the microcontroller and can now control the gain of the second amplifier stage in software. But let’s look at the changes in some more detail.

20160625_AnemometerDriver_008

New microcontroller: PIC32MX250

I mentioned last time that I was running out of code space, i.e. flash memory on the PIC32MC220. That particular model has only 32k of flash and I’m using the free version of the XC32 compiler. That free version only performs limited amounts of optimization and therefore produces rather large and slow code compared to the standard and professional version. But the other two are rather costly (around USD 500 and 1000, respectively) and are not really an option here.  And at least so far I’ve always had all the speed I needed so the only issue was flash memory.

So the straight forward solution was to upgrade the microcontroller to an otherwise identical model with more memory. The 250 I’m using now has four times more of both flash (now 128k) and ram (now 32k). I unsoldered the old chip using a hot air gun and soldered in a PIC32MX250 in its place. Now we have all the flash we need to continue our journey.

20160625_AnemometerDriver_005

Getting I2C to work

My design uses a dual op amp for the necessary amplification of the received signal. The first stage is ground-referenced and uses a simple resistive divider to set the gain (currently set at 11).

The second stage is biased to 1.65V (i.e. half way between ground and 3.3 volts) and has its gain controlled by a I2C digipot. The idea is to have the PIC control the digipot so it can adjust the gain as needed to compensate for any effect that might change the amplitude of the received signal.

So in order to control our digipot we first need to get the I2C interface working on the PIC. There are two (identical) I2C peripherals on the PIC32MX2xx and this design uses one of them (#2) exclusively to communicate to the digipot. The other one (#1) is then available to interface to the outside world.

I’ve written a set of simple functions to use the I2C interface. So far I’ve only implemented  master transmit mode since that’s the only thing we need here.

  • void app_i2c_internal_init(void);
  • bool app_i2c_internal_write(uint8_t address, uint8_t *data, uint8_t length);
  • void app_i2c_internal_writeDigipot(uint8_t value);

The functions are entirely non-blocking so they can be called from within the interrupt service routines that do the measurement.

Fixing a design bug

Unfortunately, I made a mistake in the schematic when I referenced the feedback loop of the second op amp stage to ground instead of the mentioned 1.65 volts. Now let’s look at what that did to the signal. First, below is the signal with the digipot at 0 (of 256). The gain is set to one and all is well.

AmpError_Pot0

But at a setting of 64, some clipping starts to occur as shown below.

AmpError_Pot64

With the gain turned up to 4 with a digipot setting of 192 things get really uggly with a completely unrecognizable output signal.

AmpError_Pot192

I was extremely lucky that the correct signal was available right next to the pin where I needed it so all I had to do was to cut the ground connection with a carving knife and to connect the correct signal using a tiny bit of wire.  The change is hardly visible on the photo below. Can you spot it? It’s almost at the center of the photo at pin 5 (bottom right) of the small 8-pin IC. It now connects to the 10k resistor at the bottom instead of the ground plane on its right.

20160626_AnemometerDriver_009

Controlling the gain in software

With that error fixed we can now set the gain as we please. Here some examples. Yellow is the (unamplified) input signal whereas green is the output of the (fixed) first amplifier stage.  The purple signal is calculated as the difference between the DAC+ and DAC- signals. Those two signals is what we feed into the PIC to be measured.

With the gain at 1 (digipot at 0) we get a about 2.6 volts peak-peak. A bit little but sufficient.

Amplifier_Pot0

This is probably about what we want. Digipot at 50 resulting in a peak-peak amplitude of a bit above 3 volts.

Amplifier_Pot50

Needless to say that we can jerk the gain up far more than that if we want.  Below is an example where a gain of 4 results in a seriously clipped signal.

Amplifier_Pot192

Now let’s look a a situation where such a high gain might actually be useful. In the example below I’ve lowered the input voltage to only 5 volts. As a result the received signal is only 90mV in amplitude instead of the 220mV seen above. That’s easily compensated with a bit of help from our digipot. With a setting of 170 we get a nice, clean 3 volt output signal.

Amplifier_Vin5_Pot170

Calculating the necessary gain

For the examples above I’ve explicitly set the gain in the code. But what we really want is to have the software calculate and set the necessary gain automatically.

So I’ve implemented a simple algorithm to do so. I set some target value for the peak-to-peak amplitude of the signal measured by the DAC. Knowing the amplitude and digipot setting of the last measurement I calculate the optimal gain and digipot setting for the next measurement.

AmplitudesGain1

Above is the signal without this automatic gain setting in place (gain=1). As you can see, the peak-to-peak amplitudes vary quite a bit between transducer pairs. So the gain calculations, too, work on a transducer pair basis. Each direction gets its own setting to compensate for different transducer sensitivities.

Below is a screenshot of the result. Notice how now all transducer pairs have identical (and somewhat larger) amplitudes.

EqualAmplitudes

That’s it for today. Click here for my next post.

Ultrasonic Anemometer Part 23: First successful measurements

In my last post I was happy to report that I managed to get the USB interface to work. This interface has since proved to be extremely valuable in software development and testing. While the device is taking measurements you can look at the results (or intermediate results) at your PC in real time. You can even log large amounts of data to a .csv file and inspect the results in Excel.

20160514_StandaloneAnemometer_049

But let’s look at the developements in a bit more detail. Last time the device was sending pulses and capturing some of the resulting zero-crossings but not much more than that. And in a not very structured way.

Measuring amplitude

Now it’s not only capturing the times when the zero-crossings occur but also measures the amplitude of the half-waves in between. In order to do that an interrupt is generated at every zero-crossing capture. Inside that interrupt service routine time of the zero-crossing is saved (as previously) and the ADC is started. In order to measure the amplitude at its maximum (or minimum in case of a negative half-wave), the ADC first samples the input for a 6.25 microseconds (which corresponds to a quarter-wave at 40kHz). I’ve chosen the sampling period slightly shorter to compensate for the time from when the zero-crossing occured unil the ADC is started. After the sampling period the internal sample-and-hold amplifier switches from sample to hold and the actual analog-to-digital conversion takes place.

The PIC’s datasheet advertises a maximum sampling rate of 1 million samples per second. Beware, though, that this requires separate Vref+ and Vref- connections and doesn’t work in differential mode anyway. In my configuration without separate analog references and differential measurements the maximum sampling rate drops to 400k samples per second. And the reported conversion time doesn’t include the sampling time yet. I wasn’t aware of that but luckily the PIC’s ADC is still more than fast enough for what I’m doing here.

20160428_StandaloneAnemometer_028

Finding the absolute phase

Capturing the zero-crossings is relatively easy and the results are very precise. But there’s a challenge: there are hundreds of zero crossings for each burst of pulses sent. How do you know which zero-crossings to use?

The Arduino-based anemometer used an analog envelope detector to solve this problem. After averaging plenty of samples this works most of the time. But even after many attempts to tweek the analog circuit the envelope detector approach was never as reliable as I wanted it to be.

My standalone anemometer has an entirely different approach. Being able to digitally measure the amplitude of each half-wave we can tackle the challenge in software. We have a series of measurements and we have an idea of that the signal we are looking for looks like. Looking the scope screenshot below you could easily and reliably determine where the maximum amplitude occurs. That’s what we need to teach the software to do.

ZCD_Capture

One could, of course, just loop through the all the amplitudes and find the maximum. But there are a lot of similar amplitudes and so any noise would make the result unreliable.

I did a bit of reading on digital signal processing (DSP) and realized that this is a classic DSP problem. The solution is a matched filter. You take the signal you are looking for (also known as kernel or template) and multiply it sample by sample with the captured signal and sum up the results. Do that for every possible (or reasonable) overlap of signal and kernel and find the position where the result reaches its maximum.

If you’re new to the subject (like I am), Steven W. Smith’s Digital Signal Processing is a great place to start. It’s even available online for free at dspguide.com. The method is also referred as convolution or correlation depending on who you ask. This wikipedia article gives a nice introduction to the subject.

Implementing the matched filter

I’ve parameterized the software to capture 34 zero crossings as well as the n=33 amplitudes in between them. The kernel consists of k=17 data points with a peak in the middle.

There are n-k+1=17 possibilities to entirely overlap the kernel with the signal. We can skip all the odd numbers where a negative kernel value would be multiplied with a positive sample value and vice versa. This leaves us with 9 possible positions to chose from.

For each position we need to do 17 multiplications and 16 additions. And we need to do that for every single measurement, i.e. 512 times per second. That sounds like a lot of work and it probably is. Luckily, since this is a very common DSP task, microcontrollers like the PIC32 have a special instruction for this. It’s called MAC – Multiply Accumulate and executes in a single clock cycle. The result is just amazing. The corresponding ISR takes less than 30 microseconds, including some housekeeping tasks as can be seen in the screenshot below.

Once the maximum amplitude is found, the 16 zero-crossings around it (i.e. the 8 before and the 8 after) are summed up and the sum is saved as the result of that measurement.

ConvolutionTime

Averaging measurements

The goal is to report wind speed and temperature four times per second. Since there are 512 measurements per second we can use up to 128 individual measurements  (32 in each direction) to do our calculations.

So we have plenty of data to identify and exclude outliers and do some averaging of the remaining samples. Robust statistics is the key word here, click here for the corresponding wikipedia article.

For now I’m doing something reasonably simple: First the 32 results per direction are sorted. The 12 lowest and 12 highest results are ignored and only the 8 results in the middle are summed up.

This might seem wasteful but it makes the average very robust against outliers and still results in 16 x 8 = 128 zero-crossings being averaged. The resolution of each zero-crossing is equal to 1 / 48MHz or about 20.83 nanoseconds. Summing up 128 of them gives us a resolution of far below a nanosecond. Beware however that resolution doesn not imply accuracy.

As a last step, the resulting sum is multiplied with 125 and then divided by 768 to make the unit 1 nanosecond. So every 250 milliseconds we finally have 4 time-of-flight measurements with a resolution of 1 nanosecond. That’s what we will use to calculate the winds speed as well as wind direction and temperature.

This sorting and averaging step is a bit more costly in terms of computation time. It takes around 600 microseconds to complete (see below). But unlike the convolution, it only has to be performed 4 times per second so this is more than fine.

CalculatingAverageToF

Calculating wind speed

We are finally in a position to calculate the actual wind speed. There are various ways of doing this. For now I’ve just done the simple approach of taking the difference in time-of-flight, assuming room temperature and solving for wind speed. This means solving a quadratic equation for which I have resorted to floating point math and using <math.h> for the square root function.

I don’t have my wind tunnel any more so doing any testing was difficult. But one thing was soon obvious: at zero wind speed, the time-of-flight measurements match extremely well and are extrordinary stable from measurement to measurement. Also, looking at the intermediate results (i.e. the 128 single measurements before averaging) shows that there are basically no outliers present. I could randomly pick a measurement and still get a very reasonable value.

Something seems to be systematically wrong with the first of the 128 measurements but I haven’t had time to look into this. Otherwise, the results are impressively stable. And I’m only using a relatively primitive kernel for the matched filter.

USB data logging

As I’ve mentioned at the beginning, the USB interface lets me do some serious data logging even at this early stage of development. Here’s a list of what I can do by sending a character to the device from a USB terminal.

  • ‘Z’: Get all the 34 zero-crossings of a single measurement
  • ‘A’: Get all 33 amplitudes of a single measurement
  • ‘F’: Get a full single measurement, i.e. 34 zero-crossings plus 33 amplitudes
  • ‘T’: Get all the 4 x 32 = 128 time-of-flights for a measurement series
  • ‘R’: Get the 4 averaged time-of-flights as well as wind speed and temperature

Some versions of these commands also let you specify the direction you’re interested in as well as how many sets of data you want to receive. This makes it easy to log large amounts of data that you can use to test possible algorithms on your PC before you implement them on the PIC.

20160428_StandaloneAnemometer_025

Next steps

The next step is to get the I2C digipot working so I can control the amplification in software. My idea is to aim for a maximum amplitude of around 3 volts independent of wind speed and so on.

There’s also plenty of work to do to improve the algorithm that calculates wind speed and temperature. And then I also have to implement the I2C and SPI interfaces that let the anemometer communicate to other embedded devices like an Arduino or Raspberry Pi.

Having used floating point math and <math.h> I’m also running out of flash memory. I’m currently using 93% of flash (32kB total) and 52% of ram (8kB total). There will be a slightly revised board (Rev B) that uses a PIC32MX250 which is identical to the MX220 used here but has four times as much flash and ram.

That’s it for today. On the overview page you find the software at the stage of developement just described as well as some examples of logged data (all at zero wind speed) as .csv files.

The next post on this project is here: Part 24.

Ultrasonic Anemometer Part 22: USB up and running

20160514_StandaloneAnemometer_047

Last time I showed you the nice new hardware of the new standalone ultrasonic anemometer. But at that time I had hardly any software written for it so I couldn’t do much with its 32 bit microcontroller. So the last two or three weeks I spend lots of time writing code that I’d like to share with you today.

20160428_StandaloneAnemometer_039

As I mentioned last time I worried most about getting the USB working properly. All the bit-fiddling with timers, PWM modules, input capture modules and the like can be time consuming and at time even frustrating. But I have all the confidence that I finally get what I aimed for. It might take a few nights digging through data sheets but in the end it will almost definitely work.

Now with USB I don’t quite have that level of confidence. The USB specification is quite overwhelming and there are almost countless registers to properly set and USB descriptors to specify. Without some sample code I’m pretty much lost I must admit.

Outdated Application Notes

So I was happy to see that Microchip has published a number of application notes and accompanying software. A handful of .h and .c files that you can include in your project, change some settings to suit your particular application and you’re ready to go. At least that’s what I thought.

20160514_StandaloneAnemometer_048

All those application notes were published around 2008 and the code they are referring to is nowhere to be found nowadays. Aparently, Microchip has been quite pushy trying to get their PIC32 customers migrate to their new library or rather framework called Harmony. MPLAB no longer even includes the the PLIB peripheral library everyone has been using for decades. Microchip has depreciated it and while you can still download it they make very clear that Harmony is the library of the future.

On the road with MPLAB Harmony

So faced with few other alternatives I turned to the aforementioned Harmony library. It’s many hundred megabytes to download and takes up almost two gigabytes of disk space. It integrates nicely into MPLAB X and so I created a first project. You can graphically configure the clock and pin settings so I did that. Clicked on ‘create code’ and was nothing less than shocked by the code I got.  Around a dozend source files scattered around in a dozend deeply nested folders and subfolders. And that was not yet it. Those files referenced dozends more files that came as part of harmony. It took me quite a while to just more or less figure out what the project was doing. And it didn’t do anything yet except setting some clock and port settings. Just a nightmare.

20160514_StandaloneAnemometer_045

But I felt I had few other options so I continued with harmony anyway. And after a few hours I had an almost working USB device. It enumerated just fine but I couldn’t send any data from or to it. It took me more than a week to finally get it working. In the end it was just a single character: a 1 instead of a 2 in one of the configuration files. But until then I had spent a lot of time with that harmony code and was forced to read through a lot of its documentation which is worth thousands uppon thousands of pages of PDFs.

So USB was finally working and I had acquired some rudimentary understanding of MPLAB Harmony. I still hated the whole framework but I thought that I now understand it well enough to change the code to suit my taste. So I spent another few nights trying to do that until it dawned on me that this is leading nowhere. Fortunately, by that time I had read and learned some more about Harmony and was willing to give it another try working with it as opposed to against it. So for the last week or so I was doing that.

And while I still don’t love everyting about it I now feel comfortable working with that library. I’ve tried to follow its conventions and recommendations even where they didn’t make too much sense to me. I think this will make it much easier for others to work with my code and chances are that the conventions and recommendations will start to make more sense as I get more familiar with the framework. And its nice to know that I can integrate another module or migrate to another microcontroller without having to re-invent everything.

20160428_StandaloneAnemometer_037

That was a long introduction but after all that pain the last few weeks I just had to write that down. Now to business.

USB

The anemometer inplements the USB HID (human interface device) class. While mainly aimed at devices such as mice and keyboards, this USB device sees a lot of use in applications that have nothing to do with human interaction. You can transfer up to 64 kbytes of data (64 bytes every millisecond) in each direction with guaranteed latency and that’s plenty for many applications. That data can be anything and in any format you like. And the good thing is that you don’t need to write your own drivers. You can free-ride on the device drivers that came with the operating system just like you don’t need to install a driver when you attach a new keyboard to your computer.

I’ve written a bit of code on top of the Harmony library to provide the main application with a simple to use interface. It nicely encapsulates the the USB logic and data and adds a bit of buffering functionality on top of that. It’s just two files: app_usb.h and app_usb.c in the app_usb subfolder. You can basically include them in your project and they handle all the USB stuff for you.

Once initialized, the necessary code runns inside an interrupt service routine (ISR) so the main application has nothing to worry about. All the USB data including the data buffers are private to the app_usb.c file. The app_usb.h defines just 8 simple, non-blocking functions:

  • void app_usb_init(void);
  • bool app_usb_isReady(void);
  • uint8_t* app_usb_getReceiveBuffer(void);
  • uint8_t app_usb_getReceiveBufferCount(void);
  • uint8_t* app_usb_getTransmitBuffer(void);
  • uint8_t app_usb_getTransmitBufferCount(void);
  • void app_usb_freeReceiveBuffer(void);
  • void app_usb_sendTransmitBuffer(void);

At system initialization you call app_usb_init(). But you can’t expect to have an USB connection. You need to check app_usb_isReady() every time. You never know if there is a USB cable plugged in and even if you had a connection that cable might be unplugged at any time. The module handles all that hot plugging/unplugging gracefully.

20160428_StandaloneAnemometer_038

The module implements a circular buffer for both received packages (aka frames) and packages to be sent. Each package is 64 bytes in size and the ring buffers can be set at compile time but must be a power of 2. Currently the receive buffer consists of 4 frames and the transmit buffer of 8 frames.

The app_usb_getReceiveBufferCount() informs the caller how many new USB frames have been received if any. app_usb_getReceiveBuffer() then returns a handle to the first received frame. FIFO – First In First Out. Once the frame is no longer needed the application calls app_usb_freeReceiveBuffer() and the buffer can be re-used.

Sending data works similarly simple. app_usb_getTransmitBufferCount() returns the number of transmit buffers currently in use. If this  number is smaller than then number of buffers then more data transmissions can be scheduled. Get a handle to then next buffer by calling app_usb_getTransmitBuffer(), write the data to be sent to the buffer and then call app_usb_sendTransmitBuffer().

Taking measurements

This way the main application can focus on more interesting tasks such as measuring wind speed and direction. The first task for doing so is sending some pulses.

SendReceiveOverview

If you’ve alredy followed this project for a while you are probably familiar with the kind of screenshot above. Bursts of a PWM signal at 40kHz (SIGNAL, red) are sent trough ultrasonic transducers. Note that the signal is now active-low (i.e. inverted) since the mosfet drivers used to drive the transducers are themselfs inverting.

As before, the DIRECTION  and AXIS signal determine which transducer is transmitting and receving. The SCLK and MOSI signals are just used for debugging purposes for now. They indicate when an ISR is running which helps a lot since in this example ALL the code is running inside an ISR.

TimeZero

As you can see above, the AXIS and DIRECTION signals are set a few microseconds before we start sending pulses. The first edge of the burst occurs when the 32 bit-timer (consisting of the 16-bit timers TMR2 and TMR3) is cleared. This is the point in time all our measurements are referenced to. The timer runs at the full CPU clock of 48Mhz so the resolution is about 20.8 nanoseconds.

SendReceivePWM

Output Compare module 2 (OC2) handles the PWM pulses. Currently each burst consists of 12 pulses. At 48MHz a full wave equals 1200 clock cycles as opposed to 400 on the Arduino previously used. Note that the frequency of the pulses is precisely 40kHz as expected and that very little time is spend in ISRs despite the unoptimized C code.

SendReceiveCloseUpWithComments

The timer overflows precisely 512 times per second so each measurement takes a little less than 2 milliseconds. Output compare module 1 (OC1) can be used to generate an interrupt at any time during that interval. Currently it does three things: It takes care of the AXIS and DIRECTION signals which are set just shortly before the timer overflows. It also triggers the measurements of the zero-crossings and cancels them if they don’t complete withing reasonable time.

ZCD_Capture

The input capture module 4 (IC4) captures the zero-crossings of the received and amplified signal. The board contains a high speed comparator to detect these events so the microcontroller only needs to measure the precise time whn they occur. The IC4 module has an internal buffer so we don’t need to generate an interrupt after every capture. I’ve currently set things up so that an interrupt occurs after 4 values have been captured up to a total of 32 measurements.

Commicating the results over USB

In order to find the wind speed and direction we need to somehow identify the peak in the received signal which is where the ADC comes in. But I think this is enough for now and I instead show you how the measurements taken so far can be sent to a PC via USB.

The board doesn’t have any display or anything to communicate with a human. There’s not even a status LED we could blink. That would have been nice but there are just not enough I/O pins unfortunately. So connecting the board to a PC via USB is a straight-forward way of communicating with this device.  Actually, USB will be the main testing and debugging tool during development. The in-circuit debugger isn’t very useful in this application since the measurements have to happen in real time.  Setting breakpoints will just mess things up.That’s why I insisted to get USB working first.

I’ve downloaded a simple terminal called YAT (yet another termial) that allows me to easily talk to the anemometer board. The anemometer looks at the first character in any message sent from the host and then decides what to do. So far I’ve implemented:

  • ‘T’: Return the current value of the 32-bit timer
  • ‘Z’: Return axis (0/1), direction(0/1), measurement count (0-31) values as well as the results of the first 9 zero-crossing measurements
  • Anything else: Echo back the received string

Here’s what my chat with the Standalone Ultrasonic Anemomete looked like.

YAT_Capture

Of course, the measurement is far from complete at this stage but I think this is a nice foundation to build uppon. The code is quite clean for this early stage of development and being able to communicate with the device in real-time over USB is really a great advantage.

The software can be downloaded on the project over view page and as always I appreciate any feedback.

The next post on this project can be found here.