Saturday, May 30, 2009

how to set a serial port at MIDI speed in linux

Linux serial ports only work at standard speeds by default. MIDI runs at 31250 baud, which is not a standard speed. However there are tricks to get custom speeds, but documentation is quite fuzzy. This is a simple recipe that worked for me with an FT232 USB-Serial board.

Check the baud base of the device:

$ setserial -g -a /dev/ttyUSB0
/dev/ttyUSB0, Line 0, UART: unknown, Port: 0x0000, IRQ: 0
        Baud_base: 24000000, close_delay: 0, divisor: 0
        closing_wait: infinite
        Flags: spd_normal low_latency

As you can see the baud base is 24000000 here.
Next calculate the divisor by dividing the baud_base you see here by the speed you want.
In my case 24000000/31250=768.

Apply the new setting:

$ setserial -v /dev/ttyUSB0 spd_cust divisor 768

Next start your serial application, you might want to make sure it is already set to the correct speed before you do the above changes else it might destroy your settings. The correct speed is 38400 baud, which is now aliased to 31250.

With minicom just use the menu (CTRL-A Z) to change the settings.

Screen can be used like this:

screen /dev/ttyUSB0 38400

Exit screen by pressing CTRL-A CTRL-\



Tommy said...

In the "good old days", baud base used to be 115200. So there was no way to divide that into 31250 - instead you had to change the crystal to a different frequency. This would screw up the calculation, but with most MIDI software running under DOS, that was easy fixed by poking a few hex bytes in the right place...
Fun it was.

desNotes said...

I am looking to learn more about connecting & configuring serial devices. Do you know where I can get the basics? I want to be able to connect via USB and receive data. Can you point me in the right direction?
desNotes AT gmail DOT com

Joost Yervante Damad said...

I recommend the book "Making things talk" to learn the basics about serial communication and hooking things up.