Spiraling Under Control

One of the staples of fixed wing autopilots is the circle hold.  A circle hold is the closest thing you can get to a pause button with a vehicle that must be in constant forward motion to stay aloft.  There are a few hidden challenges in the task, including wind compensation and some unexpected coupling that can lead to weird looking oscillations if not handled well.  People have been doing circle holds with UAV’s for a long long time, so I don’t bring anything new to the table, but it is always fun to play, err I mean experiment.

Circles

What happens if you periodically move the center of your circle (maybe every 5 mintues) to a new location, hold for a while, move the circle center again, circle for a while, and repeat?  Well short answer is you end up with a bunch of circles, but if you are strategic in the placement of the circle center, some pretty patterns can begin to emerge.  To add visual interest we can also change the circle speed when we move the center of the circle.  Increasing the circling speed, increases the circle radius.

fgfs-screen-001

What if each time we move the circle center point, we move it by a fixed angle (let’s try 30 degrees), and increase the offset distance by a little bit, and also in crease the airspeed by a 1 kt?  An interesting spiral pattern begins to emerge.  From the original starting point, each circle is a bit bigger than the one before, and also a bit further away.  A spiral pattern begins to emerge.

fgfs-screen-002

A flight simulator isn’t encumbered by battery or fuel limitations, so what happens if we let this run for a long time?  The spiral pattern continues to develop and grow.fgfs-screen-003

Spirals aren’t that big of a deal of course.  20 minutes of python coding could produce some far fancier spirals.  What interests me is how the patterns are produced … this is the flight track of a simulated UAV and that makes it a bit more challenging and fun.

Continuous Spirals

What happens if we fly a basic circle hold, but instead of changing the circle center point every 5 minutes, we continually move the center target of the circle in sweeping spiral pattern?  We would get something that looks a bit like a stretched spring viewed from a bit of an angle.

At the beginning of the pattern, the airspeed is set to 25 kts.  The radius (not of the circle hold but of the spiral) is set to 0.1 nm.   Each second the position is swept forward 0.125 degrees.  This means the spiral pattern sweeps forward 7.5 degrees per minute, or 450 degrees per hour.  The airspeed and spiral radius are also increased by a tiny bit each second.  The next picture shows the pattern after a bit more than an hour of flight.

fgfs-screen-004

After about 5 hours of flight we get the next picture:

fgfs-screen-006

And if we let the simulation run over night and zoom out the map a couple steps, we get:

fgfs-screen-007

A Few More Details

All these patterns were produced by the flight track of a UAV.  That means we aren’t just plotting mathematical functions, but instead are combatting wind and physics to produce these patterns.  A complex system of sensors, attitude estimation, control theory, navigation and planning blends together to produce the end result.

Simulation vs. Reality

All of this was flown in the FlightGear.org flight simulator.  However, there is a much stronger tie to reality than might first appear.  FlightGear is the ‘stand in’ for reality.  However all the sensor data is sent externally to the “avior” autopilot running in “software in the loop” testing mode.  The avior autopilot code sends all the raw sensor information (simulated IMU and simulated GPS) into a 15 state kalman filter to estimate the actual roll, pitch, and yaw.  It would be possible to cheat and use the simulators exact roll, pitch, and yaw, but the “avior” can’t cheat in real life (because this information isn’t directly available) so it faithfully estimates these values in simulation just like it must in the real aircraft.

The roll, pitch, & yaw estimates are then passed to flight control system and compared with target values for basic flight control and navigation.  The “avior” autopilot computes control surface deflections to eliminate the error between target speed, and attitude vs. actual speed and attitude.

Finally, these control surface positions are sent back to FlightGear which then computes the flight physics based on where the avior moves the control surfaces and throttle.  FlightGear computes new gyro, accelerometer, and gps sensor values, sends them to the avior autopilot, and the process repeats.

In this way we can test the “avior” autopilot quite thoroughly using the simulation.  The avior thinks it’s really flying, it receives realistic sensor data, drives control surfaces as if they were real servos, and the simulator responds realistically.  Really the only part of the avior not being thoroughly exercised is the specific code that reads the real world sensors and the specific code that drives the real world servos.

Wind

At first glance, the job of flying a circle hold around a fixed center point amounts to holding a fixed bank angle.  There is a relationship between airspeed, bank angle, and turning radius, so we just need to work out these numbers and we can fly any circle of any radius at any speed, simply by computing the required bank angle.

But things get a bit more complicated than this because we need to adjust our actual heading and bank angle to compensate for drifting inside or outside the target circle radius.  And there is this whole business of figuring out how to smoothly enter the circle pattern from any starting position and heading inside or outside the circle.

I’ll skip over the boring details (ask if you are curious) but along with all the other things that must be accounted for, the real world almost always has a little (or a lot) of wind.  Flying up wind, small heading changes of the aircraft can yield large changes in your ground track heading.  Imagine a worst case scenario where you are flying at 30 kts, exactly into a 30 kt head wind.  You are hoving relative to the ground.  But even the tiniest heading change (or wind change) will slide you 90 degrees left or right.  The opposite happens when you are flying downwind.  Aircraft heading changes produce proportionally smaller ground track heading changes.

Wind adds some unique challenges to flying circle holds that are actual circles from a ground perspective.

Coupling

I also wanted to say some brief words about coupling between axis, because it can be a bigger issue in circle holds than might first be expected.  Imagine you are flying a perfect circle hold in zero wind.  You are at a 30 degree bank, at your target airspeed, and at your target radius.  Now imagine you are a bit outside of the target radius.  You need to bank a bit more to tighten your turning radius.  But this tighter bank could cause a loss of altitude (basic airplane physics).  If the aircraft responds to the lost altitude with increased elevator, this will tighten your turn even more because you are banked.  It is easy to over shoot and end up inside the circle, which means the flight controller will command the aircraft to fly less of a bank, increasing the circle radius, but that creates more lift, more climb, etc.  Roll, pitch, and throttle can combine in some very awkward ways during a circle hold and that, along with wind and all the other aspects of basic aerodynamics and physics can make flying an accurate and stable circle hold a bit more of a challenge than you might first expect.

External Scripting

Hah, if you are still reading all the way down here, you are really a UAV geek (or you are following good skimming rules of reading the first paragraph, the last paragraph, and looking at the pictures.)

One of the fun things about the avior autopilot is that all the sensor data, attitude estimations, control surface positions, navigation state, and just about every other interesting variable is published in a giant hierarchical tree of name/value pairs.  If you’ve poked inside the windows registery, it’s kind of the same basic idea, except all in memory and very fast to access or update.

The cool thing about this is that we can expose external interfaces to this giant data structure and completely command or monitor the autopilot externally.  This enables a developer to write a perl or python script to monitor and command the autopilot.  What sorts of things could such a script do?

  • Command the autopilot to do a circle hold, then smoothly adjust the center point of the circle hold to produce interesting patterns in the UAV flight track.  That’s what this whole article is about.
  • Fly specific flight test maneuvers repeatably and accurately.  Do you want to nail down the exact stall speed of your aircraft under different scenarios?  You could write a script to fly the aircraft into a stall, then recover, climb to safe altitude, repeat.  You could write scripts to put the aircraft into all kinds of different specific flight situations and carefully record the data.  What is the elevator trim and power settings for level flight @ 25 kts, 30 kts, 35 kts, 40 kts, etc.  How about at a 5 degree bank, 10 degree bank, etc.
  • Create higher level intelligence without having to write code inside the core autopilot.  The autopilot does everything for the aircraft, and it must be reliable and robust and never fail or do something dumb.  This comes through long hours of flight testing.  Now you want to go fiddle around under the hood and change something?  That is begging for trouble!  Why not leave the autopilot alone and write your new functions in an external script?  Maybe you could write a fancy engine-out auto-land script that knows the basic performance characteristics of your aircraft and can plot and command an optimal approach path to touch down from any position and altitude to any landing strip in any wind conditions.

RC Aircraft Precision Balancer and Work Stand

This morning I whipped together a “precision aircraft balancer” (like the Great Planes “C.G. Machine”.)  I built it out of $5.57 worth of PVC pipe and connectors from Fleet Farm and it probably took me an hour at the most.

The Plan

Here is my concept drawing:

IMG_20130625_083257

Shopping List

Here you are looking at $5.57 worth of PVC parts purchased locally.  The one flaw in the original design is that no one locally sold those 3-way corner connectors.  Maybe they don’t even exist?  So I made an on the fly design change while I was shopping.  The new design uses a “T” connector and a 90 degree elbow with 1.5″ long pieces of pipe connecting them.  The parts list is: 8 x 90-degree elbows, 4 x “T” connectors, 14′ of 1/2″ PVC pipe (in 2 10′ sections.)  I went with 1/2″ PVC and that is plenty strong for my needs, but 3/4″ PVC would work just as well and make the stand a bit beefier.

IMG_20130625_093038

Construction

Cut the straight sections and fit it together.  There is no rocket science, but do remember “measure twice, cut once”.  Here you can see the parts starting to come together.  How exciting! 🙂

IMG_20130625_095317

Finally here it is all put together:

IMG_20130625_095757

IMG_20130625_101425

You might imagine that if the parts are only friction fit together, the two rails could flop over if you placed a heavy model on top.  So what I did was use PVC cement to glue the joints between the “T” connector and the 90 degree elbow connectors at the base.  I left everything else just friction fit so I could potentially take it apart for transport/storage.

Finished Stand

Finally, here is the payoff picture of the stand in action!!!  Yes, those are Christmas decorations that have not found an off season storage location.

IMG_20130625_101909Modifications

There are a variety of modifications that could be made to the design

  • Add pipe insulation to the top rails to help protect your more fragile models
  • Go with bigger PVC (like 3/4″) to make a beefier stand.
  • Drill a vertical hole into the top rail to insert a peg.  (A bolt with a rounded head with a nut screwed most of the way in makes a nice drop in peg.)  Make marks on the top rail in your favorite units.  Now you have a “Precision C.G. Machine” and saved yourself $50 at the hobby shop.  Personally I would suggest locating the peg about 1/4 to 1/3 from the rear along the top rail (not dead center) so it’s easy to just place the aircraft forward and use it as a stand without removing the pegs.
  • If you add balancing pegs, make them drop in/removable and tether them to the rail with dental floss so you can use the device as a stand without worrying about scratching or denting your model with the balance pegs.
  • Adjust the dimensions.  I built this for a flying wing with a 16″ wide fuselage so I made my stand really wide.  I also made it pretty tall to accommodate setting the aircraft on it inverted (leaving room for the vertical fins.)  If you have a different aircraft in mind, it might make sense to adjust some of the dimensions … but don’t make it too tall and skinny or it’s likely to blow over in the wind at the field.
  • Do an image search for Escher and instead of making an aircraft stand, try to build some sort of perspective/perpetual work of art.

Sold the P-47

I sold my P-47 on craigslist today.  I liked it, but for whatever reason, it wasn’t my favorite to fly and I’ve got my eye on something else … but I need to free up some space first … !  I really enjoy flying my PBY though … I need to set up a category and post a few pictures of that soon!

“fedup” with Fedora!

Fedora 18 “Spherical Cow”

f18release

I think everyone has a bit of a love/hate relationship with their technology.  We hate it when it doesn’t work, or we can’t figure something out, or something breaks or doesn’t make sense.  But we love the new upgrade, the fancy new desktop background, animated menus, or what have you.  Fedora 18 was just recently released so of course I had to jump on that and get all the new stuff here as quickly as possible.  Is it great?!?  Was it worth the wait?  Is it a waste of time?  Do I love it?  Do I hate it?  Yes!

fedup (or fedora upgrade)

Over the past week I’ve been migrating several of my machines from Fedora 17 to Fedora 18.  The old “preupgrade” tool that was available for upgrading your system to new releases no longer is available for upgrading to fedora 18. Instead a new utility called “fedup” is provided.

What do I think of the new “fedup” tool?  For me on my systems it has been a resounding #fail.  Both systems I tried to update got trashed.  In the first case I was able to run “fedup” and do the initial pre-load.  Upon rebooting I was able to do the “upgrade” boot and the installer ran all the way through to the end and it all looked really good.  But when I rebooted after completing the upgrade I found a mess.  My system couldn’t boot or booted partially into an error state of not being able to find what it needed.  I didn’t continue to debug or try to figure out what happened.  Personally I’d rather have a fresh clean system, than a trashed system that’s been just barely patched together enough to boot and run.  So I blew everything away and loaded from scratch off the DVD ISO.

On the second machine (a laptop this time.)  I ran fedup and prep’ed the system for upgrade, rebooted into the upgrade installer and proceeded with the upgrade.  But partway through the package installation process my entire machine rebooted with no warning.  This laptop isn’t prone to doing that sort of thing.  Blame it on the hardware?  Maybe, but …. ???  This also left me with a system that wouldn’t boot, so again I blew it all away and loaded Fedora 18 from scratch off the DVD.

In both cases, installing from scratch from the DVD worked flawlessly after seeing fedup fail.  On my other machines, the DVD install from scratch has worked well.  So fedup is a #fail, but otherwise I’m happy.  There’s something to be said about a clean system that hasn’t carried over all the cruft from previous revisions and years of use, so I’m not entirely unhappy that I was forced to install my systems from scratch.  (I have a sophisticated backup system “backuppc” and store my home directories on separate hard drives, so an install from scratch is not as big a deal as it might be if I had everything on a single drive with no backups.)

Freshly installing Fedora 18

In all cases (for me) installing from scratch has worked perfectly.  I’m disappointed that the upgrade didn’t work, but the fresh install procedure works quite well.  In my case what ultimately happens with a fresh install is that later I stumble on packages I forgot about or configurations or tools I had setup for some task on the old machine, and a few months later when I need to do something again, I discover that and need to scramble to get it going again from scratch on the new system.

Here are some installation hints, tips, and tweaks for Fedora 18 that I discovered along the way:

  • Naming your machine: the layout of the network config dialog box caused me to miss seeing the field where you enter the machine name.  When I was all done, I had “localhost.localhost” which I was not happy about.  I used: “hostnamectl set-hostname <name>” to set the domain name (which seems to be the way to do it on Fedora 18).  There are some nuances of fully qualified domain names that I’m not sure I got 100% right, but for now it’s close enough, the machine has a name.  The real answer is to make sure you enter your machine name during the install process (in a box way down in the lower left of the screen that can be easy to miss.)
  • Picking a drive: one other area of the installer that I tripped on was also mainly due to screen layout/ui issues.  I was installing over the top of an existing linux system and I wanted to wipe those existing partitions.  So after selecting the target disk, there is a continue button hidden in the lower right corner of the screen.  Hit that and you can go on to “reclaim” the space, delete the existing partitions and let the installer automatically reformat and repartition that area that is now available.  (Note it happily works around existing windows partitions on a system that’s already setup for dual boot.)
  • Nvidia drivers: several of my machines have nvidia graphics hardware.  I am heavily involved in FlightGear which requires 3d hardware acceleration.  The nouveau drivers are ok for desktop work, but no where close to good enough for all out 3d graphics.  In the past I’ve downloaded the NVIDIA driver from nvidia.com and installed things manually.  This time around I added the rpmfusion.org repository and installed the akmod-nvidia package.  This seems to have worked well so far.  We’ll see how it gets through a kernel upgrade.  Being left in the cold for a few days with package mismatches isn’t really an option for me so I could be back to manual installation before long — depends on how quickly the rpmfusion.org guys can track fedora updates.

Tweaking for Personal Preferences

No one likes a straight up stock machine (except maybe iUsers) so right out of the starting gate we need to tweak and configure several things.  Here is my list of “must tweaks.”

  • “yum install vino”  This adds desktop sharing.  I have several computers on my home network and this helps manage and use them by allowing me to share and view desktops from one machine to the next.  I don’t need a monitor and keyboard and desk for each computer.  Look for “desktop sharing” to enable this and run “remote desktop” to connect to shared machines.  And yes, if you are wondering, I am a heavy ssh/command line  user too. 🙂
  • “yum install gconf-editor”  This is a graphical tool that allows you to tweak gnome-shell options.
  • I run 2 monitors on my main machine and by default, gnome-shell makes all windows on the second monitor follow me to every virtual desktop.  If you aren’t sure what a virtual desktop is, then sheesh, how do you live?  I’d give up my coffee before my virtual desktops!  So to make the second monitor obey desktop switching run gconf-editor and Desktop->Gnome->Shell->Windows-> uncheck workspaces_only_on_primary
  • By default gnome only maps 4 virtual work spaces to hot keys.  Virtual desktops (err work spaces?) are worthless without being able to hotkey between them.  From a shell you can run the following command to assign Alt-1 to switching to the first virtual desktop.  Then replace 1 with 2, 3, 4, … to assign hot keys for up to 9 work spaces.  I usually do 6, that’s as crazy as I get: gsettings set org.gnome.desktop.wm.keybindings switch-to-workspace-1 “[‘<Alt>1’]”
  • For what it’s worth, I tend to setup specific tasks (like email, or working on a program, or web browsing) each in their own virtual desktop, and then throughout the day I can hotkey back and forth between them as needed.  For the cynical, this is sort of like the instant spreadsheet “boss hack” on the old video game that I can’t remember the name of now.  Facebook and google+ can get their own virtual desktop. 🙂
  • Autologin: I’m getting lazy in my old age so why not setup the machine to log me in automatically?  In “System Settings” (under user name in top bar when logged in) select “User Accounts”. Select the account and enable “automatic login”.
  • rpmfusion.org provides a number of packages that aren’t available in the default Fedora distribution.  I like installing mplayer which plays all those odd format movies.  Or maybe you want to be able to play mp3’s from rhythmbox.  Run this long command as root: yum localinstall –nogpgcheck http://download1.rpmfusion.org/free/fedora/rpmfusion-free-release-18.noarch.rpm http://download1.rpmfusion.org/nonfree/fedora/rpmfusion-nonfree-release-18.noarch.rpm  Then install what you want.  In my case I do: yum install mplayer ffmpeg gstreamer-plugins-bad gstreamer-plugins-bad-nonfree gstreamer-plugins-ugly unrar
  • NVIDIA hardware accelerated opengl drivers: A must for any gamer or flight sim enthusiast (or flight sim developer!)  Once you setup the rpmfusion.org repository you can run “yum install akmod-nvidia” to install nvidia drivers for your system.  Be sure to reboot to activate them.
  • Here is my personal list of extra packages I like to install on any fedora system: yum install emacs jpilot lsb gnumeric subversion subversion-devel apr apr-devel openal-soft openal-soft-devel freealut freealut-devel freeglut freeglut-devel libudev-devel fltk-devel fltk-fluid libopenvrlm-devel system-config-lvm librsvg2-devel libpng-devel libjpg-devel texi2html chrpathopencv opencv-devel aspell lm_sensors gnome-shell-extension-weather gnome-shell-extension-cpu-temperature gnome-shell-extension-systemMonitor gnome-tweak-tool libreoffice minicom inkscape
  • Virtualbox: I’ve always run virtualbox (now owned by oracle) but Fedora by default now has something called “boxes”.  I need to check that out at some point and see if it works.  If I can migrate my disk image over without needing to reinstall Windows XP again from scratch it might be worth doing, just to use default packages.  Oh by the way, I’m a linux guy, but I have windows xp setup in a virtual box to run a couple small programs once in a while.
  • Do you want to see the date on the status bar?  Run gnome-tweak-tool and do: Shell -> show date in clock -> on
  • Do you want google chome?  Go download the package from google and “rpm -Uvh <filename>.rpm”  Make sure you have run “yum install lsb” first to get the required supporting libs.

Conclusion

So far I’ve been very pleased with the newest release of Fedora.  Fedora 18 is a worthy successor to Fedora 17 and the previous versions too.  If you are coming from some other platform, you may find aggravations or things that don’t work (or don’t work the same way.)  But if you are coming from a Fedora background, everything I do works at least as good or better in the new Fedora 18.  With a bit of tweaking for personal preference, it offers a very solid and very powerful system with recent versions of the kernel, gnome, gcc, libreoffice, gimp and other major software packages.  It is built around standard open source packages so if there are glitches or things I (or others) might not like, you will often find the exact same behavior in other modern Linux distributions that are built on the same packages.  The upgrade installer “fedup” is worthless as far as I’ve been able to see.  But installing from scratch works great.  I can’t say if Fedora is better or worse than other linux distributions (I know we all have our personal preferences) but I will say that I’m a solidly commited “linux guy” and Fedora 18 is really great and the best Fedora so far.

 

Python Airfoil Manipulation Library

For lack of a better title …

I am creating a set of python libraries for designing and modeling aircraft.  Rather than spend a couple months learning a complicated and expensive CAD tool, why not spend that time learning python?  It makes perfect sense to me. 🙂

Scripted modeling (versus interactive point and click modeling) is a different mind set, but the advantage is you can make a change to the script and rerun it and that change cascades through all the parts and drawings and layout sheets.  In a gui based CAD system if you need to change the radius of an alignment hole that runs through all your wing ribs, you might have to painstakingly edit each and every rib, right?  What if you want to move a stringer, or add an lightening hole, or increase the wing chord by 10%? Those can be daunting tasks in a typical cad system.  But in a scripted modeling system you may just need to change a number, or add a couple lines of code, and rerun the script and you are done.

Here are a few pictures to illustrate the sorts of things I am up to.  If you are a model builder I think you will immediately see what is going on.  Please click on the illustration for larger fully detailed versions.

The following image shows blending two different airfoils: NACA 63(3)618 into NACA0015.  Also shown is the ability size the airfoil to any scale and rotate it to any angle of incidence.

demo-blend

The next image shows (1) the ability to read in a standard airfoil plot, (2) fit a smooth spline interpolation through the original data set, (3) resample the airfoil at any resolution and step size, and (4) do an adaptive fit of the higher resolution data that conforms to a specific error tolerance.  Data reduction and fitting can be important for to keep file sizes from growing too large and for reducing cut times.

demo-fit

The final image shows features that are important to modelers.  The ability to cut in spars of any width and height that are flush with either the top or the bottom.  The ability to cut out stringers that are either vertical or tangent to the surface of the airfoil.  The ability to cut out a leading edge diamond and automatically orient it for the best fit and minimal sanding.  And finally the ability to cut lightening holes and add build alignment tabs.

demo-cutouts

Another capability the library currently has (not shown in the illustrations) is the ability to skin an airfoil by some width.  The library will shave off that amount in a sweeping arc that follows the original contour of the airfoil.  This would be appropriate (for example) if you planned to sheet your wing with 1/16″ balsa.  You can shave off that 1/16″ from the ribs so that when you do the final sheeting, you will be back to the exact airfoil dimensions you intended.  You can also shave off portions of the airfoil if you plan to only sheet a part of the wing and leave part of it as an open framework.

If you are curious what the python code to create these images looks like, you can go to the links below, but for example here are some basic lines of code you can add to your script:

Load an airfoil, do a smooth spline interpolation, and resample it at 1000 steps:

root = airfoil.Airfoil("naca633618", 1000, True)

Blend two different airfoils together with some weighted percentage:

rib = airfoil.blend( root, tip, percent )

Add a lightening hole at a specific location and radius:

rib.add_hole( hx, hy, hr)

Next up: the next major component of this system that I hope to tackle is laying out the top down plans of the wing. The output would be an svg (or pdf) file that you could send to a large format plotter and print out the exact wing plan for construction.

If you are interested in taking a closer look at this project, I have setup a git repository with all the code and demos at the following link:

The project README file (which includes quite a bit more background and details) can be read here:

I’m Thankful for my Senior Telemaster

This Thanksgiving day I’m thankful for many blessings: family, friends, neighbors, shelter, food, our siberian husky who lived 16 years, and many other things.  The weather was nice Thanksgiving morning so I was thankful to have an hour to run out to the field first thing to do some flying.

On Thursday, November 22 (Thanksgiving day) my Senior Telemaster past an interesting milestone: 12 cumulative hours of fully autonomous flight. This may not sound like a whole lot, but it represents 58 separate flights over the span of 3 years. In every flight it has performed beautifully and majestically and very scale like. It is not a fast aircraft, but it’s solid, forgiving, and controllable even at very slow airspeeds. It has a lot of room, a lot of carrying capacity, and it’s very tolerant of CG changes. I have flown it on calm days and I have flown it in up to 27 kt winds (31 mph) that were gusting to higher at times. With a set speed of 30 kts there have been times it has been blown backwards in flight! She has seen sun, clouds, fog, drizzle, and even rain. Winter, summer, spring, fall, hot days, cold days — she’s seen just about everything. Through all of this it has been a solid, reliable, patient, unfailing work horse — and she’s still going as strong as ever!

She has been a test bed for 4 major autopilot revisions:

  • An original gumstix :gumstix” processor + a Xbow MNAV sensor head.
  • A gumstix “verdex”+ a sparkfun 6DOFv4 IMU
  • A gumstix “verdex” + a VectorNav VN-100T temperature calibrated IMU
  • A gumstix “overo” + a 3D Robotics APM2.5 “sensor head”

I recall one close call where I made a code+hardware change and didn’t check it thoroughly enough.  Transitioning to autonomous flight resulted in an immediate full throttle dive towards the earth.  I switched to manual mode (almost not quickly enough) and was able to manually recover from the dive just in the nick of time.  That is the only time I’ve put any serious flex on the wings!

I recall one landing when the farmer’s corn was 8′ tall and completely surrounding our little patch of flying field.  I typically had to come over the edge of the corn with inches to spare in order to get it down and stopped before the end of our flying field.  On this day we had crazy gusting cross winds and as I cleared the corn the wind just fell out from under the telemaster.  It dropped from maybe 10′ of altitude and came to a complete stop no more than 5′ from the approach edge of the corn.  That has to be my all time shorted landing with any aircraft (only counting landings on the wheels.) 🙂

So thanks to my trusty work horse for many good years of service with hopefully many more to come!

Setting up “autologin” on a gumstix running the 3.5 kernel (yocto, poky, et. al.)

The gumstix.org wiki has a page on how to configure your gumstix to auto-login on boot.  This can be very nice for “production” systems where the intention is to power on and run some specific firmware/code every time.

However, with the new Yocto/Poky images based on the 3.5 kernel, things have changed and the old instructions no longer work.  Here is a quick recipe to get autologin running again on the newer systems.  First of all credit to http://fedoraproject.org/wiki/Systemd for their section on setting up autologin on a virtual terminal with the new systemd architecture.

Step #1:

Compile this “autologin.c” program and install it to /sbin/autologin (make sure you have executable permissions, etc. etc.)

#include <unistd.h>
#include <stdio.h>
#include <string.h>
 
int main()
{
       int nrv = 0;
       FILE* fptr = 0;
       char user[64];
 
       // clear buffer
       memset(user,'\0',64);
 
       // open autologin profile file
       fptr = fopen("/etc/autologin.profile\0","r\0");
 
       // make sure the file exists and was opened
       if (fptr != 0)
       {
               // the return value from fscanf will be 1 if the autologin profile name is read correctly
               nrv = fscanf(fptr,"%s\0",user);
       }
 
       // only autologin if the profile name was read successfully,
       // otherwise show the regular login prompt
       if (nrv > 0)
               nrv = execlp("login\0","login\0","-f\0",user,0);
       else
               nrv = execlp("login\0","login\0","\0",0,0);
 
       return 0;
}

Step #2

Create the /etc/autologin.profile file by running:

echo "root" > /etc/autologin.profile

The autologin program looks for this file to determine which user id should be autologged in.

Step #3

Setup the systemd configuration.

cp /lib/systemd/system/serial-getty@.service /etc/systemd/system/autologin@.service
ln -sf /etc/systemd/system/autologin@.service /etc/systemd/system/getty.target.wants/serial-getty@ttyO2.service
cd /etc/systemd/system/getty.target.wants/
vi serial-getty@ttyO2.service

Next, change the line that reads”

ExecStart=-/sbin/agetty -s %I 115200

to read:

ExecStart=-/sbin/agetty -n -l /sbin/autologin -s %I 115200

Troubleshooting

  • If you still get a login prompt, make sure you created the /etc/autologin.profile file correctly, the autologin program needs that or it will just execute a standard login prompt.

Step #4

You may find yourself in a situation where you may not always want your code executed automatically.  You may want an option to “break in” and get a prompt.  There are many ways you could do this, but here’s one simple way:

Compile the “pressanykey.c” code and install the executable in /sbin/pressanykey

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <termios.h>
#include <unistd.h>
 
int kbhit(void)
{
    fd_set rfds;
    struct timeval tv;
    int retval;
    struct termios term, oterm;
    int fd = 0;
    tcgetattr( fd, &oterm );
    memcpy( &term, &oterm, sizeof(term) );
    cfmakeraw(&term);
    tcsetattr( fd, TCSANOW, &term );
    /* Watch stdin (fd 0) to see when it has input. */
    FD_ZERO(&rfds);
    FD_SET(0, &rfds);
    /* Wait up to one seconds. */
    tv.tv_sec = 1;
    tv.tv_usec = 0;
    retval = select(1, &rfds, NULL, NULL, &tv);
    /* Don't rely on the value of tv now! */
    tcsetattr( fd, TCSANOW, &oterm );
    return(retval);
}
 
int mygetch( ) {
    struct termios oldt, newt;
    int ch;
    tcgetattr( STDIN_FILENO, &oldt );
    newt = oldt;
    newt.c_lflag &= ~( ICANON | ECHO );
    tcsetattr( STDIN_FILENO, TCSANOW, &newt );
    ch = getchar();
    tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
    return ch;
}
 
int main(int argc, char **argv) {
    int count = 5;
 
    if ( argc > 1 ) {
	int tmp = atoi(argv[1]);
	if ( tmp > 0 ) {
	    count = tmp;
	}
    }
 
    printf("Press any key ... ");
    fflush(stdout);
 
    while ( count >= 0 ) {
	printf("%d ", count);
	fflush(stdout);
 
	//int result = mygetch();
	if ( kbhit() ) {
	    return 1;
	}
	//sleep(1);
	count--;
    }
 
    return 0;
}

Next create a ~/.profile file that includes the following:

  /sbin/pressanykey 5
  if [ $? != 0 ]; then
    echo "Starting interactive shell"
  else
    echo "Continuing with default"
    /path/to/my/code
  fi

Now, along with autologging in as root (or which every user you specified) you will then be presented with a count down timer similar to the “u-boot” timer where you can press any key to get a shell prompt, or continue to your firmware code if no interaction is required.

Hacking the APM2 Part #5: Flight Testing

This is the payoff video showing the hybrid autopilot system in action in the Resolution 3 airframe. (By the way, this is HD video so watch it full screen if you can!)

I am skipping many details between integrating the hardware and flying, but just as a quick overview:

We first integrated the system into a Senior Telemaster.  After 4 trips to the field over the span of 2 days, numerous flights, and a bunch of work in the evenings, we felt like the system was coming together and working every bit as well as it was supposed to.  There are always more things we could do with the telemaster airframe, but now that we were fairly confident that the system was working end-to-end as designed, we dropped it into our Resolution 3 (blended body, composite flying wing airframe.)  The new hybrid autopilot system needed some gain adjustments versus the old prototype autopilot so we guessed at those based on what changes were needed with the Telemaster configuration.

We enjoyed a flawless bungee launch of the wing, climbed to altitude, flipped over to AP mode, and the aircraft flew off flawlessly and ran through it’s demo routine without a hitch.  The clouds were dramatic and we noticed a rain squall moving in, so we landed and packed up just as the rain set in.

Here are some high points of the new system:

  • 800Mhz ARM processor (with hardware floating point) running a 15 state kalman filter and all the autopilot and navigation code.
  • WGS-84 math used for heading and route following.
  • Accurate yaw estimation when the filter converges.
  • Accurate wind estimation
  • 100hz sensor sampling, 100hz filter updates, 100hz autopilot and navigation updates, 100hz actuator updates with up to 400hz PWM signal generation rate for digital servos.
  • APM2 sensors.
  • Tablet/smart phone/laptop ground station interface.

If you just like airplanes, here’s some nice footage of our Telemaster landing.  This video was taken during our 2 days of Telemaster integration effort …

Landing in psycho winds:

In calmer winds:

Last flight of the day:

Hacking the APM2 Part #4: Laying out a “hybrid” system

Imagine for one second that you are a UAV developer. The DIYdrones ArduPilot is an awesome piece of hardware; you love all the great sensors that are attached; you love the all-in-one design and the small/light size.  But you are also feeling the limits of it’s ATMega 2560 processor and the limits of it’s 256Kb of RAM.  And maybe, you enjoy developing code within a full blown Linux developers environment with all the supporting libraries and device drivers that Linux has to offer.

Hardware Layout

Here is a picture of a protype “hybrid” autopilot system for small UAV’s.  What you see in the picture includes:

  • An ArduPilot Mega 2.0 (lower left)  The APM2 includes an MPU-6000 IMU, a Mediatek 5hz GPS, static pressure sensor, compass, and a variety of other items.
  • A 1Ghz Gumstix Overo with a Pinto-TH expansion board. (longer thinner board, upper right).  The Overo runs Linux, has 512Mb of RAM, and has a hardware floating point processor.
  • An MPXV7002DP pressure sensor (upper left).  This is attached to a pitot tube and measures airspeed.
  • A Sparkfun TTL level translator (between the overo and the pressure sensor)
  • A Futaba FASST 6 channel receiver (lower right)
  • A set of power distribution rails (8×3 block of 0.1″ pins.)
  • [not shown/mounted remotely] Digi Xtend 900Mhz radio modem.

The above picture was deliberately taken without most of the wires to show the components.  Once all the wires are connected, things will look much more “busy”.  This is a prototype system so the components will be jumpered together, probably with a bit of hot glue here and there to ultimately secure the wiring before flight.

Software Layout

Just as important as the hardware layout is the software layout.  This is maybe a bit more boring and I can’t really take a picture of it to post here, but I will give a few bullet points for anyone who might be interested.

  • The APM2 runs a custom built firmware that simply collects all the sensor data, packages it up into checksummed binary packets, and sends the data out over a uart.  In addition, the APM2 reads checksummed binary packets inbound over the same uart.  Generally inbound packets are actuator commands.
  • The Overo runs a custom built autopilot application that is portable.  It is not device/hardware independent, but it is designed to talk to a variety of hardware over a common interfaces.  This Linux-based autopilot app can read all the sensor data from the APM2 (being transmitted at 100hz over a 500,000 baud link.)  The autopilot app runs a computationally intensive 15-state kalman filter.  Manages the mission tasks, computes wgs-84 great circle navigation targets, runs the low level PID code, and ultimately sends servo position commands back to the APM2 over the same 500,000 baud link.
  • The high level autopilot software runs in an environment that is more natural and has more power/space for developing the “high concept” portions of the code.  The APM2 is great for reading a bunch of sensors really quickly.  In a hybrid system both major components are able to do what they do best without having to suffer through tasks they aren’t as good at.
  • The high level autopilot is configurable through a structured XML configuration system.  It includes an advanced 15-state kalman filter.  It runs the same PID code configured in the same way as the FlightGear flight simulator.  It also includes the same “property system” that FlightGear pioneered.  It includes a rich set of IO API’s, and hopefully will soon sport a built in scripting engine.
  • A word about the “property system”:  The property system is an in-memory tree structure that relates “ascii” variable names to corresponding values.  There is loose type checking and on-the-fly type conversion similar to many scripting systems (I can write a value as a ‘string’ and read it back out as a ‘double’ and the system does sensible conversions for me.)  Any internal module can read/write the property tree, so it is a great way to build “loose” interfaces between modules.  Modules simply reference the values they need and there is no compile time enforcement.  This allows for building “robust” interfaces and eliminates much of the cascading changes throughout the code when a class gets updated.  In addition, we can build external network interfaces to the property system which allows external scripts or other code to monitor and even modify the property tree.  This allows external scripts access to the core values of the sim and access to set modes and otherwise “drive” what the autopilot does.  In addition, there is a natural one-to-one mapping between the property tree and an xml config file.  This is handy for easily loading/saving configurations.  At a low level, property system variable access from the core code is simply a pointer dereference, so using these values is almost as fast as referencing a locally scoped variable.  It is hard to describe in a few words what all the “property system” is or does, but it’s an amazing infrastructure tool that helps build flexible, robust, and high functioning code.

September 7, 2012 Update:

Here is a picture showing the whole system plugged together with 6″ sparkfun jumper wires.  The wiring gets a little “busy” when everything is connected together so I plan to do some work buttoning things up, simplifying, and cleaning up the wire runs.  I’ve attached 3 servos to test auto vs. manual outputs.  You can see a 900Mhz Xtend modem (1 watt power, 115,200 baud), and the entire system is powered by a single RC receiver battery.  In the aircraft this should all run just fine off the BEC.  And here is a video of everything in action:

That’s about it. The modified APM2 firmware is happy and running.  The overo autopilot code is up and running and talking to the APM2.  Next up is validating the radio modem ground station connection, and then I’m running out of things to do before dropping this into an airplane!

September 17, 2012 Update:

It’s far from a perfect integration, but I spent some time this evening bundling up wires.  Definitely an improvement.  Working towards full integration into a Senior Telemaster (electric powered) and hope to do some first test flights later this week.  Today I test fit everything, powered everything from the main flight battery and verified basic control surface movements in manual mode and autopilot mode.  The radio modem link is running and the mapping and instrument panel views on the ground link up and run.

Hacking the APM2 Part #3: Servos

Here are a few random notes on the APM2 and servos.

As we all know, the servos are controlled by sending a digital pulse on the signal line to the servo.  The length (time) of the pulse maps to the position of the servo.  A 1500us pulse is roughly the center point.  900us is roughly one extreme and 2100us is roughly the other extreme.  Different systems will use slightly different numbers and ranges, but these are good numbers to start with.  Historically, RC systems stacked the pulses for multiple channels on a single radio signal — affectionately called the “pulse train.”  If you crunch the numbers — given a max pulse width of about 2000us and a bit of inter-pulse spacing, we can send about 8-10 channels of data at 50hz on a single signal line.  Standard analog servos are designed to expect 50 pulses per second and can misbehave if we send a faster signal.

With modern 2.4Ghz systems, the servo/channel data is sent digitally and at much faster data rates.  Receivers drive each servo pulse concurrently and the concept of a “pulse train” is largely gone — as is the need to space things out at a 50hz rate.  If you crunch the numbers again and look at a max pulse width of 2000us with a bit of inter-pulse space, we can actually send servo data at 400hz to a digital servo and it will respond as expected.  (8 channels at 50hz, 1 channel at 400hz — makes sense.) 🙂

What does all this mean to an UAS builder?

  • It means that if we use digital servos, we can send position updates to the servo and expect some response at up to a 400hz rate. In real life these servos have mass, motors that take time to move, on board electronics that take time to process the signal, and other factors, so we can’t expect instantaneous response, but we can expect an improvement over the old 50hz analog servos.
  • It means we have a strong motivation to sample our sensors faster than 50hz, run our attitude filter faster than 50hz, run our guidance, control, and navigation code faster than 50hz, and command our actuators faster than 50hz.
  • It means that if we can increase our throughput to 100hz or 200hz, we can have a far more responsive and “tight” system than we could if everything was running at 50hz.  Faster response to gusts and disturbances, ability to counter more of the aircraft’s natural dynamics.  With proper autopilot tuning, this can lead to a much higher quality system, much more accurate flying, and a much more stable platform to hang our sensors off of.

The APM2 has the ability to set the PWM frequency for the output channels.  Channels are grouped and several hang from a single clock generator so we can’t change the PWM rate individually, but we can do it for groups of channels.  Question: if our system is running at a full 100hz update rate, does it make sense to set the servo output rate to 100hz or something higher?  I argue that we should set the output rate as high as is possible (400hz) because the servo will pick up a change fractionally quicker at a 400hz output rate than at a 100hz output rate.  In the end though, most servos are somewhat noisy and crude and subject to physics, so it may not have a huge noticeable effect, but any little thing that makes the system more responsive and increases the end to end throughput from sensing to responding is welcome.