Genericizing Arduino Libraries

When writing a library, pass in I2C ports to make the library more useful on different platforms.

My AVC 2016 vehicle used a handful of our SAMD21 Minis. It’s an amazing board because it’s got multiple serial ports and multiple I2C ports. But as I attached things like the HMC5883L to the SAMD21, I quickly realized that most libraries assume you will be using Wire.write(). What if I want to use a library, but with a different I2C port? You have to go into the library and modify quite a bit to get it to work. I want future library writers to avoid this so I decided to write a really simple example library to show readers how write libs that can accept different hardware ports.

I’m a hack when it comes to hardcore C so I learn by example. Bill Porter’s Easy Transfer Library from 2011 (!) saved the day and was the key to cracking this problem.

I wanted to create a simple-as-possible library example so if you’re creating your own library, consider this template as a starting point:

And here's what a bit of the library looks like. Because we've passed a reference (&wirePort) as an argument to the library we use arrows instead of dots to access the member functions.

Using an underscore in front of a variable name doesn't do anything magical it just makes it easier to understand which variables are private to the library. From David's Writing a Library for Arduino: "Adding an underscore to the start of the name is a common convention to make it clear which variables are private..." The _i2cPort variable can be accessed by various functions within Memory.cpp but not by the user's main sketch.

In the same vein, libraries that use Serial.print() won’t play nice with a board like the SAMD21 that can have three serial ports. So here’s a really simple example showing a library that allows a serial stream to be passed into it.

And the library:

Checkout the full files to see how to set up your header file and cpp.

Why should you care?

Imagine the day when we can use any board with any library and it just works. It’s coming fast; we just need to write the libraries as extensible as possible!

If you decide to write your own library, David wrote a great tutorial covering the basics so start there.

There are probably ways to make these templates even better. Please let me know if you know of any additional tricks.