Announcing a new OCaml library for the Adafruit Raspberry Pi RGB LCD!
- December 29, 2013
For still-to-be-determined reasons, the fine geeks at Gallium suddenly decided to acquire Raspberry Pis. Some of the geekier elements in the lab also decided to raise the nerdyness level and get a kit LCD plate with a keypad.
After the delivery guy arrived, Damien provided us with a professional soldering iron and, behold! we’re soldering our LCD plates like it’s junior high and we’re in “cours de techno”. (A discipline which involved soldering basic circuits, using Thomson MO-5s and DOS 1.0 to print on needle printers, and learning to write accounting reports on MS-Works 1.0, that was back in 2001. Time flies.)
Anyhow, after soldering (without failing!) 113 wires, we managed to hook up the LCD to the Raspberry Pis without frying the device, and we were ready to try out the i2c communication protocol with the LCD using… the sample code in Python.
Yes, Python.
At Gallium, we’re not interested in compromise. We want the real stuff. We rewrote the LCD library in OCaml.
This required:
- reading the documentation for the port expander
- reading the documentation for the Hitachi HD44780 LCD protocol
- reverse-engineering the original code which was, somehow, cryptic.
After that, we:
- used ocaml-ctypes to perform the right ioctls, using not-so-subtle
calls to
Obj.magic
to expose the file descriptor hidden underUnix.file_descr
, - watched in awe a variadic function being called properly via ctypes (after checking with Xavier I-know-all-ABIs-because-I’ve-written-so-many-backends Leroy, this works for the ARM ABI as long as we don’t use floats),
- read cryptic documentations on smbus-protocol
and dev-interface
to understand where to find the
smbus_*
functions, - failed to understand that i2c-dev.h was to be found in the source of the i2c-tools, and that it is not installed by i2c-tools, even though /usr/include/i2c-dev.h exists,
- learned to compile i2c-dev.h as a shared library on linux (gcc -shared -fPIC),
- cried because of a bug in ctypes
- re-read the cryptic documentation and rewrote the whole thing to no
longer use the
smbus_*
functions but direct read/writes on the /dev/i2c file descriptors.
Having put all of these elements in place, we spent several nights trying to design a good library. We dropped some things from the original python library, rewrote some parts to be (in our humble opinion) clearer, added data types to clarify stuff.
The result is a neat library that’s available online at https://github.com/protz/ocaml-adafruit-lcd (not yet in OPAM, I’ll do that shortly once the dust settles). There’s even a demo program that will draw a camel on your LCD!
PS: the Hitachi LCD protocol says to check the busy flag, which I diligently do, however, I’ve never seen a busy flag ever being 1 ever in my testing. If any electronics geeks are out there, I’d love for them to check my code!