AVR CAN Bus Project: Step 4 – LeafCAN: Nissan Leaf SOC Meter

I have implemented a SOC (State of Charge) meter for the Nissan Leaf. Many thanks to garygid and others from the MyNissanLeaf forums, for their help in decoding the Leaf CAN bus messages, and figuring out the pinouts.

The top line shows the SOC%, raw SOC value, and number of charge bars displayed in the dash.
The second line shows battery pack voltage and current in amps.

You can download the Eagle CAD schematic and AVR (Arduino) code from github:  lincomatic / LeafCAN
The Eagle schematic uses the Sparkfun library.

The schematic shows how to implement the entire circuit, without using the Olimex AT90CAN128 breakout board.

My original intent was to make a small PCB that directly attached to the LCD, and put it into a small case, but I never got it past the breadboard stage.  Unfortunately, I have gotten busy with other projects, so I am probably not going to do further development on this device nor finish the PCB layout, unless there is a large amount of interest. However, feel free to adapt it as you wish for your own CAN bus projects. Do bear in mind, however, that the design is licensed via the GPL, so if you use it for a commercial project, you must openly share your design.

Previous: AVR CAN Bus Project – Step 3: CANspy CAN Bus Monitor
Next: LeafCAN v1.1 Released

AVR CAN Bus Project – Step 3: CANspy CAN Bus Monitor

Sorry for the delay in posting the circuit and schematics from my AVR CAN Bus Project – Status Update 1.  The circuit for interfacing the Olimex AT90CAN128 Header Board is incredibly simple, and only requires 3 components.

Parts List
(1) .1uF ceramic capacitor
(1) 10K resistor
(1) Microchip MCP2551 CAN transceiver


If you’re going to connect it to a Nissan Leaf, the car has 3 different CAN buses accessible via the OBD-II connector. The pinouts can be found on MyNissanLeaf.com in this thread: Leaf CANbus Decoding (Open Discussion)

To communicate with the AT90CAN128 header board from my PC, I connected a USB to serial converter to USART0: TXD0 (pin 3) and RXD0 (pin 2).

Arduino Sketch

Below is my CANSpy sketch for monitoring the CAN bus via the serial port, as depicted in my Status Update 1.

Download: CANspy.zip

To compile the sketch, follow the instructions in AVR CAN Bus Project – Step 1: Programming AT90CAN128 with Arduino.

In my next update, I’ll show how to implement a SOC (State of Charge) meter for the Leaf using a LCD display.
Previous: AVR CAN Bus Project – Status Update 1
Next: AVR CAN Bus Project: Step 4 – Nissan Leaf SOC Meter

AVR CAN Bus Project – Status Update 1

I got the circuit wired up yesterday:

The 6-pin jumper on the left lets me select one of the 3 CAN buses on the Nissan Leaf accessible via the OBD-II connector.

I hacked up some code quickly, and was pleasantly surprised that it actually worked! Woohoo! The part I thought was going to be most difficult – getting the CAN interface firmware working – turned out to be the easiest. Here’s my first capture of live data from the EV CAN bus:

Schematic and source code will follow.

Previous: AVR CAN Bus Project – Step 2: Programming Low Fuse
Next: AVR CAN Bus Project – Step 3: CANSpy CAN Bus Monitor

AVR CAN Bus Project – Step 2: Programming Low Fuse

One of the basic functions that the CAN Bus project needs is to be able to communicate with a PC via a serial port.  For modern PC’s the most straightforward way is to connect the AT90CAN128 header board to the host via a Serial->USB converter.  The most common type is the ubiquitous FTDI Cable, which is a USB cable with an embedded FT232R chip inside. Since I have a couple of spare Arduinos, I like to just use the embedded FT232R in the Arduino, rather than investing in a FTDI cable.  To use an Arduino as a serial cable, simply remove the ATmega328P MCU, and then connect the the TxD, RxD, and GND pins between the Arduino and the external device.

The AT90CAN128 has two USART’s.  The first one, on pins RXD0(2) and TXD0(3), is accessed via the Serial object in Arduino.  The second one, on pins RXD1(27) and TXD1(28), is accessed via the Serial1 object in Arduino.

To test serial communications with the host PC, I connected the first USART to the Arduino board with MCU removed as follows:

AT90CAN128 RXD0 pin 2 -> Arduino Digital 0 (RX)
AT90CAN128 TXD0 pin 3 -> Arduino Digital 1 (TX)
AT90CAN128 GND pin 53 -> Arduino GND

Then I wrote a quick sketch to simply read characters from USART0 and echo them back to the PC:

void setup()

void loop()
while (Serial.available()) {
int c = Serial.read();

To instead test the 2nd USART, substitute RXD1 for RXD0, TXD1 for TXD0, and Serial1 for Serial.

After burning the sketch, I simply opened the Arduino Serial Monitor, and typed characters to test the connection.  Much to my chagrin, the AT90CAN128 was echoing garbage back to the host.  I spent hours trying various things, checking and rechecking my wiring, to no avail.  I started to suspect that maybe the at90can files I got from SuperCow were inproperly configured.  One thing that raised this suspicion is that I found that the delay() function was running much slower than it should.  User evnow of the MyNissanLeaf forum pointed me to a HEX file of a similar serial echo program that Olimex posted on their site for the AVR-CAN board.  I burned the file into the AT90CAN128 using avrdude:

avrdude -c usbtiny -p at90can128 -U flash:w:avr-can_UART.hex

Once again, the board was corrupting the serial data.  This test showed that the culprit probably wasn’t SuperCow’s at90can files, since this hex file has been tested and working by other users.

Finally, it dawned on me that perhaps the fuses weren’t properly programmed.  I got a crash course on fuses from Adafruit’s avrdude tutorial.  Adfruit’s tutorial also linked to a great AVR fuse calculator.  First, I read out the fuses to 3 files:

avrdude -c usbtiny -p at90can128 -U lfuse:r:lfuse:h
avrdude -c usbtiny -p at90can128 -U hfuse:r:hfuse:h
avrdude -c usbtiny -p at90can128 -U efuse:r:efuse:h

The 3 commands above read the low, high, and extended fuses respectively, and output them as text files lfuse, hfuse, and efuse.  I found that the values were lfuse=0x4f, hfuse=0x19, efuse=0xff.  Using the Embedded Atmel AVR Fuse Calculator, I noticed that when lfuse=0x4f, that CKDIV8 (Clock divide by 8)  is enabled.  This didn’t seem right, and might account for the fact that the delay() function seemed to be running about 8x too slow.  Not knowing much about fuses, I decided to just use the value that Arduino uses for the ATmega328P, lfuse=0xFF, which turns off CKDIV8.

avrdude -c usbtiny -p at90can128 -U lfuse:w:0xFF:m

Bingo!  No more corrupted serial data, and the delay() function now runs at normal speed.  I have a feeling I’ll have to play with the other fuse bits at a later date, but since the board is working OK I’ll leave them be for now.  If you want to copy all of my current fuse settings, use this command:

avrdude -c usbtiny -p at90can128 -U lfuse:w:0xFF:m -Uhfuse:w:0x1F:m -U efuse:w:0xFF:m

Previous:  AVR CAN Bus Project – Step 1: Programming AT90CAN128 with Arduino
Next: AVR CAN Bus Project – Status Update 1

AVR CAN Bus Project – Step 1: Programming AT90CAN128 with Arduino

Last month, I bought a Nissan Leaf EV.  It’s pretty cool driving around in an all-electric car.  Luckily, there’s a great forum called MyNissanLeaf, where Leaf owners can learn a lot, and share information.  I’m currently collaborating with one of the forum members to design and build a Level 2 EVSE.  I will document that project on this blog at a later date.  Having a serious case of project ADHD, I discovered that forum members had set about hacking the Leaf’s CAN buses, and couldn’t resist joining the fray.

Being most familiar with ATmel AVR microcontrollers and Arduino, I decided to use that platform for this project.  ATmel has a subtype of the AVR with CAN bus capabilities, the AT90CANxxx.  I found an interesting development board containing an AT90CAN128 and headers for access to all the pins on the MCU.  I ordered one from Sparkfun for $29.95.  They also sell another board, the AVR-CAN, but it contains things that I don’t need, such as an RS-232 interface, and can be programmed only via JTAG – I only have a USBtinyISP, which is an ICSP programmer.  Unlike the AVR-CAN, the AT90CAN128 Header Board doesn’t contain a CAN Bus transceiver.  I decided to go with the Microchip MCP2551, since that’s what the AVR-CAN uses.

The AT90CAN128 header board is from Olimex, and comes in a cute little box:

Here’s a closeup of the front:

and the back:

I decided to try to get this board working with Arduino, since it’s a lot easier to set up than WinAVR.  The first problem to solve is how to adapt the Arduino IDE to work with the AT90CAN128 and my USBtinyISP.  After much Googling, I found SuperCow had already done the dirty work and posted it to the Arduino forum.  He packaged the core files, bootloader, and a couple of examples into a handy zip file (which has since been taken offline). Since he used an unknown JTAG programmer, I had to adapt his files to work with the USBtinyISP and JTAG ICE mk1.  Also, I modified them to work with Arduino 1.x+.

You can download the latest version from github: https://github.com/lincomatic/AT90CAN  To install it, simply unzip the atcan90 directory into <your arduino directory>/hardware/at90can.  Next time you restart Arduino, you can select it from Tools->Board->[usbtinyisp]AT90CAN128.

If you have a JTAG ICE mk1 programmer instead, select [JTAG ICE mk1]AT90CAN128.

I connected up my USBtinyISP via the 10-pin ICSP header, burned the Blink sketch, hooked up an LED, and bingo!  It’s working flawlessly.

In at90can/cores/at90can, I found can_lib.h and can_lib.cpp, which appear to be all we need to interface to the CAN bus.  Since I currently know ZERO about CAN bus, I have a lot of reading to do before I can commence programming.  SuperCow’s original zip file contains a couple of rudimentary examples.

Before I start programming, I need to build a little interface board containing the MCP2551 CAN bus transceiver, which should arrive next week.  I already have an OBD-II cable to tap into the Leaf CAN bus via the OBD-II connector.  Currently, obdcables.com is having a special on the 9-ft model.


Downloads:  https://github.com/lincomatic/AT90CAN

Next: AVR CAN Bus Project – Step 2: Programming Low Fuse




Arduino-lite – A Lightweight Runtime for AVR

I just ran across Arduino-lite, a lightweight alternative runtime to Arduino, for programming AVR MCU’s.  This project is spearheaded by Robopeak Project.  It looks pretty cool.  It’s kind of halfway between Arduino, and coding directly with avr-gcc.  It supports the standard Arduinos, as well as:

  • Atmega8(A)
  • Atmega168(PA)
  • Atmega328(PA)
  • Atmega1280
  • Attiny2313
  • Attiny26
  • Atmega48(PA)
  • Atmega88(PA)

Not only does it support more MCU’s than Arduino, it also supports frequencies from 1-20MHz, unlike Arduino, which only supports 8 & 16MHz.

Furthermore, Robopeak claims that Arduino-lite’s binaries are 50% smaller than those produced by Arduino. An example on Robopeak’s Blog shows how Arduino-lite reduces the digitalWrite() function down to 1 AVR instruction.  It appears to make heavy use of macros, which is nice, because it eliminates function call overhead.  On the other hand, type checking and such is severely restricted.  I think it might be a great tool for projects that need to be compact, or run as fast as possible.  Also, it will greatly simplify coding for the ATtiny MCU’s.

It’s definitely not for n00bs, but if you’re comfortable with makefiles, give it a shot.  The download includes everything you need to get started.  You can download it for free from google code.

I just downloaded it, and am going to give it a whirl.  It almost sounds too good to be true.  If you have any experience with it, please leave a comment.

Download Arduino-lite: http://code.google.com/p/arduino-lite/

Lampduino – an 8×8 RGB Matrix Floor Lamp

This past weekend, I finally finished building my 8×8 RGB matrix floor lamp.  I call it Lampduino.  A Processing sketch running on a host computer controls Lampduino via a USB connection.  When turned on without a computer, it automatically displays a soothing plasma simulation. If you want to build one of your own, I wrote a step by step Instructable:

Lampduino – an 8×8 RGB Matrix Floor Lamp

Space Invaders


Related articles:

Reducing Arduino/FTDI FT232R Serial Latency

I’m working on a project in which a PC communicates with an Arduino (a Colorduino, to be exact) over a serial connection. It’s an 8×8 RGB LED matrix, which will be controlled by music. The ATmega168 MCU in my beta Colorduino has such small RAM that I can only buffer at most 2 screenfuls of data, even when I reduce the color resolution from 24-bits per pixel to 12-bits per pixel. I need to send the data down to the Colorduino very quickly. There needs to be very little latency, or the lights will lag the beats of the music. The serial communication speed is not much of a problem. Each data packet I’m sending is 100 bytes, so at . Besides the raw speed of communication, there is a built-in latency, due to buffering being done by the communications drivers. Luckily, FTDI’s Windows drivers provide a way to tune down the latency a bit.

Start the Windows Device Manager while your FTDI USB->Serial cable or Arduino Duemilanove is attached.  Look for its corresponding USB Serial Port under Ports (COM and LPT).

Right click on it, and select Properties from the popup menu.  Next, click the Port Settings tab, and click the Advanced… button.

In the dialog which pops up, lower the Latency Timer (msec) value from its default of 16 down to 1, and click OK.

After you disconnect/reconnect your device, the new Latency Timer value will take effect.

I am not sure if there are similar settings in OSX or Linux.  Hopefully, someone can dig up a similar IOCTL to achieve the same effect.

8×8 RGB LED Matrix Construction: Step 2 – Wiring

The first step in wiring up the matrix is deciding on the method.  I immediately ruled out soldering, because it’s messy, slow, and smelly.  Also, it incurs the risk of overheating the LED’s as well as being hard to repair.  I also ruled out using crimp-on connectors due to expense.  After pondering it for a while, I decided that wire wrap would be the best approach for several reasons:

  1. it’s cheap
  2. there are no toxic fumes
  3. there is no risk of overheating and destroying LED’s
  4. it’s easy to undo, so repairs are easier
  5. it’s relatively quick to do
  6. it’s as reliable as soldering – perhaps more reliable, since there’s no risk of cold-soldered joints
  7. the wire is so thin that it can be threaded into the gaps between the foam matrix pieces

The downside is the small wire gauge – 30AWG.   I was afraid that it might too small, so I consulted some tables on the Internet, I found that it has a resistance of 105.2 Ω/1000 ft. I estimated an upper bound of 4 ft of wire, so that’s ~.4Ω – probably insignificant for this application.  Next, I found that the current carrying ability (Ampacity) is estimated at .144A by most tables, but one actually had it listed at .86A.  The LED’s I’m using run at a maximum of 20mA per color.  In a column, a maximum of 1 LED at a time is lit, so it’s definitely in spec.  On the other hand, if a whole row is driven w/ the with all 3 colors lit, we can end up with 8 x 3 x 20mA = 480mA.  This is way over the .144A spec, but below the .86A spec.  I decided to just try it, and if I encountered problems, I would put multiple wires in parallel for the rows.

I already had a wire wrapping tool, which ,I bought many many years ago (ouch,they seem to have gotten expensive over the past 30 years! I think I spent $5 on mine), so all I needed was some wire.  Radio Shack carries 50 ft spools of red, white, and blue 30AWG kynar-insulated wire for 3.99 a roll (note:  the price seems to have increased to $4.19 in the 2 weeks since I bought mine).  I bought one roll of each.

I started out wiring each color in sequence along an 8-LED chain, but later found that it’s more orderly to wrap the 3 wires (R/G/B) between each pair of LED’s at a time.  When I wrapped my first strand of 8 LED’s I didn’t pay attention to the orientation of the leads.  This made a mess.  It’s better if you orient the leads in the same direction as you wrap each chain (e.g. red pin to the left), rather than just doing it haphazardly.  This way, the wires don’t criss-cross each other as much.  After much experimenting, I found that a 4″ length of wire between each pair of LED’s was optimal for my 2″ ID matrix.  This left enough slack between the successive LED’s to work with.

I’m using common anode 5mm diffused RGB LED’s bought on eBay from a Chinese vendor… $25 for 100.  Not particularly cheap as eBay goes, but they use free  trackable EMS shipping, which takes about half the time as regular HK post.  The vendor sent me common cathode LED’s by mistake, so I had to wait for him to send me another batch w/ the right polarity.  The pins go from left to right in the photo, B-G-Anode-R.  The anode lead is longer, which makes it easier to identify.  Note that since the anode is for the rows, while the other R/G/B leads are for the columns, I didn’t wire it yet at this stage.  Here are the completed strands:

Since the LED’s will be face downwards in my matrix, my idea was to fasten them by simply poking the wires through the cardboard/foam sandwich.  I found that the paper was a bit too thick to do this easily, so I had to cut slots into the matrix pieces to receive each LED.  Be sure to do this before you thread the 8 LED strands into your matrix!

It’s hard to see the slits in the photo above.  Here is a close-up:

Make sure that you cut all the way through the foam sandwich.

After completing the 8 chains of 8 LED’s, the next step was to thread them into my matrix.  The wire wrapping wire is very thin, and easily fits into the interlocking slots of the matrix.

To wire up the rows, you need to flip over the matrix, so that you can wire and thread the row wires perpendicularly to the columns.

This step requires a bit more dexterity, because you have to work with the LED’s inside the matrix.  Thankfully, there are only 8 rows (as opposed to our 24 (8×3) columns, so there are a lot less wires to deal with.   In the photo above, notice how the I’ve flipped the matrix.  The RGB wires are threaded through the bottom slots, while the yellow anode wires are threaded perpendicularly, through the top slots.  Also, note how I’ve secured the LED by jamming it into the slot that I cut.  The gaps among the 4 leads on each individual LED are rather narrow, so it’s a good idea to spread the leads apart before plugging them into the matrix, to avoid shorts.  You might be wondering why I have the LED’s pointing sideways instead of straight up. This is because I am building a matrix which will stand up vertically, so that the light will come out both sides.  Also, in my previous experiments with LED orientation, I found that the colors didn’t mix very well when the LED’s were pointed directly at the viewer.As you can see, this setup made it considerably more difficult and time consuming to build than if I had wired them pointing upwards on a single sheet of poster board.

Here is how I routed the column wires:

Finally, I wire-wrapped all the leads onto a pair of 16-pin male headers.  The pin groups are conveniently labeled on the Colorduino, so it’s easy to figure out which wires go where.

Even so, I managed to reverse all of the green wires; since I used wire-wrap, it was easy to undo them and hook them up in the correct order.  It’s a good idea to manually test all of the connections before plugging them into the Colorduino.  I used a 5V supply with a 100Ω resistor and test clips to check each individual LED.  Amazingly, I didn’t have any shorts.  After testing was completed, I used small blobs of hot glue to secure each LED, and in each interlocking corner of the matrix.

When I finally powered it up via my USBtinyISP, I found that my PC couldn’t communicate properly with the Colorduino.  The LED’s were drawing more current than the USBtinyISP could output.  Hooking the Colorduino up to my 5V 1A supply fixed that.

Here’s what it looks like with drafting film laid on top, and all the lights set to maximum brightness:

One very disappointing discovery is that I won’t be able to properly set the white balance on this matrix.  Note the wide range of color variation among the LED’s.  I guess the quality control is not so good when you buy cheap LED’s on eBay.  I had the same problem even with the white LED’s that I used in my 5×5 monochrome matrix.  Also, I don’t understand why the LED’s are making bright dots, since I was getting better diffusion in my initial experiments.  The LED’s I used in the experiments should have been very similar.. they were from the same vendor, but were the common cathode ones that he sent me by mistake.  I guess the new LED’s I received are not as diffuse as the last set he sent me.

Another discovery I made while testing is that the orientation of my wiring is wrong.  I had wanted the wiring to be routed such that the Colorduino would be on the bottom.  In fact, the Colorduino is positioned on the side.  Therefore, I’m going to have to swap the rows and columns in software – an easy fix.  I ran the matrix full brightness for a while, and the row wires aren’t melting or heating up, so the thankfully, the current carrying ability of the row wires is OK.

The wiring task was a grueling and tedious task.  I spent a total of about 16 hours spread across 4 days doing it.  Thank goodness for TV, or I would have gone insane.  Needless to say, I’m all caught up with the recordings on my DVR!  My hands ache, my back aches, my joints ache!  One annoying thing about 30AWG wire is that it’s so thin that it’s hard to get a grip on it, and when it falls on the floor, it’s hard to pinch it between your fingers to pick it up.  Wiring up the matrix required 256 wires (8x8x4), each wire needed to be stripped and wrapped on both ends… 512 joints to wrap!!  I really felt like I was losing my mind, and that I was going to go blind.  It has to have been the most tedious task I’ve ever completed!

The next step will be finishing up the matrix assembly.  I still haven’t gotten the outer frame onto it.

Related articles:

8×8 RGB LED Matrix Construction: Step 1 – Cutting Foam Board

I started building my 8×8 RGB LED matrix this weekend. The first step was mechanical construction of the matrix. Below are the materials I used:

I recycled a piece of foam core poster board. This kind of poster board is composed of two sheets of thick paper, with a piece of foam sandwiched in between. You should be able to find it in an office or art supply store. The dimensions of the board were 45x30x1/4″. The tools needed were just a straight-edge, a ruler, and an x-acto knife. During the course of cutting it, I wore out two blades, so you might want to keep some spares handy.

The first step was measuring and drawing out the cutting lines on the board in pencil. After my previous adventures in RGB LED Testing, I’d settled on an inside dimension of 2×2″ for each cell. Since the matrix is composed of 8×8 cells, I needed to cut 14 identical grid pieces. I tried to take a photo of the entire sheet after drawing in all the guide lines, but the lines didn’t show up clearly. Below is a close-up instead:

I found that it’s easiest to lay out the cuts so that the grooves on each adjacent pair of grid pieces are facing each other. This way, you can cut 2 slots at once. I first cut the slots, and then I cut out the grids:

Note that you need to use extremely sharp blades when cutting foam-core poster board. Once your blade begins to dull, it won’t cut through the foam smoothly, and instead, it makes it turn into nasty little chunks as the blade drags through. If your blade starts to dull, change to a new one. Also, make sure to avoid putting excessive pressure on the board with your elbows, knees, etc … once the foam compresses, it won’t bounce back. I spent about 5 hours total cutting out the 14 pieces below:

It was a tedious and boring task. Lucky I had a TV set in the room. When it was done, my arms, fingers, and back were all so sore, I had to pop 400mg of ibuprofen! Below are the fruits of my labor:

I bought a can of white gloss spray paint to paint over all of the printed bits, so unlike the photo above, the final product looks entirely white. In retrospect, I’m not sure it was worth using recycled board, because of the labor and cost of the paint. I’m not 100% sure that it was really necessary to paint it white – maybe the dark bits wouldn’t cause reduced brightness – but I didn’t want to take a risk … it would be hard to paint after wiring up the LED’s.

The next step is wiring up the 64 RGB LED’s … 4-wires each means a total of … 256 wires – 512 connections! Another long and grueling task!

Related articles: