Sump pump water level monitor using ESP8266 and Gmail sender update

For the last couple of weeks, it rained a lot and sometimes I got emails almost every 10 minutes sent by the sump pump monitor through ESP8266 I made (previous post). I thought that was too often and started thinking what would be better way to receive the notifications.

Here is what I wanted

  • to see more data than simple notification when the pump runs. In other words, I’d like to see periodic measured data such as the water level every minute.
  • to receive emails in regular basis, like every hour with the data collected for an hour. If I don’t get an email over an hour, that means there is something wrong, for example, power outage, monitoring system malfunction, wifi router error, or the monitoring system is sunk in the water (the worst case).
  • to receive email when the water level is too high.

So, I made some update and cleaned my original code. Now I get emails every hour and the title of the email look like this.

50 (41/69) 36 min

which means the current level is 50cm, the highest level for the past hour is 41cm, the lowest is 69cm. Since the ultrasonic sensor is mounted on top of the sump pump pit, the smaller number means the higher water level. 36min means the pump runs with 36 minutes interval. Now the body of the email looks like this.

69 67 66 65 65 64 62 61 60 60 59 58 57 56 55 54 53 52 51 51 50 49 48 48 47 46 46 44 42 41 69 68 67 66 65 64 63 62 61 60 59 59 58 57 56 55 54 52 52 51 50
It measures the water level (the distance from the sensor to the water surface) every minute (actually a little longer than a minute due to other delays) and converted into a string and add it up to a string for an hour and put the string value to the body of the email.
The Gmail widget on my phone shows the last few messages as shown below screenshot.
If you’re interested, you can download the Arduino code for this update from my github repository (LINK).

Golf GPS

After a few years of golfing, although my score is still not very good, I found that knowing the distance to the hole and how far I hit with the club helped me to choose a club better. There are commercial products to do this, but I wanted to make one for myself.

I have searched for small enough components to fit in a small plastic box (45mm x 30mm x 11mm inside) for golfing. Here is the list of the components for the gadget.

  • Plastic box: Hammond 1551F
  • GPS: PA6C
  • Display: OLED 128×64, I2C
  • Battery: LiPo 150mAh
  • Two push button switch with a little high actuation force to avoid accidental press
  • Microcontroller: Arduino bootloader (internal oscillator, 8MHz) loaded ATmega328p TQFP
  • Battery charger: MAX1555
  • PCB: 0.8mm thick with 2oz copper, designed with Eagle, used OSH Park to make 3 boards

The functions and requirements I thought about the gadget are listed below.

  • When powered on
    • Display date and time
    • If you are moving faster than 3km/h (like driving or walking), shows speed and bearing
    • Menu is ready to start playing golf
  • Before starting
    • Choose a course to play
    • Select starting hole, front or back
  • Display following information while playing golf.
    • Hole number
    • Current time
    • Distance to the hole (center of the green) in yard
    • Distance from the last shot (to see how far I can hit with the club I used) in yard
    • Total number of shots
    • Number of shots for current hole
  • Automatic advance to the next hole
  • Change hole to play manually at anytime in case you need to skip a hole or the automatic advance didn’t work properly (for example, you moved around the green back and forth to find the ball or forgotten club or whatever)
  • Subtract a shot from the total number of shots in cases of a shot added by mistake
  • Battery should last at least 5 hours
  • Two push button switches for menu and select
  • Programming port for improving the program, adding new course data, and battery charge
  • When the battery voltage drops below 3.5V, replace time on screen with “LOW”

Once I get a chance to play, I will find more functions to add (or remove). Hopefully it gets warmer soon.

So, here is the schematic diagram.

JeonLab golfGPS

Here is a little story about my experiences with the PCB fab houses. I used to order my PCBs to Seeedstudio. It was a few years ago when I ordered the PCB from there and the shipping fee was inexpensive although it took a little longer for delivery. Late last year, my son designed his first PCB and I helped him to order the PCB. I have also used OSH Park some time ago, so I compared the services between Seeedstudio and OSH Park. Since the PCB size was a little big (few inches by few inches), so I picked Seeedstudio which was cheaper. But later, I found they don’t offer regular mail to Canada anymore. They only offer express shipping options. That was even more expensive than for the PCB itself, but I wanted my son to get the board as quickly as possible, so ordered the parts to Seeedstudio. Later I found I needed to pay brokerage charge for custom. Bad bad experience. I will never use them anymore. Compared to them, OSH Park is amazing. For this small size PCBs, I paid just about $10 with free shipping to anywhere in Canada and US. It also took less than 2 weeks.

Here is the picture of the PCB. I don’t really like purple, but purple is their default color. But the color is not that important anyway.



And some pictures of assembled.



The plastic housing material is transparent with blue tint, but the surface is not smooth and has some texture. So, I had to sand the surface for better visibility for the OLED display. As you can see in pictures below, there is no problem to read numbers.



I was planning to add a micro SD card reader so that I can enter new course coordinate data from my laptop by simple text editing. But I changed my mind. First, there is no more space in the package for the SD card reader. Secondly, I won’t need to add new courses that often. Currently I have 4 courses around my place in the program. The 18 hole coordinate data is stored as 3 dimension array with float type. So, it will take only 144bytes (4bytes x 2 (latitude and longitude) x 18holes) per course. The compiled program occupies about 61% of the program storage area and there is still over 11kbytes.

For the OLED display, I used the library from Rinky-Dink Electronics. I’d like to thank him for sharing the library. It’s very small and fast. I also used the fonts found from his website and modified a little bit for narrower size.

I wrote my own GPS data parsing function. It reads only GPRMC data and parses date, time, and coordinate. I have used this parsing function previously in this post.

Regarding the distance calculation, I have developed a simple formula some time ago. It works pretty well even for short distance. See this post for more detail.

You can download the Arduino code here. You can freely use/modify it for your own projects under GPL-3.0 license. If you have any questions, email me or leave a comment below.


GPS distance measurement between two coordinates using Arduino

I knew the dimension of the LCD (Nokia 5110) as 43mm x 43mm but it looked smaller than I thought.  That’s good because I want to put it on top of the GPS (Holux M-1000).

In my previous post, I explained how to get coordinates, date & time, speed, and bearing data from GPS, Holux M-1000.  Now that I have the LCD, it’s time to add two parts to the Arduino sketch: 1) LCD driver/display, 2) distance calculation between two locations.

1. LCD Driver

First of all, I searched for a simple and small library for the LCD, Nokia 5110. There were a few different libraries for this LCD: Adafruit’s, Sparkfun’s, and Henning Karlsen’s.  Among these libraries, I chose Henning Karlsen’s because I needed only simple text display with a couple of different font sizes.  Henning Karlsen has separate library for graphics as well.  I would like to thank Henning for his sharing his nice work on the library.  Henning’s library supports 3 different font sizes: SmallFont (text and number, 6×8), MediumNumber (number only, 12×16), and BigNumber (number only, 14x 24).  Only downside of this library is that the Medium and Big fonts do not support texts but only numbers. However I would need only numbers to display with bigger fonts, this limitation was no problem with me.

2. Distance calculation between two locations

There are number of websites showing how to calculate distance between two locations from latitudes and longitudes. Movable Type Scripts shows various  calculations of distance, bearing and other useful conversions using Haversine formula and BlueMM posted the Excel formula to calculate distance which is basically the same way as Haversine.

The calculation is quite straightforward but I found there was a problem: Arduino (Atmega328p) cannot handle over 6-7th decimal digits which is very important in trigonometric calculation for short distance.

Arduino reference page says “Floats have only 6-7 decimal digits of precision. That means the total number of digits, not the number to the right of the decimal point. Unlike other platforms, where you can get more precision by using a double (e.g. up to 15 digits), on the Arduino, double is the same size as float.”

Let me give you an example.  Suppose we started from a position A (lat: 40.00, long: 80) to a position B (lat: 40.01, long: 80.00). That is, we moved 0.01 degrees in latitude only. If you calculate the distance using Haversine formula on your PC, you will get about 1,111.9m. However, Arduino calculates it as 3,110.8m. Big error!  More interesting thing is that even if you reduce the latitude difference to 0.001 or 0.0001 degrees, you get the same results, 3,110.8m. So I investigate further what exactly cause this error. Of course I know the culprit is the float precision limitation as said above. But I wanted to know which part of the calculation by Arduino cause this big error. In the Haversine formula, there are COS, SIN and ACOS functions used.  I tested a few different calculations using these functions and found the calculation of COS and SIN functions affect minimal but the problem was the ACOS.  If you calculate the formula on your PC only inside of ACOS bracket, you will get 0.9999999848. See my point? The decimal places below 6th in ACOS function is actually important to calculate the angular difference for small distance, but unfortunately Arduino cannot handle this.  Not only for small distance but for even relatively long distance (say over 1 degree for instance) there is error between the results on the PC and Arduino.

Well, so I started thinking about how to avoid trigonometric function calculation when over 6th decimal places are important. And I found a solution! Instead of calculating angular difference between two positions and THEN calculating the distance by multiplying the mean earth radius, calculating a ratio of angle between two positions (latitude and longitude separately) over 360 degrees and divide the circumference of the earth by this ratio. In other words, keep the numbers big while calculation. Arduino’s float type has a limitation on the small decimal places, but can handle relatively big numbers!

Here is my formula:

The mean circumference of the earth is 2 x 6,371,000m x π = 40,030,170m

Δd (lat) = 40,030,170 x ΔΘ (lat) / 360 (assuming ΔΘ is small)

Δd(long) = 40,030,170 x ΔΘ(long) x cosΘm / 360 (Θm: mean latitude between two positions)

Now, the distance is √[Δd (lat)^2 + Δd (long)^2]

Below is the test Arduino sketch to test my formula.  The result is 11.029m while Haversine formula for the same coordinates gives 11.119m.  This is close enough considering the accuracy of the most GPS is bigger than one meter.

float gpsLat0 = 40.0;
float gpsLat = 40.0001;
float gpsLong0 = 80.0;
float gpsLong = 80.0;

void setup()
float delLat = abs(gpsLat0-gpsLat)*111194.9;
float delLong = 111194.9*abs(gpsLong0-gpsLong)*cos(radians((gpsLat0+gpsLat)/2));
float distance = sqrt(pow(delLat,2)+pow(delLong,2));

void loop()

To be continued….

GPS (M-1000) with LCD (Nokia 5110)

Finally, I got the Nokia 5110 LCD that was ordered on eBay a few weeks ago. It took me a couple of days to find the best library for the LCD and quickly updated my Arduino program to display current location (latitude and longitude), date/time, speed, and bearing. There is 2.8V regulated power in the GPS that powers the JeonLab mini and LCD. I will upload my sketch and full detail later.

 photo GPSwithLCD5110_currentlocation.jpg

GPS (Holux M-1000) signal read using Arduino 1: coordinate/bearing/speed and UTC

Holux M-1000 is a GPS receiver with a Bluetooth.  I had used it for navigation with Palm TX and Treo700p (yes, I have long been a big fan of Palm PDA series) and Geocaching until I bought Android smartphone which has a built-in GPS module. So Holux M-1000 has been in my drawer collecting dust for more than a year. From last summer, I began to play golf and I think I’m getting better. 🙂  I searched and found a lot of Android applications for assist golfing with maps, hole/hazard information, showing how many yards left and so on. I’m a gadget mania so I downloaded most of them and tried but none of them satisfied me.  In most of cases, I didn’t bother to pull out my phone and enter my password to unlock the phone and go to the application and run and wait.  Well, one might say that why not keep the phone ON while you are playing? Yes, you can do that. But the GPS module drains battery so fast and I don’t want to miss any phone calls because of the low battery.  Not only because of the battery consumption, I can’t find any application fits me (yet). So I thought I would like to have a GPS module, very simple module, that can show distance between two locations. For example, at a tee, the first location can be marked by pressing a button on the device and from that point, the device shows how far I moved while I walk to the spot for the second shot. And then I can push another (or the same) button to clear the first point and mark current spot as the first location and do the same, and so on. What parts would I need for building this device?  Here is the list of the part I noted.

  • GPS module that can communicate with Arduino (or Jeonlab mini, of course 🙂
  • LCD: I have a 16×2 LCD but it’s bulky and shows only two lines. I have ordered popular Nokia 5110 LCD on ebay and I’m waiting for it as of this writing.
  • Arduino compatible board (preferably small)
  • Power (battery for sure)
  • some resistors, caps, wire, prototyping board, push button switches etc.

That’s when I remembered my old gadget, Holux M-1000.  It has a bluetooth which means it should have serial output somewhere between the GPS module and the bluetooth module.  I started opening up the Holux M-1000 and found RX… TX… on the PCB. YES!!  But I needed to know what voltage requirements for these pins. So I searched on internet for a datasheet or instruction manual of Holux M-1000 and found there were already some people tried to read GPS signal from the Holux M-1000 using either Arduino or PIC microcontrollers. Maybe I was not very lucky to find good articles but none of them were quite useful to give me answers what I wanted clearly.  I found the User’s Manual (1371865.pdf) from Holux homepage and I got very important information as below.

  • Pin 4 and 3 on the USB mini B connector on Holux M-1000 are TX and RX (so I don’t have to add wires from the PCB. That’s good news to make my life easier. In fact, I had thought the USB jack is only for charging the battery!)
  • Pins 5 and 1 of the USB connector are Vcharge (5V) and GND, respectively as standard USB pinouts.
  • Those two RX and TX pins’ voltage range is 3.3 – 5V
  • Data format: NMEA0183 V3.01, GGA, RMC, VTG, GSA, GSV
  • Power consumption: 40 – 50mA in normal mode, 35mA in power saving mode

Now, I’m not familiar with NMEA data format, so I searched on internet again and found some good sites here and there. There are bunch of GPS information you can get from sentences that Holux M-1000 generates periodically as GGA, RMC, VTG, GSA, and GSV, but I don’t need all of them. All I need is latitude and longitude actually, but additional information such as time and date, bearing, speed will be good to know as well.  The sentence, RMC has all of these. Well, program might be simple if I needed to read data from only one sentence, then.  photo Holux-Jeonlab.jpg The GPS (Holux M-1000) and the Jeonlab mini v1.3 with an FTDI breakout board are shown above. I have USB A to mini-B cable but I didn’t want to cut the cable, so I used a female USB-A connector as shown below. Note that only 3 pins (V+, GND, and TX from GPS) are used since I only need to read serial data from the GPS, not sending any command or data to it.  photo USBpinout.jpg And the picture below shows how they connected each other. The FTDI breakout board is connected to my computer through USB cable.  photo Holux-Jeonlabconnection.jpg While I’m testing, I need serial communication between the Jeonlab mini and my computer and I will need these pins (RX, TX on the Jeonlab mini) later when I want to modify my program.  So I decided to use the Softwareserial library which is already included in the Arduino libraries. The TX pin from the GPS is connected to the pin 10 of the Jeonlab mini.  I also connected the V+ from the GPS to the Vcc pin of the Jeonlab mini as well as GND pins. In fact, you don’t need to connect the V+ pins as long as they are powered up by their own power source, but this way I can continuously charge the GPS battery from my computer USB port. I will need more time to finish the whole program while I’m waiting for the LCD that I bought, but let me show how I have programmed so far.  It can read RMC data from the GPS and get the coordinate, bearing, speed, date and time. Thanks to ‘serial parse’ function that is included in the Arduino version >1.0, it was easy to get numeric values from the serial data coming in from the GPS. However, one tricky thing was to get the local time from UTC time and date. I had to consider time zone, DST(daylight saving time), number of days of each month, leap year, etc. That was fun to figure out how to get correct time and date. Here is my code so far. I guess it is quite straight forward, but if you have any question, please add a comment below.

 GPS distance measuring
    - GPS: Holux M-1000
    - Arduino: JeonLab mini v1.3
    - LCD: Nokia 5110
 Programmed by: Jinseok Jeon (
 Date: Sep 2013
 Revised: Oct 28, 2013

#include <SoftwareSerial.h>
SoftwareSerial gps(10, 0); // RX, TX

const int TimeZone = -5; //EST
int DSTbegin[] = { //DST 2013 - 2025 in Canada and US
  310, 309, 308, 313, 312, 311, 310, 308, 314, 313, 312, 310, 309
int DSTend[] = { //DST 2013 - 2025 in Canada and US
  1103, 1102, 1101, 1106, 1105, 1104, 1103, 1101, 1107, 1106, 1105, 1103, 1102
int DaysAMonth[] = { //number of days a month
  31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
int gpsYear;
int gpsMonth;
int gpsDay;
int gpsHour;
byte gpsMin;
byte gpsSec;
//float distance;
float gpsLat0;
float gpsLong0;
float gpsLat;
float gpsLong;
float gpsSpeed; //km/h
float gpsBearing; //deg
boolean LEDstate = false;
boolean SpeedWatch50;
boolean SpeedWatch70;
boolean SpeedWatch120;

#include <LCD5110_Basic.h>

LCD5110 LCD(6, 5, 4, 2, 3); //SCLK, MOSI/DIN, DC, RST, CS/CE
extern uint8_t SmallFont[];      // 6x8 pixels
extern uint8_t MediumNumbers[];  // 12x16 pixels
//extern uint8_t BigNumbers[];     // 14x24 pixels

void setup()
  pinMode(8, OUTPUT); //LED
  digitalWrite(8, 1); //LED off
  pinMode(7, INPUT_PULLUP);
  pinMode(9, INPUT_PULLUP);
  pinMode(12, INPUT_PULLUP);
  LCD.setContrast(70); //0-127, you need to find proper number
  LCD.print("JeonLab", RIGHT, 16);

void loop()
  int a1, a2, b1, b2;
  if (gps.available() > 1)
    if (char( == 'R' && char( == 'M' && char( == 'C')
      gps.parseFloat(); //discard unnecessary part
      a1 = gps.parseInt();
      a2 = gps.parseInt();
      b1 = gps.parseInt();
      b2 = gps.parseInt();
      gpsLatLong(a1, a2, b1, b2);
      gpsSpeed = gps.parseFloat() * 1.852; //knot to km/h
      gpsBearing = gps.parseFloat();
      if (gpsYear % 4 == 0) DaysAMonth[1] = 29; //leap year check

      //Time zone adjustment
      gpsHour += TimeZone;
      //DST adjustment
      if (gpsMonth * 100 + gpsDay >= DSTbegin[gpsYear - 13] &&
          gpsMonth * 100 + gpsDay < DSTend[gpsYear - 13]) gpsHour += 1;
      if (gpsHour < 0)
        gpsHour += 24;
        gpsDay -= 1;
        if (gpsDay < 1)
          if (gpsMonth == 1)
            gpsMonth = 12;
            gpsYear -= 1;
            gpsMonth -= 1;
          gpsDay = DaysAMonth[gpsMonth - 1];
      if (gpsHour >= 24)
        gpsHour -= 24;
        gpsDay += 1;
        if (gpsDay > DaysAMonth[gpsMonth - 1])
          gpsDay = 1;
          gpsMonth += 1;
          if (gpsMonth > 12) gpsYear += 1;
      LCD.clrRow(0);//8 pixel high row to clear (0-5)
      LCD.printNumF(gpsSpeed, 0, LEFT, 0); //km/h
      if (gpsSpeed > 2)
        LCD.printNumF(gpsBearing, 0, RIGHT, 0); //bearing in degree

      LCD.printNumI(gpsMonth, 0, 24, 2, '0');
      LCD.print("-", 12, 24);
      LCD.printNumI(gpsDay, 18, 24, 2, '0');
      LCD.print("-", 30, 24);
      LCD.printNumI(gpsYear, 36, 24);

      LCD.printNumI(gpsHour, 54, 24, 2, '0');
      LCD.print(":", 66, 24);
      LCD.printNumI(gpsMin, 72, 24, 2, '0');

      if (gpsLat0 != 0.0)
        float distLat = abs(gpsLat0 - gpsLat) * 111194.9;
        float distLong = 111194.9 * abs(gpsLong0 - gpsLong) * cos(radians((gpsLat0 + gpsLat) / 2));
        float distance = sqrt(pow(distLat, 2) + pow(distLong, 2));

        LCD.clrRow(4);//8 pixel high row to clear (0-5)
        LCD.printNumF(distance, 0, LEFT, 32);
        LCD.print("meter", RIGHT, 32);
        LCD.printNumF(distance / 0.9144, 0, LEFT, 40);
        LCD.print("yard", RIGHT, 40);
      if (gpsSpeed <= 50) SpeedWatch50 = 0;
      if (gpsSpeed <= 70) SpeedWatch70 = 0;
      if (gpsSpeed <= 120) SpeedWatch120 = 0;

      if (gpsSpeed > 50 && SpeedWatch50 == 0)
        SpeedWatch50 = 1;
        tone(11, 4978, 100);
      if (gpsSpeed > 70 && SpeedWatch70 == 0)
        SpeedWatch70 = 1;
        for (int i = 1; i <= 2; i++)
          tone(11, 4978, 100);
      if (gpsSpeed > 120 && SpeedWatch120 == 0)
        SpeedWatch120 = 1;
        for (int i = 1; i <= 3; i++)
          tone(11, 4978, 100);
  if (digitalRead(12) == LOW) //marking current position
    tone(11, 3140, 100);
    if (gpsLat0 == 0.0)
      gpsLat0 = gpsLat;
      gpsLong0 = gpsLong;
      gpsLat0 = 0.0;
      gpsLong0 = 0.0;
  if (digitalRead(7) == LOW) //LED backlight toggle
    tone(11, 2810, 100);
    digitalWrite(8, LEDstate); //LED on
    LEDstate = !LEDstate;
  if (digitalRead(9) == LOW) //for future functional button
    tone(11, 3910, 100);


void gpsTime(long UTC)
  gpsHour = int(UTC / 10000);
  gpsMin = int(UTC % 10000 / 100);
  gpsSec = UTC % 100;

void gpsLatLong(int lat1, int lat2, int long1, int long2)
  gpsLat = int(lat1 / 100) + (lat1 % 100) / 60.0 + float(lat2) / 10000.0 / 60.0;
  gpsLong = int(long1 / 100) + (long1 % 100) / 60.0 + float(long2) / 10000.0 / 60.0;

void gpsDate(long dateRead)
  gpsDay = int(dateRead / 10000);
  gpsMonth = int(dateRead % 10000 / 100);
  gpsYear = dateRead % 100; //last 2 digits, e.g. 2013-> 13

Digital Car Compass and Thermometer

My car doesn’t have a compass which I wish to have one. So I started making one using my JeonLab mini v1.3 (minimalist Arduino compatible board), popular 16×2 LCD panel with a back light LED, and a 3 axis magnetometer.  Here is the part list and pictures of the LCD, JeonLab mini v1.3 and the prototyping board.

  • LCD: 16×2 HD44780 LCD (white text on blue background)
  • JeonLab mini v1.3
  • Digital compass: MAG3110 (bought an assembled from ebay)
  • Temperature sensor: TMP36
  • Phototransistor: LTR-4206E
  • 7805 regulator
  • resistors and capacitors (see schematic diagram)
  • Car battery jack
  • prototyping board
  • push button switch
  • solid copper wire (1mm in diameter) for bracket
  • cable ties

parts photo 20130203_162415.jpg

The JeonLab mini v1.3 is so small that can be attached to the back of the LCD.

compass & LCD test photo 20121228_174420.jpg

First of all, the LCD, JeonLab mini and the magnetometer, MAG3110 have been assembled on a breadboard and tested. The magnetometer has 3 axis sensor, but because, fortunately, the most roads where I live and commute to work are relatively level. So I didn’t bother to use complicated equations, but decided to calculate simply the heading angle using ATAN from X and Y readings. And it really works just good enough. Take a look at the source Arduino code below.
JeonLab Car Digital Compass & Thermometer

LCD display
Digital compass (MAG3110)
Interior temperature
LCD backlight brightness automatic adjust

MAG3110 read: Original code from Sparkfun example code

#include #include <avr/eeprom.h>

#define MAG_ADDR 0x0E
int avgX, avgY;

struct settings_t
long maxX, minX, maxY, minY;

LiquidCrystal lcd(2,3,6,7,8,9);

void setup()
config(); //configuration of the magnetometer, MAG3110
pinMode(10,INPUT); //temperature sensor
pinMode(5,OUTPUT); //LCD backlight LED
analogWrite(5, 100);

//read previously stored calibration data from EEPROM
eeprom_read_block((void*)&settings, (void*)0, sizeof(settings));

lcd.begin(16, 2);

void loop()
//read the magnetometer and calculate heading
float heading = (atan2(readx()-avgX, ready()-avgY))*180/PI;

//read and calculate the interior temperature in celcius
float temp = (analogRead(0)/1024.0*5000.0-500)/10;

//read ambient brightness from the photo-transistor
int brightness = map(analogRead(1), 900, 1023, 50, 255);
analogWrite(5,brightness); //LCD backlight LED voltage control by PWM

//diaplay compass bearing
lcd.print(” “);
if (abs(heading) <= 22.5) lcd.print(“N “); if (abs(heading) >= 157.5) lcd.print(“S “);
if (heading >= 67.5 && heading <= 112.5) lcd.print(“E “);
if (heading <= -67.5 && heading >= -112.5) lcd.print(“W “);
if (heading > 22.5 && heading < 67.5) lcd.print(“NE”);
if (heading < -22.5 && heading > -67.5) lcd.print(“NW”);
if (heading > 112.5 && heading < 157.5) lcd.print(“SE”);
if (heading < -112.5 && heading > -157.5) lcd.print(“SW”);

if (heading < 0) heading += 360.0; //display heading lcd.setCursor(3,0); lcd.print(int(heading)); lcd.setCursor(7,0); lcd.print(int(temp)); lcd.print(“\337C”); lcd.setCursor(0,1); lcd.print(” “); lcd.setCursor(0,1); lcd.print(“Brightness: “); //show PWM value for a reference lcd.print(brightness); if (digitalRead(10) == HIGH) //monitor calibration button status { analogWrite(5,200); lcd.setCursor(0,1); lcd.print(“calibrating…..”); delay(1000); calXY(); } delay(1000); } void calXY() //magnetometer calibration: finding max and min of X, Y axis { int tempXmax, tempXmin, tempYmax, tempYmin, newX, newY; lcd.setCursor(0,1); lcd.print(“Rotate the car “); delay(1000); lcd.setCursor(0,1); lcd.print(“and press button”); delay(1000); lcd.setCursor(0,1); lcd.print(“Now, begin! “); delay(500); tempXmax = tempXmin = readx(); tempYmax = tempYmin = ready(); while(digitalRead(10) == LOW) { newX = readx(); newY = ready(); if (newX > tempXmax) tempXmax = newX;
if (newX < tempXmin) tempXmin = newX; if (newY > tempYmax) tempYmax = newY;
if (newY < tempYmin) tempYmin = newY;
settings.maxX = tempXmax;
settings.minX = tempXmin;
settings.maxY = tempYmax;
settings.minY = tempYmin;

//store new X, Y values in the EEPROM
eeprom_write_block((const void*)&settings, (void*)0, sizeof(settings));


lcd.print(“Calibration done”);
lcd.print(” “);


void config(void) //MAG3110 config taken from Sparkfun example
Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
Wire.write(0x10); // cntrl register1
Wire.write(0); // send 0x00, standby mode
Wire.endTransmission(); // stop transmitting


Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
Wire.write(0x11); // cntrl register2
Wire.write(0x80); // send 0x80, enable auto resets
Wire.endTransmission(); // stop transmitting


Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
Wire.write(0x10); // cntrl register1
Wire.write(0x19); // send 0x01, active mode
Wire.endTransmission(); // stop transmitting


void print_values(void)

int readx(void) //MAG3110 read X value taken from Sparkfun example
int xl, xh; //define the MSB and LSB

Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
Wire.write(0x01); // x MSB reg
Wire.endTransmission(); // stop transmitting

delayMicroseconds(2); //needs at least 1.3us free time between start and stop

Wire.requestFrom(MAG_ADDR, 1); // request 1 byte
while(Wire.available()) // slave may send less than requested
xh =; // receive the byte

delayMicroseconds(2); //needs at least 1.3us free time between start and stop

Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
Wire.write(0x02); // x LSB reg
Wire.endTransmission(); // stop transmitting

delayMicroseconds(2); //needs at least 1.3us free time between start and stop

Wire.requestFrom(MAG_ADDR, 1); // request 1 byte
while(Wire.available()) // slave may send less than requested
xl =; // receive the byte

int xout = (xl|(xh << 8)); //concatenate the MSB and LSB
return abs(xout);

int ready(void) //MAG3110 read Y value taken from Sparkfun example
int yl, yh; //define the MSB and LSB

Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
Wire.write(0x03); // y MSB reg
Wire.endTransmission(); // stop transmitting

delayMicroseconds(2); //needs at least 1.3us free time between start and stop

Wire.requestFrom(MAG_ADDR, 1); // request 1 byte
while(Wire.available()) // slave may send less than requested
yh =; // receive the byte

delayMicroseconds(2); //needs at least 1.3us free time between start and stop

Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
Wire.write(0x04); // y LSB reg
Wire.endTransmission(); // stop transmitting

delayMicroseconds(2); //needs at least 1.3us free time between start and stop

Wire.requestFrom(MAG_ADDR, 1); // request 1 byte
while(Wire.available()) // slave may send less than requested
yl =; // receive the byte

int yout = (yl|(yh << 8)); //concatenate the MSB and LSB
return abs(yout);

And the schematic diagram is below.
Schematic photo JeonLabCarDigitalCompassThermometer-1.png

I have introduced a step-by-step assembling procedure on Instructable, and here are some pictures of assembling and mounting on top of the interior mirror of my car.

assembling JeonLab mini v1.3 photo 20130203_165903.jpg

Note that there is no LED attached. A 6-pin header is attached upwards for the FTDI USB interface and 3 single header pins are attached at the bottom of the JeonLab mini to support on the prototyping board which will be attached to the back of the LCD.

JeonLab mini on the back of the LCD photo 20130209_122723.jpg

 photo 20130217_124514.jpg
The temperature sensor (TO-92 package), a voltage regulator, and a calibration switch are assembled.

finished assembly photo 20130317_163954.jpg
Next to the temperature sensor, the phototransistor (looks like a 3mm LED in black) is added to adjust the LED backlight of the LCD automatically.

wrapping heat shrink tube photo 20130409_193307.jpg
A thick solid copper wire (appx. 1mm in diameter) is used to form a simple bracket on top of the interior mirror.

finalizing bracket photo 20130409_194316.jpg
A heat shrink tube is used to insulate the copper wire bracket where it touches the LCD PCB.

attched to the mirror photo 20130409_194552.jpg
Two short cable ties are used to fix the assembled LCD and bracket on top of the mirror.

magnetometer fix photo 20130413_153144.jpg
The magnetometer is held by a small suction cup on the wind shield at the back of the mirror.

in my car photo 20130410_174041.jpg
Finally, it works!

Wii Nunchuck hack: making an electronic level with Arduino compatible JeonLab mini v1.3

I have posted a project on using the accelerometer chip in the broken Wii Nunchuck. It was broken: the joystick did’t work. However, the accelerometer chip in the Nunchuck was intact and it also has the I2C interface which can be easily communicate with Arduino (or compatible board) with the Wire.h library.

I have seen those applications on iPod touch or Android tablets that can be used as a level using their built-in accelerometer sensor chip with a nice graphic showing bubble level.  I thought I could make one like that with the Wii Nunchuck and started building one.  I had bought a Wii Nunchuck from ebay to replace my kids’ broken Nunchuck for less than $10 (I don’t remember exactly) and I thought it was much cheaper to buy them than to buy the accelerometer with I2C interface or breakout boards so I bought a couple more at that time.

The joystick and the PCB look like this.
Wii Nunchuck PCB-Joystick

I don’t need the (broken) joystick part, so I cut off that part.
Accelerometer part of the Wii Nunchuck PCB top
The accelerometer chip (A7260) is shown.

The I2C converter is at the bottom of the PCB.
Accelerometer part of the Wii Nunchuck PCB bottom

Now I need a case for this project and found perfect size clear acrylic case from my junk box. I don’t even remember where I got it.
Clear case
Clear case width
Clear case height

The width inside of the case was almost perfect for the JeonLab mini v1.3. I had to file off about half mm of the PCB. I also thought to use a 3.0V CR123A battery for this project.
JeonLab mini v1.3 in clear case with CR123A

But later I changed the power supply to a 3.3V regulated with a 12V A23 battery for better stability.

The cut PCB from the Nunchuck was glued on top of the ATmega328P chip on the JeonLab mini v1.3.
Wii Nunchuck PCB on JeonLab mini v1.3 in case

The I2C wires, clock and data, are connected to the analog pin 5 and 4 on the JeonLab mini v1.3, respectively.
I2C wiring between Wii Nunchuck PCB and JeonLab mini v1.3

I also connected the power for the Nunchuck board to the JeonLab mini v1.3 board as shown below, but this was my mistake.
Power sharing between Wii and JeonLab mini

The power supply I thought was 3.0V battery, so I thought sharing the power should be fine. BUT I forgot the program upload through the FTDI. The accelerometer chip and the I2C interface need 3.3V (3.0-3.6V) and the ATmega328 on the JeonLab mini v1.3 (and other Arduino compatible boards as well) can work 3-5V. The Nunchuck data reading header, nunchuck_funcs.h (from WiiChuckDemo by Tod E. Kurt) provides the settings for utilizing the analog pins 3 and 2 as power source for the Nunchuck board but this provides 5V, not 3.3V. The problem is that 5V supply to the Nunchuck board could damage the chip(s) either the accelerometer or the I2C chip or both. Actually, the first one I used had been unstable and noisy, so it had to be replaced with a new one. That’s when I decided to change the power source from the 3V battery to 12V battery with a 3.3V regulator and added a Schottky diode (1N5819) to protect the Nunchuck board from FTDI 5V supply.

Now, let me explain the design. Using the accelerometer sensor on the Nunchuck board, it detects which side is tilted and send the 3 axis data to the Arduino program loaded JeonLab mini board through the I2C protocol. The program compares the current data to the stored (in EEPROM of the ATmega328P) calibration data. There are three stages of displaying: 1) If the value is within certain range, it will turn on the central red LED connected to the digital pin 7; 2) If the value is greater than the range (sens in the program) and less than 2 times of the range (sens), it will turn on the red LED and one green LED at the opposite (in order to simulate the bubble direction) side of the tilt; 3) If the value is greater than 2 times of the range (sens), then only the green LED is turned on.

The calibration values are the neutral value of each axis reading when it is leveled on that axis. For example, the Nunchuck data reading is between 60-70 (these values are different from sensor to sensor) at -g (upside down) on that axis and is over 170 at g (up right). So the neutral (leveled) value of each axis is about 120-130. The calibration begins when the pin 10 goes HIGH by connected to V+ with a small push button switch pressed. One the calibration process begins, in order to give the user some time to put the device down on a flat surface, it waits until the central red LED blinks a few times. The actual calibration is done really quickly and followed by a few quicker blinks.

Here is the whole program.

 * Wii_Nunchuck_Level
 * Feb-Mar 2012, Jinseok Jeon
 * Wii Nunchuck data read:
 *  nunchuck_funcs.h from WiiChuckDemo by Tod E. Kurt, 

#include "nunchuck_funcs.h"

byte accl[3]; //accelerometer readings for x, y, z axis
int calPin = 10; //calibration pin
int sens = 1; //sensitivity
int orient;

void setup()
  for (int i=5;i&lt;10;i++) { 
    pinMode(i, OUTPUT);
  } //9 left, 8 up, 7 center, 6 down, 5 right
  pinMode(calPin, INPUT);

void loop()
  //if the calibration pin is pressed, jump to funcion calibrate()
  if (digitalRead(calPin) == HIGH) calibrate();

  if (orient == 1 || orient == 2) {
    if (abs(accl[0] + orient*10))  sens) digitalWrite(5, HIGH);
    if ( + orient*10)-accl[0] &gt; sens) digitalWrite(9, HIGH);
  if (orient == 3 || orient == 4) {
    if (abs(accl[1] + orient*10))  sens) digitalWrite(8, HIGH);
    if ( + orient*10)-accl[1] &gt; sens) digitalWrite(6, HIGH);
  if (orient == 5 || orient == 6) {
    if (abs(accl[0] + orient*10)) &lt;= 2*sens &amp;&amp; abs(accl[1] + orient*10))  sens) digitalWrite(5, HIGH);
    if ( + orient*10)-accl[0] &gt; sens) digitalWrite(9, HIGH);
    if (accl[1] + orient*10) &gt; sens) digitalWrite(8, HIGH);
    if ( + orient*10)-accl[1] &gt; sens) digitalWrite(6, HIGH);

  for (int i=5;i&lt;10;i++) { //turn off all LEDs
    digitalWrite(i, LOW);

void getData()
  accl[0] = nunchuck_accelx();
  accl[1] = nunchuck_accely();
  accl[2] = nunchuck_accelz();

  orient = orientation(); //get orientation

void calibrate()
  for (int i=0;i&lt;3;i++) {
    digitalWrite(7, HIGH);
    digitalWrite(7, LOW); 


  for (int i=0;i&lt;3;i++) {
    EEPROM.write(i + orient*10, accl[i]);

  for (int i=0;i 125 &amp;&amp; accl[0]  110 &amp;&amp; accl[2]  170) orient = 1; //bottom on floor
    else if (accl[1]  110 &amp;&amp; accl[1]  110 &amp;&amp; accl[2]  180) orient = 3; //left on floor
    else if (accl[0]  110 &amp;&amp; accl[1]  125 &amp;&amp; accl[0]  170) orient = 5; //back on floor
    else if (accl[2] &lt; 80) orient = 6; //front on floor
  return orient;

Some pictures below show the assembling procedure of the LEDs and the tiny switch from a broken camera. Here I want to give all of you a note: don’t throw away any broken electronics. Because they don’t work doesn’t mean they are garbage. There are a lot of good parts you can use for other projects.

Bubble LEDs
assembled bubble LEDs and resistors
assembled JeonLabmini v1.3 - Wii Nunchuck - bubble LEDs

The tiny switch found from a broken camera.
micro switch for calibration

A 10k resistor is used to pull down the pin 10 and this tiny switch is connected to the pin 10 and V+ to trigger the calibration.
Calibration switch connection

Now these are the parts for the power supply. There are a piece of prototype board, a Schottky diode (from a broken power adapter), 0.1uF ceramic capacitor, a 10uF electrolyte capacitor, 12V A23 battery, 3.3V regulator LD33V, and battery contacts also found from the broken camera.
Power supply parts
Battery contacts from broken camera

The battery contacts were modified a little bit and soldered on the board. The regulator doesn’t need the big heat sink so the metal part was cut on top and soldered on the board and it also form a perfect battery holder.
battery holder with 3.3V regulator

This is assembled power supply in the case.
power supply with rearragned caps

Fully assembled Wii Nunchuck Level:
Completed Wii Nunchuck Level top

When it is leveled:
Wii Nunchuck Level leveled

When it is tiled to left:
Wii Nunchuck Level tilted left

When it is tilted to right:
Wii Nunchuck Level tilted right

And here is the Youtube video showing how it works.

MAKEFILE settings for the ATtiny45/85 programmer with JeonLab mini or Arduino

In order to program an ATtiny45 or ATtiny85 with the JeonLab mini (or Arduino) wirh the WinAVR (AVRdude), you need to change the MAKEFILE as follows.

1. MCU name
MCU = attiny85 # or attiny45

2. change winavr folder location if needed (default: c:\winavr)
EXTRAINCDIRS =c:\WinAVR-20100110\avr\include
DIRAVR = c:/WinAVR-20100110

3. Programmer setting
AVRDUDE_PORT = com9 # change this for your connection
AVRDUDE_BITS_PER_SEC = -b 19200 # add this line

That’s all you need to make changes to the default MAKEFILE for this particular programmer. Leave all the other settings as default.

JeonLab mini ATtiny programmer using Arduino ISP

For relatively small (less number of pins than ATmega328) project, ATtiny series, ATtiny45 or Attiny85 are good choice in terms of its physical size (8-DIP or 8-SOIC)  and low power consumption.

There are many ways to program it. One of the popular device is USBtinyISP and DASA. Both of them work very well with WinAVR (AVRdude).

I’d like to share how I program ATtiny85 with JeonLab mini 1.3. The idea has been adapted from High-Low Tech Group and One missing note from High-Low Tech Group is that you need to add a 110-120 ohm resistor between VCC and Reset pins of JeonLab mini (or Arduino) to prevent Auto reset on serial connection as explained in here and here.

You will need a JeonLab mini or Arduino or any Arduino compatible board with FTDI USB interface. Here is an example with JeonLab mini v1.3.
ATtiny programmer with JeonLab mini

I used a piece of prototype board to assemble a JeonLab mini v1.3, 6pin male header for the FTDI basic board (Sparkfun), 3 indicating LEDs, a 8pin DIP socket, and a ceramic resonator for ATtiny (if you are using internal oscillator, you don’t need it). I also added another LED to the ATtiny PB0 (pin 5) in order for quick debugging, but if you don’t need or want it, just ignore it. The function of those indicating LEDs in ArduinoISP sketch you will upload later are:

9 (red, right): Heartbeat – shows the programmer is running
8 (red, middle): Error – Lights up if something goes wrong
7 (green, left): Programming – In communication with the slave

Here is a picture before assembling the JeonLab mini PCB. You can see the 100+15 ohm in the middle of where the JeonLab PCB is to be mounted.
assembling ATtiny programmer on prototype board

Fully assembled board.
assembled JeonLab mini ATtiny programmer

Or you can use a breadboard.
ATtiny programmer with JeonLab mini on breadboard

Now go visit High-Low Tech Group and download ATtiny 45/85 support hardware files and extract them to hardware folder in Arduino. Once this is done, connect the board to USB port of your computer and run Arduino and load ArduinoISP sketch. Check your board setting (see below picture) and port number and upload ArduinoISP to the JeonLab or Arduino.


As you can see in the picture above, there are new hardware (board) options, ATiny45 and ATtiny85. Now your JeonLab mini or Arduino has been transformed into a ATtiny 45/85 programmer.

Using this configuration, you can upload your Arduino (of course, there are some limitations like pin numbers and memory capacity) sketches to the ATtiny 45 or 85 from Arduino IDE. Here is an example with the famous Blink sketch. Note you have to change the pin number 13 to 0 (or 1, 2 if you connect an LED there).

Blink upload_ATtiny85
Please note the board should be selected as ATtiny 45 (or 85) (w/ Arduino as ISP). You will encounter two errors as below but you can ignore them.

avrdude: please define PAGEL and BS2 signals in the configuration file for part ATtiny85
avrdude: please define PAGEL and BS2 signals in the configuration file for part ATtiny85

Not only from Arduino IDE, but you can also program your ATtiny with WinAVR or avrdude from DOS command window using this set-up.



New! JeonLab mini v1.3 (Arduino compatible)

JeonLab mini v1.3 assembled 1

This new version of JeonLab mini is a solderless breadboard friendly Arduino compatible board with minimal components. The key features of this board are:

  • Arduino bootloader loaded ATmega328p (28-pin DIP)
  • 3 resistors and a capacitor are attached to the bottom as they are thinner than the height of the header plastic
  • all through-hole components
  • pins for the FTDI connector for program (sketch) load or USB-serial communication
  • no power regulator
  • 2 LEDs for the power and d13 pin
  • 16MHz ceramic resonator with built-in capacitors

JeonLab mini v1.3 assembled bottom

JeonLab mini v1.3 on bread board with FTDI

Pin arrangement:

JeonLab mini 1.3 pins

JeonLab mini v1.3 schematic