Monday, April 12, 2010

Accessing an Arduino from Erlang

(2013-01-08: There is a native Erlang interface to Unix serial ports here: srly. See the readme for the API. It should work on Mac OS X, BSD and Linux.
And, if you want to load code to the Arduino directly from Erlang, try this: stk500)

First we'll need to upload a sketch to the Arduino. There are many examples floating around. Here is a simple one to control LED's. Yes, not exactly novel.

You will need to modify the definitions of FPIN and LPIN to match the first and last digital pins the LED's are plugged into. Compile and upload the sketch.

The lights are set as a bitmask. For example, to activate the first LED, send the integer 1; for the third LED, send 4; and for both the first and third LED, send 5. If you defined the DEBUG macro, you can test from the serial monitor by sending the ASCII representation of the numbers.

Now download and compile the erlang-serial port driver. Start up Erlang:
1> Pid = serial:start([{open, "/dev/ttyUSB0"}, {speed, 9600}]).
2> Pid ! {send, 1 bsl 2}. % LED at position 3

Doing Something Useful

Switching LED's on and off programmatically is hours of fun. But, like many others have discovered before, hook it up to a monitoring system and it becomes sort of useful.

I have a monitoring service running Nagios. Yeah, I think Nagios sucks too. The Erlang code does a request for the tactical overview page, parses out the statistics and sets the alert status accordingly.

Monitoring Ambient Light

Here is another simple project: creating a graph of ambient light levels using an LDR and the really quite awesome eplot library.

Connect the LDR to an analog pin and upload a sketch: The Erlang code has 2 components: a process that periodically reads and stores the sensor data and a web server that displays a graph in PNG format.
Reading the sensor:

Displaying the graph:

After the web server is running, the web page can be found by going to:

(I think the spikiness was caused by a blinking LED somewhere around the LDR).

1 comment: