Calibrate a magnetic sensor

I recently worked on a project that required a magnetic sensor (MPU-9250) be calibrated to get best accuracy. I had some basic understanding on how to calibrate a magnetic sensor, although I’ve not done calibration before. The calibration turned out to be a bit complicated and took a while to understand. I got some help, including method to get best calibration, from the author of the MPU9250 Arduino library, Kris Winer. I thought that if I shared my experience here, others that are planning to calibrate their magnetic sensors may find it useful.

First of all, what is calibration? In a general sense, calibrating a sensor makes the sensor provide the most accurate readings allowed by the sensor’s own precision. As an example, let’s assume for a moment that the earth’s magnetic field and any other stray magnetic fields are shielded and you have a uniform magnetic field generated artificially for the sole purpose of calibration. Let’s say that the field strength is 400 mG (milliGauss), equivalent to 40,000 nT (nanoTesla). Now if you align one axis of your magnetic sensor parallel to the direction of the field, it should read 400mG. If you then carefully rotate your sensor so that the axis is anti-parallel with your field, it will read -400mG. If you didn’t do a good job in either alignments, you will read less values, say 390mG, if you’re off by about 13 degrees, because only a portion of the field, which is a vector, is projected along your magnetic sensor’s axis.

In the diagram above, the thick blue arrows represent the constant magnetic field of 400mG pointing to the right. The thin arrows represent various orientations your sensor could take. If your sensor + axis is also pointing to the right, you get the full 400mG. If your sensor + axis points to the left, you get -400mG. If your sensor + axis makes an angle, it reads a projection of the field, which is less. You can figure out the angle:

The above was assuming that there IS a constant magnetic field and the sensor’s reading IS symmetric along its positive and negative axis, meaning with zero magnetic field, the sensor reads zero. When not calibrated, the sensor reading will NOT be zero under zero field. It could read say 10mG. As a result, you might get say 510mG and -490mG with the field on. You know what that means. There is an offset (bias) of 10mG that should be subtracted from your reading to get the correct reading of +-400mG.

The above was the basis for calibration to remove the offset (bias) on each axis. In order to get the maximal and minimal value, you need to write your code to store max/min out of a stream of live data while you rotate your sensor in space, trying to maximize or minimize the readout. Then repeat two more times for a 3-D magnetic sensor. Since you don’t have a magnetic shield, you are relying on the earth’s magnetic field as the constant field. The earth’s magnetic field is not horizontal, or pointing from north to south. In most areas, the field either has a vertical up component, or a down component. And in most cases the field points from south to north as the rotational north pole (AKA the north pole) is near the magnetic south pole, where field lines go in, not coming out. In my area for example, the earth magnetic field points primarily downwards, only slightly towards north, making an angle over 70 degrees with the horizontal. The magnetic field has very little component in the east direction. The relative strength between East, North, and Downward is about 1:64:195. The angle the magnetic field vector makes with the horizontal is called magnetic inclination, with downward being positive. This is approximately atan(195/64)=72 degrees. The angle the magnetic field vector’s horizontal component makes with the true north is called magnetic declination, with east being positive. This is approximately atan(1/64)=0.9 degrees. The properties of magnetic field varies greatly from place to place and also changes from time to time. To find out the magnetic field in your area, visit

The following is from my area:

The next calibration is for sensitivity. The sensor either returns an analog voltage or a digital value. How do we convert this return into actual magnetic field in mG? This means finding the relation between the sensor readout and actual physical values. Say the sensor is digital and returns values between 0 and 32767, which represents magnetic field between 0 and 49150mG. Then you can use the conversion vactor 49150/32767=1.5mG/LSB to convert your readout. Here LSB means one digit (least significant bit). For an analog sensor, you will need an x.xx mG/V.

All sensors provide this factor in their spec sheets so you can just use this factor to get the actual magnetic field. But since not all sensors were made identical, some sensors should use larger or smaller values than the spec’s factor. Some manufacturers test their sensors at factory and store a correction factor for each axis in the sensor for better accuracy. For example, the MPU-9250 sensor (the magnetic sensor is AK8963) has digital magnetic field sensor output. One of the sensors I got has the following factory trims:

X-Axis sensitivity 1.18

Y-Axis sensitivity 1.19

Z-Axis sensitivity 1.14

So instead of a straight 1.5mG/LSB, the x-axis has 1.5*1.18=1.77mG/LSB. We’ll multiply this factor to the x-axis readout to get x magnetic field in mG. Same for y and z axes.

And yet sometimes these adjustments are still not able to make all 3 axes read the “400mG” value. They are very close to be identical already so we can apply a small correction. We average the maximal readings from all three axes, then divide by the maximal reading of each individual axis to get three factors. If say the x-axis reads slightly higher maximum than y and z axes. Then the avg_max/x_max will be slightly less than 1. We apply this factor to the the final result:


For one of my sensors, this yields 1.5*1.180*0.975*x_readout=1.726*x_readout(mG)

If the sensor you’re using doesn’t have the factory trim, then you’re out of luck unless you have both a magnetic shield and a nice uniform magnetic field inside the shield so you can find out the trim.

The following are steps for the AK8963 magnetic sensor calibration I did, using Kris Winer’s MPU9250 Arduino library:

  1. Extract factory sensitivity factor by calling initAK8963().
  2. Call readMagData() to extract raw data repeatedly enough to get accurate max/min for all axes.
  3. Calculate bias in raw counts by (max+min)/2, such as (510+ (-490))/2=10
  4. Combine factory sensitivity factor and Kris’s scale factor described above.
  5. Keep these biases and factors in program.

As a testimony to the method that works, here are two graphs.

This graph has three separate plots from raw data that represent mx vs. my, mx vs. mz, and my vs. mz. I rotated my sensor as much as I could for a few minutes before I got bored and couldn’t think of any other ways of rotation. The fact that all three plots are near circular means that the sensor’s three axes have very similar sensitivities. I was simply rotating the sensor around, giving all three axes opportunities to read the whole magnetic field. This means when the x axis reads the whole field, y and z axes read nothing. Some trigonometry can show that the result is a series or circles making a disc. But the discs were not centered as I expected, because the z axis had a very large bias (this means the blue is mx vs. my). After my bias calibration, here is what I got:

Now all three plots are centered at zero pretty well visually, although I didn’t multiple the factory sensitivity or the final factor from Kris’s calculation. This shows that bias calibration is the most crucial. If your sensor doesn’t have stored factory sensitivity factors, getting it calibrated for bias alone will go a long way.

FYI, this is my sensor board inside an enclosure. I found it much easier to hold and rotate when it’s in a box. The cable became much less of an issue when I was rotating the box. The black square board is my SDI-12 USB adapter. The purple board is the sensor board. I customized the SDI-12 USB adapter by gluing the sensor board to it and connecting it to the I2C bus on the adapter.

Open source data logger

I have been designing data logger for a number of years. This is my answer to lots of data logging needs. An Arduino Nano-based open source data logger:


The logger provides the following features (in green) including features of Arduino Nano (in black):

Microcontroller Atmel ATMEGA328P
Power 5 V via USB or 2X AA battery (internally)
Digital I/O 10 (4 PWM output, other Arduino pins used internally)
Analog Input 4 10-bit ADC (8 on ATMEGA328P, only 4 brought out)
DC Current per I/O Pin 40 mA max
Flash Memory 32 KB of which 2 KB used by bootloader
EEPROM 1 KB on ATMEGA328P, 32 KB on real-time clock breakout board
Clock Speed 16 MHz
MicroSD card 32 GB maximum
Real-time clock Temperature compensated (DS3231)
ADS1115 4-chn 16-bit differential ADC with up to 16X programmable gain
LCD 16 column by 2 row character LCD with back light on/off control
Input Rotary encoder with switch (when shaft is pressed)

Table. Specification of Arduino Nano and the rest of the modules.

Another photo:


As you can see, the logger incorporates a number of breakout boards instead of including these ICs on a single circuit board. More to come…

LEDs vs. CFLs

There are lots of discussions of how LEDs are the ultimate power savers that beats all other methods of lighting. On the other hand, it only beats some lighting methods but not all. Compact fluorescent light (CFL), for instance, has similar efficiency in converting electricity into light to LEDs.

It’s funny that most people thought that vacuum tube technology was useless and CFL is just one of them that is still kicking! After reading some wiki I was reaffirmed that LEDs and CFLs actually have similar principles of operation, that is when you compare them with incandescent light. The two still have some slight differences if you care to know:

*While LEDs have conduction electrons moving inside semiconductor, CFLs have free electrons moving in glass vacuum tube.
*While conduction electrons excite semiconductor bonds in LEDs, free electrons excite gas molecules in CFL.
*While excited semiconductor bonds decay and directly emit light in LEDs, excited gas molecules emit UV light in CFL, which strikes fluorescent powder, which turns UV into visible light.
*There is electrical resistance in semiconductors against electron motion but no electrical resistance in vacuum tubes, but the fluorescent powder does waste energy converting UV into visible light.

I guess that’s why these trade-offs made them similar in efficiency. So what is your take on LED vs. CFL?

Arduino workshop to be held at AAPT meeting

This is the first time an Arduino workshop it to be held at a physics national conference:

American Association of Physics Teachers summer conference in Omaha, NE, July 30, 2011

Search (ctrl+F) for session W20. I don’t know who is organizing this workshop yet but I’ll be there to gauge interest in using arduino for physics teaching.

I will also give a talk on arduino and building teaching apparatus at the meeting. Lots of slides to make and finishing touch to my uniform circular motion apparatus for a competition.

How to calculate current-limiting resistor for LEDs

Here is typically how you calculate the “current-limiting resistor” for an LED.

You will need to know ahead of time:

1) Supply voltage Vdd, in case of the typical 5V arduino boards, Vdd=5V

2) Typical forward bias voltage of the LED Vfb, read the spec sheet. My personal experience is that more powerful LEDs have higher value of Vfb.
Take this one for example:

A range of 3.0 to 3.6V is given. I would try to use the average of 3.3V. Some other spec sheets give typical values and you will use that value.

3) Current rating i_m. The above LED is said to have 20mA current rating. It’s the maximal sustained current you want it to have. Again some other spec sheets give you current at typical forward bias voltage and you can use that value.

Now to calculate the current-limiting resistor, just do this:

Vdd=Vfb+Vr, where Vr is the voltage dropped on the current-limiting resistor. So Vr=i_m*R. Where i_m is the LED current rating.

So R=(Vdd-Vfb)/i_m

For the above LED, R=(5V-3.3V)/0.02A=85 ohm. That is when you are pushing a little bit. Plus, arduino pins can only supply 20mA and the entire ATMEGA chip can supply 200mA. So to be safe, I would use a 150 ohm resistor. Then the LED will be less bright. If you use the LED for lighting purpose, its brightness is relevant to you. But you use it as an indicator instead of illumination, make it not that bright by using larger resistors.

Typically, if an LED is passing 1mA of current, you can see it in the dark, or straight on in a room but hard to see from sideways. If you run 20mA on an LED, it hurts your eyes to stare at it.

The following is taken in a dark bedroom. I believe only 3 LEDs were on together, passing around 6mA each only 🙂

Cross talk

Cross talk is a common feature that probably originated from phone lines carrying noise from an active conversation across its wires. If you have a piece of electrical wire close to another one, then the change of the current on one wire will induce change of current of the other, simply by the law of induction in physics. If you have strange noise in your project such as ultrasonic ranger, motors, etc., you may want to see if your power lines are cross talking with your control or sensor signal lines.

The ultrasonic transducer for example is a big power sucker. It’s turned on only momentarily and then turned off quickly, and then repeat for 7 to 8 times to generate the necessary sonic pulse for distance detection. The change in current within a unit amount of time, or di/dt, is big on the power lines and that could couple to their neighbors via induction with dB/dt (magnetic field changes with time), AKA cross talk. To eliminate this noise, you may add a capacitor between power and ground near the transducer to reduce the need to change current on the wire that passes the current. Charges on the capacitor simply flow to the device as needed to reduce the need to pull additional currents along the power line. This capacitor is called a decoupling capacitor. Or you can also shield your control or signal line and connect it to the ground. For a mobile device, a decoupling capacitor is most convenient.

When I was a grad student, I observed this strange but straightforward physics law of induction first hand. I was trying to control a power supply with a PID temperature controller. The power supply was connected to resistive heaters so was a thermistor. They went down the same cable, which was not properly shielded. The thermistor was used as feedback for tjhe PID temperature controller. I got the strange jump of power every now and then and the temperature was not stable. Then I realized the problem and used the shield inside the cable to shield the signal from the power lines. It worked nicely afterward. It turned out, the thermistor reading was strongly affected by the power supply suddenly turning on or off and that affected the temperature reading and knocked the PID off balance. My experience, either use a decoupling capacitor or use shield around your sensors. The shield needs to be grounded.

Arduino parking sensor

(This project is also posted on instructables

My wife has told me about a reverse/backing parking sensor her friend has on their car. It helps someone parallel park in a tight spot. We normally don’t need one but I can see sometimes having one will really help. So I set out to make her one tonight.

As a physicist, I have to lecture on the principle of the sonic ranger a bit. It is a rather simple device, the small cousin of the police speed gun! The sonic ranger sends a few pulses of supersonic waves and waits for the waves to bounce back from an object in front of it. Once it detects the reflected sound, it knows how much time it took the waves to travel a round trip from the ranger to the obstacle and back. With speed of sound at around 340m/s, you can calculate the distance to an object. You can also find velocity if you measure distance at two consecutive times and do distance change over time. Bats use their sonic ranger to fly in pitch black caves or catch food! Mr. English also tried the same technique with no apparent training and failed miserably. One episode of Stan Lee’s super heroes also featured a blind person using his tongue clicks to tell what’s around! That’s it for sonic ranger intro!

Diagram from Parallax

After some coding, wiring, swearing, I’ve got a working prototype. It has the following functions:

  1. Displays distance to an obstacle in feet/inch and mm.
  2. Display analog distance as bar graph
  3. Audio alert of distance as frequency of beeps, like a radioactive sensor (Geiger Muller counter) so that the beeps become more frequent as the car approaches the obstacle closer.
  4. Adjustable audio alert beep frequency so she can pick an appropriate parameter just for her.

I’ve listed the parts here:

  1. One arduino Duemilanove or UNO (many vendors sell this)
  2. One Phi-1 shield kit for arduino ( I designed this shield. Here is documentation. They also sell this on ebay.
  3. One RJ11 jack and breakout board. I made some breakout boards myself and used the RJ11 jack from the Phi-1 kit. But you can buy from sparkfun: Rj11 jack and RJ11 breakout board. You have to observe which pin is which with a multimeter.
  4. One four-wire phone cable. Just go to a dollar store and make sure you’re not getting two-wire cables.
  5. One Ping or other ultrasonic sensor from parallax. Alternatively you can also buy this one from sparkfun.  You will have to make sure you’re connecting the PWM pins to arduino. I don’t have this.
  6. One 1uF capacitor. You can get it anywhere you but the other parts.
  7. Either a car power adapter that outputs center-positive 9V to 12V or a 9V battery with a connector from here

First, assemble your Phi-1 kit. Make sure you solder on the buzzer on top right corner, and one RJ11 jack on the bottom right corner, like in this picture:

Next, test it with the test code found on the Phi-1 shield home page to make sure it works.

Assembling hardware is easy:

  1. Solder the RJ11 jack on its breakout board.
  2. Connect phone cord between the shield and the RJ11 jack with breakout board. Determine which pin on the breakout board goes where on the shield

  1. You will need a cable or solder three wires to the sonic ranger. I found this connector in my drawer but if you don’t have one, go to a surplus store. Old CD-roms also have these wires. Make sure you get the right pin to the sonic ranger. Test with mulitmeter. I used my own breakout board so all signals are marked. Since the cable is only 3-pin, I had to feed 5V on the X pin on my shield. I jumped the x pin to 5V. If you have a cdrom cable you have 4 pins and can switch out pin orders easily with a small jeweler’s screw driver. The output of the sonic ranger should go to arduino channel 2 Y, which is connected to analog 3.
  2. Stick a 1uF capacitor between 5V and GND to filter out noise. Trust me, this is not optional! Observe polarity of your cap.
  3. Run my program and use it!

I have made two versions of the program, a fully interactive one with menu and adjustable parameters. Another version is a nutshell, if you’re interested in learning how things work quick.

Full version

Nutshell version

Phi-menu version (see my phi-menu page)


First I tested it indoors with my wife. Everything works fine (first two videos).

Since it’s warm today (by our local standard) so I got out and installed the sensor with my wife. It worked! (next four videos).

12FT 4-wire phone cord, about 10 pieces of wide tape and some masking tape later, the sensor is on my rear bumper sticker. I had it on my trunk first but it is angled and too high. It couldn’t detect a car but a garage door was fine. So I moved it to the middle of the rear bumper cover.

Here are some pictures I took in a parking lot after backing towards some other dude’s car seriously close (more than I am comfortable without the sensor).


Since there is only one sensor, backing straight is most accurate but backing while turning is not. I need at least two sensors one on each side to cover both sides. Since I’ve got this thing working, I’ve become more observant and saw many newer cars have small attachments on their rear bumper covers, two or four. I suppose they’re either the sonic rangers or empty spots for installation. Will save money for a second sensor 🙂

If you are copying this project, make sure you get two rangers. Phi-1 shield can pass two signals on one 4-wire phone cord. Also make sure you get sensors built for wider angular response so you’re not just testing obstacles right behind but on the side as well. Mine is built for precise measurement so it only detects object more or less right in its line of sight.

Updated housing and mounting options:

I’ve made a small plastic sheet housing out of some 3X5 card holder with my blade half way and fold into a box, then attach some cardboard behind the sensor to prevent it from sliding, nice! Now attaching some 3M command pads with “velcro” I can attach my sensor on my car and easily remove it when it rains outside.

I will mount the sensor next weekend.

More updates today: I turned on the sensor in my electronics class to show my students how it works but to my surprise it’s not working! I then realized we have acoustic ceiling panels that absorb sounds! So I instead pointed it to the floor. Not working either. Nor did the white board. I just got random numbers around 500mm+-300mm. I tried and tried. Then I thought maybe my new housing is interfering  with the sound or my capacitor was not well connected. The I tried it in an electronics lab with the same results, the floor is not accurately sensed beyond 400mm.

Then I went back to my office and thought I had to rip the nice housing open. Before I decided to do it, I gave it a last try in my office. Well, it worked again! I guess very plainer materials like floor tiles and white boards reflect most sound just as they do light, mirror reflection so it’s very hard to make the sound reflect exactly back to the source to be detected. But I have carpet in my office, perfect scatterer, so it scatters in all directions. Although scattering reduces reflected intensity very largely, it makes the reflection a wide-angle source so the reflection (although weak) makes it back to the source to get amplified and detected. The number is stable again and physics work! Hahaha!

Here’s the videos:

Run 1 video:

Run 2 video:

Pulling away from garage door:

Driving towards garage door:

In parking lot very close to another car:


Measure temperature

There are many ways to measure temperature with an Arduino. We will discuss how to use a thermistor and a temperature IC.

Here is a picture of a 10K thermistor:

Here is a picture of a temperature IC, LM35:

The principle behind a thermistor (or the sensing component of a temperature IC) is the physics of semiconductors. A thermistor is a heavily-doped semiconductor. A semiconductor is conducting weakly compared with a conductor like copper but much more conductive compared with insulators like rubber.

The ability to conduct depends on a few factors. Among them, the amount of conducting charges in the material is quite important, which is directly proportional to the conductivity of the material. Insulators have very little conducting charges but conductors have a lot. The amount of charges in these two types of material don’t change much near room temperature. Semiconductors on the other hand, have moderate amount of conducting charges, whose quantity changes very largely as temperature changes. At high temperature, a semiconductor releases more conduction charges, it is less resistive. At low temperature, it releases less conduction charges and is thus more resistive. If you dope a semiconductor, the change of resistance becomes more pronounced for easy measurement.

So to sum it up, a thermistor is a resistor, whose resistance value decreases with increasing temperature, the therm- and -istor. This is like transistor is trans- and -istor. To measure temperature, we measure the resistance of a thermistor with a voltage divider. Let’s build a voltage divider and measure some temperatures.

First, purchase some 10KOhm thermistors for any electronics vendor. They should provide you the temperature vs. resistance data or formula to calculate temperature from resistance.

Then build a voltage divider and put a 10KOhm resistor in series with the thermistor. Connect 5V to the resistor and GND to the thermistor.

Now the voltage at the junction between the resistor and thermistor will change when ther thermistor changes resistance at a change of temperature. The more resistive, the higher the voltage.

Connect an analog channel to the junction. You can then sense the voltage and output to PC or display on an LCD screen.

Test the above parts with a multimeter before attempting to program Arduino to display temperature.

To display temperature, you may copy down the resistance of your 10KOhm thermistor at all different temperatures into an array.

Then read the voltage, convert voltage into resistance from simple circuit calculations.


If you care about error bar, read my Resistor sorter theoretical error.

Every time you read in a voltage, convert it into resistance, then look up the table for two values that are closest to your reading, use interpolation to find a more exact temperature value. You can also use the formula provided to you by the manufacturer to estimate the temperature like this one:

Formula 1 (complete expression).

or a simplified version:

Formula 2 (Simplified formula that gives resistance at temperature T(k))

You need to invert the function obviously to get temperature:

Formula 3 (Simplified formula that gives temperature T(k) at certain resistance R(ohm))

The values of T1, R1, and B should be given to you in the spec sheet, such as T1=298K (ie. 25DegC), R1=10K (the resistance of the thermistor at T1 temperature, so a “10K” thermistor will have R1=10K at 25DegC), B=4050K. The calculated result is in Kelvin. After subtracting 273 you will get DegC.

If this is too much math for you, I have good news, the temperature IC makes it easier to read temperature:

You may also use a temperature IC. Most common temperature ICs are either calibrated for degree C or F, like the LM35 is calibrated to degree C. They output a voltage proportional to these temperatures, both positive and negative, say 10mV/C or 10mV/F. Connect the output of the IC to Arduino analog input and you are good to go. Arduino can’t measure negative voltages so you either have to limit your measurement above 0DegC or 0DegF, or you can find one that reports Kelvin, which never reaches zero. Another way to measure negative voltage is to shift it to positive voltage with a bipolar to unipolar converter circuit. You will need a few things to construct a converter, which I can cover in a different post.


If you are measuring temperature near where your arduino is, the LM35 gives the easiest way to achieve that. On the other hand, if you measure temperature at a distance and have to run a long wire between arduino and the temperature sensor, you should use a thermistor to reduce noise. You can always pick the best serial resistor for your thermistor so the output voltage is neither too high nor too low.

More on discrete thermistors:

You need to choose the right fixed resistor for optimal accuracy. First determine your range of temperature you measure first, then find the middle of that range, and pick a fixed resistor that has the same resistance as the thermistor if it were at the middle of the temperature range. IE. if your temperature measurement is around 25DegC and you are using a 10Kohm thermistor, you need a 10Kohm fixed resistor in series to the thermistor. If you use a say 200Kohm thermistor with R1=200Kohm and B=4022K (use formula 2 and 3), and your temperature range is -30DegC to 50DegC, so center is 10DegC, then you need a fixed resistor that matches the thermistor resistance at 10DegC, which is 409Kohm according to formula 2. So you either use 390Kohm or 430Kohm as both are standard values easy to obtain.

There exist applications of heating up thermistors with large current. If you want to tell liquid level, you can use the liquid as heat sink and apply larger current on the thermistors so only those ones in the liquid will stay cool and have large resistance. The ones outside liquid are hot and less resistive.

Some simple code for 10Kohm thermistor sensing:

void setup()




void loop()


float resistance, voltage, r_fixed, T0, T, R0,B;
T0 = 298.15;//initial temperature for calibration
R0 = 10000;//initial resistance for calibration
r_fixed = 10972;//known resistance
B = 4050;//B for normalization

voltage = analogRead(sensor_a)*5.0/1024;// Renormalizing from 0 to 5 volts.
resistance = voltage*r_fixed/(5.00-voltage);//find unknown resistance
T = 1/(log(resistance/r_fixed)/B+1/T0)-273.14;//find temperature from unknown ressistance


Hall effect switches

Sometimes you find a non-contact switch is very useful in sensing presence and speed. Take car speedometer for example, you need to know how many turns the wheel makes per second to find the car’s speed. You could use a mechanical system to find out the speed of the wheel but a mechanical system is prone to failure. You need a non-contact measurement of the rotation of the wheel. In quantum physics, there exists no way that would measure something without changing the one being measured so no real non-contact measurement exists. But when everyday measurement is concerned, lots of ways constitute non-contact measurement. One can use a photo gate to tell speed. On the other hand, mud can also get into the system and prevents a photo sensor from working properly. An alternative is to use magnets and magnetic sensors. If you attach a magnet to the moving part of your wheel, then attach a magnetic sensor to a non-moving part of your car, close to the moving magnet, you can detect the presence of the magnet every time the wheel brings the magnet close to the sensor. If you keep your count and work out the relation between counts and angular speed, then angular speed and linear speed, you can display it on the speedometer.

So the sensor that we are going to use is a Hall effect switch, which is a digital element that outputs HIGH and LOW under different conditions. Here is the principle:

From physics, magnetic field affects charged particles. Inside a semiconductor, the charge carriers can be either positive or negative. Say you pass positive charge from left to right at a constant rate (current is constant). Then the magnetic field will affect the charge carriers and deflect them towards the side. The deflected charges are deposited on the side of the semiconductor, which set up an electric field. The electric field does just the opposite what the magnetic field does, deflecting the charges the other way around. Once there are enough deflected charges, the electric field will exert enough force to the moving charges to completely cancel the force from the magnetic field. At this point, the deflection stops and charge carriers flow through in a straight line. The stronger the magnetic field, the more charges need to be deposited and the greater the electric field. You can measure the field in terms of voltages, and deduce the amount of magnetic field strength, which is proportional to the voltage.

Here is a Hall effect switch:

There are three pins, 5V, ground, and signal.

For this particular one, bringing in North pole to it will result it to switch to HIGH. Then removing the north pole will not return the switch to LOW until the south pole is brought close to it. It will output LOW. A switch that retains its state until a different condition is met is called a latch. When north pole is brought near, the switch latches to HIGH, until when a south pole is brought in and the switch is latched to LOW.

Another type of sensor is not latched so if it senses north pole, it will switch to HIGH, then if north pole switch is removed, it switches to LOW. To find the switch that fits you, you should read the spec sheets on the logic behaviors.

Here is the link to the latching switch sold at

Here is the link to the non-latching switch sold at

With the non-latching switch as trigger, I was able to create a persistence of vision display. Come back and read more about my persistence of vision display when I post it!

Music box

Add to FacebookAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to TwitterAdd to TechnoratiAdd to Yahoo BuzzAdd to Newsvine

This is a project for a music box. It is not an ordinary music box as it doesn’t play songs but rather plays different musical tones when different sides of it faces up and gets a gentle tap.

Flip-n-shake/tap music box

You are given a well-decorated box, cube, with one musical note on each side,  flip it so that a desirable musical note faces up, shake or tap on the box, that note will play. When playing, the top side of box will glow with a certain color. Since there are 6 sides to a box, 6 notes can be associated with each side. I’ve built the prototype last weekend and managed to play a few simple songs by flipping and tapping on it. I am adding some video later this week. This box needs a lot of artistic touches in order to attract attentions. That is where I need some help. I hope to find some help at the Art Department. I imagine that when finished, two such boxes can be made so a person can pick them up with two hands and shake them to play as many as 12 notes. Many simple songs can be played with these two boxes.

Here is a demo:

This picture tells the inner working of the box prototype, an Arduino, a buzzer, and an accelerometer:

Please don’t mind the writings on the paper. I am looking for a house and I recycle/reuse paper 🙂

Stage 1: prototyping

The following is a video of the prototype. As you can see, the entire box is very ugly and needs a lot of artistic touch. I will post updates when I get more progress on it.

You have to crank your volume all the way up. I need a louder speaker and a lot of holes on the box!

Stage 2: adding light effects

Update: I’ve added some light effect and removed all the paper 🙂

You have to crank your volume all the way up. I need a louder speaker and a lot of holes on the box!

Stage 3: adding intelligence to the box

Now the box has a favorite tune. If you tap in the first 6 notes of this tune, the box will recognize it and plays the tune. In the future, I will purchase an MP3 shield to play high quality sound, like “Ah, that must have been my favorite tune, the XXX. I will play it for you”. Then it plays the tune in hi-def audio. I’ve removed the box top to make sure the sound volume is loud enough.

Stage 4: adding MP3-quality sound to the box

Check back later for this stage!

Stage 5: adding artistic touch to the box

Check back later for this stage!

Stage 6: adding lights to each side of the box

Check back later for this stage!

Stage 6: displaying the box in public place

Check back later for this stage!