Archive for the ‘Virtual world’ Category

Geek Sunday

Imagine that it’s a Sunday morning, and you are pretty bored and want to do something relaxing and a little bit of fun. Imagine that you talked about LEDs and Arduinos with a colleague two days before, and so you have checked your electronics storage and know perfectly how many LEDs you still have (too many, I can assure you). Why not do something fun with them? For example, LEDs that play along a MIDI track 🙂

So, what I did was:

  1. find out a nice MIDI track, a not too complex one if possible; I decided for “Twenty One” by Jessica Curry, from the “Dear Esther” soundtrack: I love that theme, and it’s basically a single instrument (a piano). I already had a MIDI version of it, which I simplified a little bit (I basically removed the counter-theme)
  2. find out how many 220 Ω resistors you have (turns out: about 40, that go along perfectly with the 36+ red LEDs that I had)
  3. find out how many shift registers (the famous 595 IC) you have: not so many, unfortunately. I only had 3, so I can pilot up to 24 LEDs, or 2 octaves. I would have preferred 3 octaves…

I put together the circuit (I tried to resemble a piano keyboard, with two rows of “keys”; if I had more LEDs of a different color, the result would have been better. Also, I didn’t want to solder anything, so the positioning on the breadboard cannot be as precise as one would like. I also needed two more LEDs, that I had to switch on and off from the Arduino side without the 595) and the code: it uses the MIDI library to receive the “note on/off” messages from the serial line (you can see the RX LED switching on the Arduino in the video), and it switches the LEDs according to the pitches that it receives. Since I only had 2 octaves, I had to transpose the theme one octave down, and since the MIDI file had 3 tracks but I had just one line of LEDs, I had to prioritize the tracks: basically, if the same note is played by two tracks, the track with the highest priority would decide when to stop the note. I achieved this by reordering the tracks in the MIDI file, so that the ones with a highest channel number have a highest priority.

The last step from the Arduino point of view was install the dear old Hiduino firmware: basically it allows the Arduino to be recognized as a MIDI device, instead of a serial device, so that it can communicate with multimedia apps on the computer side. Of course, once you rewrite the firmware, you need to upload the sketches from the ISP header.

Finally, I fired up Jack (the low latency audio daemon), Rosegarden (to reproduce the MIDI file) and KMidiMon (to monitor the MIDI events), I connected the Arduino to the computer, routed the MIDI lines to all the “clients”, and voilà!

This slideshow requires JavaScript.

P.S.: nevermind the names of some of the variables in the code: they come from previous experiments with the 595s, and I haven’t changed them due to laziness…

Read Full Post »

Era da parecchio che non scrivevo più un post tecnico, e forse nemmeno questo sarà così tecnico, quanto più una rapida riflessione.

Nel paio di settimane di ripresa del lavoro dopo le vacanze estive, ho avuto occasione/necessità di scrivere un paio di utility da usare su un paio di sistemi embedded, essenzialmente per scaricare dati usando un po’ di protocolli (modbus, messaggistica di TinyOS). La scelta del linguaggio un po’ di tempo fa sarebbe ricaduta su un banale Java, ora invece è ricaduta su Scala.

Premessa: tendo a non prendere in considerazione linguaggi di scripting per cose che non siano uno script scritto al volo e da usare due volte in croce; questo perchè, per quanto apprezzi linguaggi come Python quando serve,

  1. la struttura del programma tende a degenerare rapidamente: se non sei costretto dal linguaggio a mantenere un minimo di struttura, e non hai tanto tempo da perdere (una delle utility è stata scritta in una giornata, per poterla testare sul campo il giorno successivo), non fai nulla per dare almeno quel minimo di struttura
  2. se il linguaggio non è compilato, tendo ad evitarlo: il lavorare solo a runtime ti costringe ad intercettare la classica quantità di ca***tine solo eseguendo il programma n volte, mentre se compili quegli stessi problemi li risolvi molto prima (se penso a tutte le volte in cui ti accorgi di aver sbagliato la ricezione di un messaggio in Erlang per aver invertito due parametri in una tupla…).

Dicevo: la scelta ormai ricade su Scala, dato che:

  • ha un build system tutto sommato decente (per quanto sotto ci sia Ivy ed i repository di Maven): salvo trovare incompatibilità tra versioni di Scala e versioni di libreria, funziona abbastanza bene e si configura con un semplice file di testo
  • ha il sistema di classi e quant’altro di Java
  • è compatibile con Java (fondamentale: per modbus avevo già testato tempo fa una libreria che funzionava sui miei apparecchi, e TinyOS ha una versione Java delle sue librerie)
  • è (anche) funzionale: se un linguaggio non mi supporta lambda, liste ed il trittico filter/map/fold, per quanto mi riguarda è un linguaggio che non considero
  • posso scegliere quando fare le cose immutabili e quando no (quest’ultima cosa praticamente mai, dato che la mutabilità è il male, ma in alcuni sporadici casi è un male necessario).

Tutto qui 🙂 a breve penso di scrivere un post un po’ più tecnico su un altro progetto più a lungo termine, fatto sempre in Scala, con cui ho potuto sperimentare con un po’ di tecnologie divertenti (tra cui Akka, Play e RabbitMQ).

Read Full Post »

Remember when we played Tomb Raider @ 640×480 with enormous pixels?

2014-06-22_00002 2014-06-22_00004 2014-06-22_00009

P.S.: yeah, I know, not really news, but for the first time since the ’90s I have a decent graphics card!

Read Full Post »

$ uptime
14:27:19 up 566 days, 23:34, 4 users, load average: 0.29, 0.57, 0.74

Read Full Post »

Akka actors

I’ve been following the Coursera course titled “Principles of Reactive Programming” (link), which is almost over (next week will be the last one), and in the last two lessons we learnt how the Akka implementation of actors works.

Now, since in the last four years I have developed code using Erlang for my Ph.D. thesis (and for other secondary projects in between), I am quite used to the actors principles and architecture, but it has been quite interesting to look at them in a different implementation, and I wanted to write a couple of paragraphs on the differences with respect to Erlang, and my (brief) opinion on these differences (beside the fact that Scala is statically typed, which is huuuuuge):

  • Akka actors take TONS of syntax from Erlang, in particular: BANG! 🙂
  • seeing the messages in Scala as case classes instead of tuples is very very strange at the beginning, and it is even stranger when you assign a message to a variable: it looks like you are calling a function…
  • Akka actors have automatic supervision: processes are automatically linked (to use Erlang terminology) to their parents, and a father kills all its children by default when he dies; then you can add specifications on the supervision behavior and tune it better, and as in Erlang you need to explicitly handle the termination messages when needed. Now, this is a characteristic that I am not really sure I really like: I mean, I prefer to decide if I want to spawn a linked process or not, and to decide if I want a process to be supervised or to live by itself. Maybe this is due to the fact that in Erlang supervision works basically when you are using predefined behaviors, while here it works for everyone… I don’t know, I have to try it a little bit more to decide on this
  • the receive primitive does not fail if there is no match to a message: this is an improvement on one side, because you can freely ignore some messages that arrive to a process (they are still consumed, see below), but on the other hand you need to remember to implement the function that receives the non-matched messages in your actors, otherwise they will go to the event stream (more on this later), while in Erlang you typically write a case to catch everything else in the end of each receive block, where you log the unforeseen message. Again, mixed feelings: you need to remember stuff, but at the same time you can separate unknown messages and the reaction to them in different blocks of code, which is not bad.
  • Akka actors have the concept of context, which basically allows you to change state from time to time and create a sort-of finite state machine for actors behavior; this means that you can divide messages belonging to different phases of the actor in different blocks of code, which helps maintaining everything clearer. I really like this feature.
  • Akka has an internal pub-sub system, where actors can publish messages (using topics) and subscribe to topics; this is also the place where everything not catched goes (it is called event stream). It is an interesting concept, and I can imagine it can be quite useful (logging is the first thing that comes to mind).
  • Finally, Akka gives developers the possibility of persisting state: I don’t know this characteristic that well, essentially because I have not used it yet (only seen on slides), but it looks interesting and helps overriding the single assignment vs actors with a state…

All in all, I have to say that I like Akka actors, even if I have mixed feelings on a couple of characteristics (especially the automatic supervision, I still have to fully digest it…). Anyway, this is another reason that convinces me that if I had to start a new project from scratch today, I would use Scala for sure.

Read Full Post »

A few weeks ago I ported the Firmata library to Lua, as a first step of an experiment of a DIY Arduino Yun. For several reasons I had to postpone that experiment (reasons being writing my Ph.D. thesis, and the fact that the Carambola board has the wrong pin distance to do anything good with it), and now I have an Arduino Yun, which essentially is a Carambola done well (and I couldn’t expect less by the Arduino people).

So, the next step is to run my Erlang framework, ELIoT, on it (the fact that the Yun has double the internal flash memory of the Carambola and support for external SD cards is simply great), and to interact with the microcontroller (the usual Atmega 32u4) I needed a porting of Firmata to Erlang. The Yun team gives you a Python library for intercommunication, but since it is not C/C++ I couldn’t make a wrapper to an Erlang driver, so I decided to go (Erlang) native.

Thus, meet the library: as before, it is a simple port of the Java Processing one, meaning that it supports only analog and digital write/read operations, among the other operations of Firmata. I have tested it on the Arduino Yun: the Atmega 32u4 was running the Standard Firmata sketch, and a computer was running Erlang and the library (I still have to install Erlang on the Yun microprocessor itself), and it works, at least with the usual simple test of enabling the integrated LED and read from one of the analog sensors.

The library itself is structured as a gen_server: just one instance each time, of course.

*** UPDATE ***

Now the library works in both push and pull modes: a client can query the server to obtain the current values of sensors, or it can receive the updates directly from the server by subscribing to a specific (analog or digital) pin.

Beware that the latter will generate a new update message for each Firmata update from the Arduino (for example, the StandardFirmata sketch running on my Yun produces about 50 messages per second, one update every 20 ms). You may need to filter these messages, e.g., taking action when a certain threshold between consecutive values is exceeded.

Read Full Post »

Arduino in a box

Arduino in a box

Un paio di righe per descrivere brevemente un esperimento preparato stamattina con Arduino ed un paio di accessori.

Il problema è il seguente: capita di andare via di casa per diversi giorni (ad esempio a Natale o ad agosto), per vacanza o per altri motivi; al vostro ritorno, potreste domandarvi se è mancata o meno la corrente, e di conseguenza se quanto avevate lasciato in frigorifero o in freezer è ancora commestibile. Nel mio caso, so se è mancata perchè la sveglia del comodino lampeggia, ma non ho idea del tempo in cui sia effettivamente mancata.

Da qui, l’idea di mettere assieme un Arduino, un RTC ed uno shield con SD, per scoprire effettivamente se e per quanto tempo sia mancata la corrente quando non sono in casa. Il codice sotto riportato scrive su un file una riga di timestamp ogni 5 minuti (sfruttando l’interrupt che l’RTC lancia una volta al minuto): se la corrente viene tolta, l’Arduino si spegne e smette di scrivere su file, salvo poi riprendere al ripristino dell’alimentazione, e l’RTC avrà mantenuto nel frattempo l’orario (essendo alimentato a batteria), ed una semplice analisi del contenuto del file permetterà di scoprire l’intervallo di tempo in cui non sono stati scritti timestamp.

Non do rassicurazioni sul codice sotto riportato: test brevi hanno funzionato, ma sto ancora svolgendo un test prolungato nel tempo. L’unica particolarità del codice è che sia l’RTC che la SD comunicano attraverso SPI, utilizzando due modalità diverse (MODE3 vs. MODE0), quindi bisogna alternare le due prima di usare l’uno o l’altro dispositivo. La libreria per RTC serve solamente a semplificare la scrittura nei registri, mentre la libreria Time serve per tradurre una data ed ora in UNIX timestamp.

I collegamenti hardware dell’RTC sono molto semplici e vanno sulle connessioni standard SPI dell’Arduino Uno (CS è 10, dato che lo shield SD ha CS sul pin 8); l’uscita SQW dell’interrupt del DS3234 va al pin 2, che corrisponde ad interrupt zero per l’Arduino Uno.

#include <SPI.h>
#include <ds3234.h>
#include <SD.h>
#include <Time.h>

#define RTC_CS 10
#define SD_CS 8
#define RTC_INT 2
#define MINUTES 5
#define FNAME "logger.txt"

int time_interrupt = MINUTES;
File logger;

void setup()
  pinMode(RTC_INT, INPUT);
  pinMode(SD_CS, OUTPUT);
  DS3234_init(RTC_CS, DS3234_INTCN);
  attachInterrupt(0, INT0_ISR, LOW);
  Serial.println("Waiting for first alarm...");

void loop()
  struct ts t;
  tmElements_t t2;
  time_t time;

  if (time_interrupt == 0) {
    DS3234_get(RTC_CS, &t);
    t2.Second = t.sec;
    t2.Minute = t.min;
    t2.Hour = t.hour;
    t2.Wday = t.wday;
    t2.Day = t.mday;
    t2.Month = t.mon;
    t2.Year = t.year - 1970;
    time = makeTime(t2);
    logger = SD.open(FNAME, FILE_WRITE);
    if (logger) {
    time_interrupt = MINUTES;

void set_next_alarm(void)
  boolean flags[4] = { 1, 1, 1, 0 };
  DS3234_set_a2(RTC_CS, 0, 0, 0, flags);
  DS3234_set_creg(RTC_CS, DS3234_INTCN | DS3234_A2IE);

void INT0_ISR(void)
  attachInterrupt(0, INT0_ISR, LOW);

Read Full Post »

Older Posts »