## Magnometer calibration

All of our smartphones have an integrated compass. It can be very useful when you are looking for in which direction you should start heading while walking. However, you have probably noticed that sometimes, the direction showed by our phones can be quite...wrong! It happens when the compass has not been calibrated correctly. But if you try to turn the compass around in every direction, you'll probably notice that the direction arrow finally takes the right direction. Why? Because the smartphone is doing a "live" calibration as you move the compass.

What you should keep from this introduction is that compass calibration is fundamental ! Don't intend on using a magnetic sensor in your project unless you have it calibrated. Otherwise, the data you'll be using will probably be inaccurate, if not completely random 😀

##### Back to basics
###### What does a magnetometer do?

"NOPE! (Chuck Testa)"

The magnetometer gives you a three dimensional vector of the magnetic field it senses. This magnetic field is a combination of both the earth's field and of the magnetic field created by all the surrounding objects. And this second magnetic field is far from being negligible,  especially in our hobbyist projects where there's electronics (and motors) all around.

Theoretically, the measured magnetic field should :

•  be centered around 0
• always have the same strength

If we could represent it in 3D, it should basically look like a perfect sphere centered in 0.

In reality :

• it is not centered around 0, because of the presence of other magnetic fields around the sensors(such as other magnets, electric wires) : it is hard iron distortion.
• it does not have a constant strength, because of the presence of other ferromagnetic materials around the sensors, which skew the magnetic field. This is soft iron distortion.

What we get is essentially a potato-shaped magnetic field (because of soft iron distortion), that is not even centered (because of hard iron distortion).

##### Calibration techniques
###### Hard Iron distortion

Hard iron errors introduce an offset in the magnetometer data

To get this offset is pretty simple : we keep track of the maximum and minimum values the magnetometer outputs on each axis while moving it in space. From what we know the maximum and minimum should be centered around 0, so we get the offset by :

We can then subtract the measured offset from each raw measurement in order to get  hard iron free data.

###### Soft Iron distortion

Here, the work consist in transforming a potato in an orange. Or, transforming an ellipsoid into a sphere, if you prefer. It's actually easier than it sounds. There are  obviously mathematical formulas that involve matrices but let's keep it simple here.

Let's say earth magnetic field's value is F. It is the norm of the vector given by the magnetometer. While we've seen it should be the same on the three axes, experience shows it's not. So let's assume we have measured the maximum magnetic field Fx for the x axis,Fy for the y axis, Fz for the z axis.

We then calculate the average field value F by :

Let's assume that F = 1. If F_x = 0.8, it means that F_x is only 80% of the average field value. Hence the potato. Now if we simply multiply all the incoming x values by F/F_x, the potato effect, will be gone, as we expand the range of the x values so that it is no longer 80% of what it should be, but 100%.

###### Final equation

If we no combine the two equations and use vectors, we get:

Scale transforms the potato into an orange(soft iron distortion) and the Offsets vector brings it back in the center(hard iron).

###### Calibration process

The calibration consist in getting the min/max values of x/y/z fields, and then calculations the offsets and scale factors. The more you move the magnetometer in all directions, the more efficient your calibration will be.

###### Using calibration data

// We get the raw values here  in mx,my,mz

//(this is pseudo code)

// Now we apply the calibration data

mx = (int)((scale_x)*(mx-x_offset));
my = (int)((scale_y)*(my-y_offset));
mz = (int)((scale_y)*(mz-z_offset));


##### Results

Using Processing and  a slightly modified version of this program, I was able to quickly draw the 3D representation of the magnetic field. The video shows the before/after.

As you can see, hard irons distortion was HUGE before calibration. I could never have gotten reliable readings without correcting them. Soft iron errors were also present, and completely removed by the calibration. 🙂

## T-Rex 700L Dominator

Hey there !
It's been a while since the last article... So let's talk about something big this time. something really big. REALLY. The T-REX 700L Dominator, a class 700 (rotor size of about 1.6m, 5kg) helicopter made by Align. If you remember, I started to fly helis with an other Align helicopter, the T-REX 450 Sport V2. We remember beeing very afraid of it when the rotor started to spool up for the first time. Let me be clear, this T700 has NOTHING to do with it.

So, from a technical point of view, this 700 heli is the most advanced version of the T700E, first 700 electric heli made by align of this side. It features the last upgrades of the frame, BL815H and BL855H brushless servos, the 800MX Align motor, a Castle Creation 120A ESC and the DFC rotor head. The stabilization control is done by the new GPro controller (formerly known as 4GX)

The Cyclic BL815H brushless servomotors

The huge 800MX Align motor.. A real monster !

The built is really straighforward and you just have to follow the manual :). Beware to threadlock all the metal-to-metal screws and VERIFY it's well locked ! I crashed because a servo screw became loose... 🙁

The frame beeing assembled

As I said, it comes with the latest "inovations" from Align, so you have two helicoidal gears wich make a really nice sound once in the air 🙂

Close-up view of the motor and servos

Tail and servo tail

View of the implentation of components

As I didn't have (still don't) a High Voltage receiver, I had to think a little about electronics in this bird. This is the wiring I used to power the servos with HV source (2S lipo = 8.4V fully charged), and feed the receiver with a safe 5V.
Electronic wiring

The BEC component is actually in the T700L Dominator kit, good point for Align (again) :-D.

Tail assembly details
One word about the CC 120A ESC. When using lower head speed (<1800RPM), the CC tends to get very hot (above 100°C). This can lead to the destruction of the device. I wanted to put a 1500RPM head speed at first but changed my mind after seeing that. 1850RPM works fine for me. As you can see in the next picture, I put the controller on the rear of the frame, which is excellent in terms of heat because we have a giant propeller above it that helps to cool it down 🙂

Setting the GPro up is really a piece of cake, we can see Align really cared about the ease of use for this device. It comes with a free software for PC, Android and Iphone users! Note that for the phones, you have to buy a BlueTooth device separately.

GPro unit

As I could expect, it flies REALLY well, and the FBL head is quite amazing at all head speeds I tried (from 1500 to 2100).

## The drone parachute

Multicopters can become deadly weapons if the motors stop spinning as they should. There are so many reasons for a failure to happen (bad motors, bad battery, radio problems,etc...)  that it is absolutely necessary for the pilot to anticipate it, especially if you intend to flight over people's head!  We made the choice to never fly directly above people, but if you're willing take that risk,  you might be interested into getting a parachute on your drone . That's why we designed last year a DIY parachute for our quadcopter  🙂

The principle is very simple : the parachute is carefully folded  in a tube on top of which lies a lid that a servomotor keeps closed. At the bottom of the tube, a big spring pushes strongly the parachute towards its top end. So if the servo lets the lid go, the spring will push the parachute in the air.

I recommend you use a strong spring, so the parachute is entirely pushed out when the servo releases the lid. The spring we used is 10cm long, has 8 turns and is 3.5cm wide. It can be fully compressed under pressure, which is what we wanted here, in order to get the smaller parachute we could.

One of the major problems with parachutes is that the air needs to get "under" the parachute envelope in order to make it act as it should. If it doesn't , the parachute will become useless. We followed the method described in the following video :

### Parachute surface calculation

Obviously, your parachute's surface needs to match the weight of your copter, and the desired landing speed you would like to reach. I think a commonly accepted falling speeds sits around 5m/s (18km/h).

We found in the past a pretty useful formula that gives the diameter of tissue to use depending on the weight you want to slow down and its expected falling speed:

, with m in grams and V in km/h.

For our 1kg drone, it gives us a diameter of 122cm. As you can see, the parachute can quickly become huge compared to the size of your multicopter, and you should maybe start thinking about where to place it on your drone from the very beginning of its conception.

For our quadcopter, we used a slightly smaller parachute (taken from a distress rocket) than the 120cm recommended size given by the formula, which led to higher falling speeds than the expected 5m/s, but it stayed slow enough to keep the drone intact after many, many test flights ! 🙂

Here's the final video 🙂

Comment if you have any question ! 🙂

## PiWeather part 4 : first PCBs

I don't have so much time to give to this project, but PiWeather is still moving forward!

The first prototype only had a DS18B20 temperature sensor, and was working on a breadboard, so the next logical step was to design and realize a first PCB for the project. I also moved from the DS18B20 to the DHT22 sensor because it gives both temperature and humidity, and is pretty accurate. I added to that a pressure sensor : the BMP085, sometimes referred to as GY 65 on eBay! This would give my sensor unit the ability to read pressure, temperature and humidity.  That's a good start !

I used EAGLE to design the schematics and the PCB :

We made the PCB ourselves like we did for our old quadcopter flight controller shield. It is pretty hard to get good results with homemade PCBs, and the tracks have to be very big if you want to be sure there won't be any problems. We got a working PCB on which we soldered the components, and it succesfully worked, powered by two AA cells!

I am pretty happy with this PCB as it works great, but it obviously has drawbacks:

• PCB making is the worst. It never works as you want, there always is a problem, some tracks are too thin, some are too thick, you have to carefully check for possible shorts...
• There is no protection against oxydation. Of course you can by some sprays for that, but I don't know if that would work great for an outdoor sensor.
• The minimum track width is too big to make something small and reliable
• It's very, very ugly 😀

So I started to look for inexpensive solutions for my PCB to get produced in a "professional" way. And I found exactly what I wanted on Seeedstudio.com .They offer a very cheap PCB service starting at 9.99\$ for 5 PCBs of max 5cm x 5cm. Perfect!

Seeedstudio provides you design rule files for EAGLE, so you can see directly if your design will respect their process. I designed a new 2 layer PCB that Seedstudio produced and sent to me in a few days.

I was blown away by the quality of the boards 😀

The v0.2 finally took life and is ready for duty !

In the next weeks we'll try to build the first outdoor sensor, which will be solar powered. Then we'll probably deploy the website hosting the data gathered by the numerous PiWeather stations 😀

Cheers 🙂

Update 25/10/14 : The schematics are on github : https://github.com/psykhi/PiWeatherEAGLE

I also created a Raspberry Pi shield in order to plug the nRF24L01+ 🙂

I will write an article about it!

## PiWeather, part 3: low power design of the first prototype

In this third article about the PiWeather project, I will present a few techniques I used to design the first PiWeather prototype.

When I tried to write down for the first time the "specifications" of my sensor units, I thought that getting to more than one year of battery life would be satisfying. But I really didn't have any idea if I could reach this goal with an Arduino. It turns out you can. And, depending on your project obviously, you can reach very, very long battery lives with a regular Atmega328p used on a regular Arduino UNO.Let's go through a case study here, with a 220 mAh CRC2032 battery. It delivers 3V but let's pretend here it can deliver 5V for the sake of simplicity.

## Get rid of the Arduino board.

This decision is a no brainer. There is no way to make something low powered when using the Arduino board. It's actually quite logical when you think about it. It packs many more things than the 328p itself, like an FTDI chip, 3.3 and 5V regulators.

A program running on a regular Arduino UNO board will draw about 55mA, which is a LOT .The CR2032 battery will live 4 hours.

Now remove the 328p from the UNO board, put it on a breadboard with a 16 MHz quart and a, 5V power supply. You get down to 11mA. Now the battery will last 5 times longer, so 20 hours.  Only 20?!

## Does your application need to run at 16MHz@5V ?

If you' re working on a low power project, what you want is to only monitor some values, and take simple actions from the data you read. My sensor units only need to read what the sensors tell them, and send these data back to the Pi. There is absolutely no need for performance, therefore no need to run at 16MHz.

A side effect of lowering operating frequency, is that you can also lower the AtMega328 voltage. Indeed, it requires 4.2V to safely operate at 16MHz. At 8MHz, you only need to give it more 2.4V. Which means you could use a single cell battery such as a CR2032, or two AA/AAA batteries.

The difference between running at 16MHz@5V and 8MHz@3V is huge : power consumption drops from 11mA to roughly 3-4mA! Another very big save. Another advantage of running the ATMega at 8MHz is that you can use its internal oscillator, thus eliminating the need for a crystal(or resonator). That's why I chose the 8MHz frequency for this project.

## Save power with good software

The software part is as important as the hardware part, when trying to reach lowest consumptions. Indeed, the ATMega328 has different sleep modes that can theoretically reduce its power draw to barely 100nA!

When used in the "default" mode, the Arduino will just endlessly run through the loop function, event if there is nothing to do. This will draw around 4mA running 8MHz@3V. This barely gives us a battery life of 56 hours with a CR2032 cell.

### Use interrupts

The ATMega328 can be put into different sleep modes. The "highest" sleep mode basically turns off the Arduino. The only to wake it up is then to trigger an interrupt (that you will have previously registered in your setup() function !). A possible source of interrupt is the change of state on one of the Arduino's pins. Another  way of triggering an interrupt is to use a timer. Timers can generate an interrupt periodically to trigger an action. The maximum sleeping time you can achieve with the Arduino is unfortunately pretty low : 8 seconds. This means that if you want, like me, to sleep for minutes between every action, you'll have to keep track of a counter to reach the desired sleeping time. I found the Low-Power library to be pretty useful. It keeps away the ugly register assigning code and makes sleeping a breeze 🙂

## The results

My code is pretty simple. Sleep 800 seconds (around 13 minutes), wake up,acquire and send the sensors data (a few seconds), and go back to sleep for 800 seconds. The average power draw while sleeping is 6 µA, due to the watchdog timer of the Arduino. The few milliamps drawn at wake up can be ignored since they represent less than 0.5% off the total time, which gives us approximately 225/0.006=1562.5 days of battery life. This is much better. If you don't need the timers and can get external interrupts to wake up your device, you can achieve a lifetime that will essentially be your battery life time!

## First prototype

The first sensor unit prototype is very simple. A DS18B20 temperature sensor, an ATMega328p and a nF24L01+ for RF communication. The power is given by a CR2032 battery.

One of the flaws of this design is the minimum voltage required by the DS18B20. It theoretically is 3V. The CR2032 voltage is 3V when new, but slowly goes down until around 2.8V (then it's pretty much flat). It turns out the DS18B20 behave completely normally, even at 2.8V, but powering a sensor outside its recommended operating voltage range is probably never a good thing.The second prototype, which I'll present in a future article, fixed this 🙂

That's it for this short introduction to low power design for Arduino. If you want to know everything about Arduino and low-power, read Nick Gammon's great posts here 🙂

## PiWeather : How to communicate wirelessly between an Arduino and a Raspberry Pi

If you wonder what PiWeather is, check out the first article I wrote !

One of the key part of this project is to first determinate what technology to use to transmit the data and second how to encode the data to send. What I wanted was:

• Reliability
• Low power design
• Good range (enough to cover a small house)
• Ease of use
• Something cheap
• Something that could work simply on the Arduino and Raspberry Pi side

# RF chip

My first choice was spontaneously to pick 433MHz RX and TX as they are incredibly cheap and can reach a pretty long range if you associate them with the right antennas. The problem with these is that the very low-level side of the transmission. If you put the TX pin high, the RX pin will go high too, and that's it. You really have to do all the encoding by yourself, and if you want it to be really reliable, you must provide a way to ensure all your data were transmitted correctly (like a CRC).  I first thought I would have to cope with this and handle all this low-level part by myself on both the Pi and Arduino's sides, when I stumbled upon the one RF chip I needed: the 2.4GHz nRFL24L01+.

The nRF24L01+ was exactly what I needed: cheap, low power, easily connected to a Pi or an Arduino through SPI, built-in CRC, both RX and TX at the same time, multi pipe, and more!

It also is really easy to use through SPI: just give it the bytes you want to send (up to 32), and send it to the address of your choice. The same thing goes for the RX mode, it can even generate an IRQ when a message has come!

I used the library from Stanly Seow on both Arduino and Raspberry's side, and it works pretty good! One flaw of the Pi's implementation is that it doesn't use interrupts generated by the nRFL2401+, so it kind of stalls the Pi polling the chip. I modified it a bit to use interrupts from the great WiringPi library, allowing my program to sleep 99.9% of the time. I will get into these details in an other post, stay tuned 😉

Okay, so I know how data will go from my sensor units to the Pi. But what am I going to send?

# Messages

So far, I've thought about sending the following data to the Pi from the sensor units:

• Temperature
• Pressure
• Humidity
• Wind speed
• Wind direction
• Rain metrics
• Unit battery level, to detect low voltage

Also, my units needed some kind of address or unique ID so the Pi could easily recognize them, so I added an ID in the list of things I could possibly send. I could have decided of my own encoding format, but what if I change in the future the things I send and in which order, etc? You can see now that encoding the data in a forward compatible way is really not that simple!

I actually never thought about encoding myself the data 😀 It was just to show you that it is definitely not a piece of cake. I knew exactly what I needed to use : Google Protocol Buffers

From the Google website , "Protocol buffers are Google's language-neutral, platform-neutral, extensible mechanism for serializing structured data – think XML, but smaller, faster, and simpler". You can find libraries to use them in almost any available language, from a micro controller with 2kB of RAM running C code, to a server running PHP or Python.

### So how does it work?

You first describe the messages you want to send in a file having the .proto extension:

message SensorData{
required int32 id=1;
optional bool binding= 2;
optional float temperature = 3;
optional int32 battery_level = 4;
optional float pressure = 5;
optional float humidity = 6;
optional int32 type = 7;
}


message is the keyword required to start defining a message. Then it looks a bit like a mix of a C structure and enum declaration. You define your fields and attribute them a unique ID (ex : the field temperature has the ID 3), and then add if your field is optional or required in the message. In this case, each of my sensor units will have to send its ID to the Pi during a transaction so the Pi know who it is talking to, but some sensors will retrieve temperatures, some wind speed, some pressure, so I made all the other fields optionals.
If I want in the future, to add a new data to my message SensorData, such as windspeed, I can just modify my the proto file like so:

message SensorData{
required int32 id=1;
optional bool binding= 2;
optional float temperature = 3;
optional int32 battery_level = 4;
optional float pressure = 5;
optional float humidity = 6;
optional int32 type = 7;
optional float wind_speed = 8;
}


And you know what the great part about this is? It will be backward compatible with the existing sensor units using the "old" messages! So no need to re-flash the existing sensor units if I had optional fields in my messages, which is a very, very nice thing 🙂 I won't get more into details for GPB here, their website has tons of examples of how to use them!

To actually use these messages, you need to translate them into the language you are using. I chose to use NanoPb, which is a very good implementation of protocol buffers for embedded systems. It has a tiny footprint (less than 2kB!) and generates all the code you need to include in your project, so no need to link against a lib, which is always good news 😉

NanoPb takes the proto file and creates the associated C structures, encoding/decoding functions for my messages. The generated structure looks like this:


typedef struct _SensorData {
int32_t id;
bool has_binding;
bool binding;
bool has_temperature;
float temperature;
bool has_battery_level;
int32_t battery_level;
bool has_pressure;
float pressure;
bool has_humidity;
float humidity;
bool has_type;
int32_t type;
} SensorData;



Let's say my sensor unit has both a temperature sensor, and a humidity sensor. If I want to send the data to the Pi, I can do like so:

 SensorData message;
uint8_t sensorDataBuffer[32];/*Maximum size you can send with the nRF24L01*/
pb_ostream_t stream;

message->has_temperature=true;
message->temperature=sensor.temp();
message->has_humidity=true;
message->humidity=sensor.humidity();
message->id=42; /*The unit ID*/

/*Let's encode this with nanopb*/

stream = pb_ostream_from_buffer(sensorDataBuffer, sizeof(sensorDataBuffer));
pb_encode(&stream, SensorData_fields, message);

/*Now our encoded data is in the sensorDataBuffer, ready to be sent ! */
nRF24.send(sensorDataBuffer);


It's as simple as that, and very powerful. I think protocol buffers are really the right way to go for size constrained embedded applications such as this one. But don't think they are only used for small applications, they can be so powerful that they are wildly used in different industries to send big loads of data, through nested messages for example 😉

So that's it, I introduced you the chip I use to make the communications, and the format I adopted for the messages my sensors send wirelessly. I think I will go back on this in a coming article where I will define exactly how the software I developed works.

Cheers 🙂

# The weather station project (codename : PiWeather)

It's been quite a while we haven't posted anything here, but it doesn't mean we're not working on cool things !

A few months ago, I thought it would be cool and useful if I could monitor temperatures inside and outside of my apartment. This way I could know when to open the windows or close them in summer when it gets warmer outside than inside, and the other way around. Then I figured that I might as well add other data, such as pressure, humidity, maybe wind speed and others if I gather the time and the energy to go through with my project, which I admit, rarely happens 😀

Anyway, things are now moving with the project so now is the time to write here. The idea for this first article is to introduce briefly what I will do and how I am planning to do it. I will update this article in the future with links to the latest articles I post about the PiWeather project.

## Architecture

As you probably guessed from the project's codename, the central unit is a Raspberry Pi. The Pi itself does not host any sensor. It will instead be connected wirelessly to them, or more precisely, to what I will call from now on “sensor units”. These sensor units will be Arduino based (what a surprise!) sensor platforms. I mean by this that a sensor unit can host more than one sensor on board, like both a pressure sensor and a temperature sensor for example.

## Goals

My goals are :

• No wires : While the Pi will be connected both to a power source and through Ethernet, the sensor units must be wireless.
• Plug and play sensors. Just put a battery inside a sensor unit, and you're done. No complicated setup on the computer, through switches, nor command lines.
•  Longest possible battery life for the sensor units. If you have to change batteries every other week, then being wireless has in fact no point.
•  Web interface to monitor and access all the logged data
•  Use cheap parts

There are probably tons and tons of similar projects on the Internet, and I don't really care. The point is as always to have fun, learn, design, and do something useful...Okay, it's not always useful 🙂

## Technical topics

On a technical side, the topics I will try to approach during this long journey are:

• The sensors I used or plan to use
• Low power Arduino design
• Arduino development in Eclipse
• Raspberry Pi program cross compilation
• Communicate wirelessly between an Arduino and a raspberry Pi
• Symfony 2 PHP framework
• Create a daemon for Linux
• Interrupts on Raspberry Pi
• PCB design
• Case design (if I make to this stage obviously :D)