Code and Life

Programming, electronics and other cool tech stuff

Supported by

Supported by Picotech

Using Raspberry Pi as an automatic MIDI logger

During my summer holidays I got an interesting idea: Pianoteq has a very nice feature of “always on MIDI logging” that saves everything you play on your keyboard while Pianoteq was on. I’ve previously made some MIDI projects and had a great idea:

How about building a small device that records everything I play on my piano, and save it as MIDI files?

This would enable me to later grab a good performance, and eliminate the “recording anxiety” I get if I know I’m recording and should definitely not do any mistakes during the next 1000+ notes. Furthermore, even with easy MIDI recording to USB stick, it’s still several manual steps plugging the memory stick in, starting recording, stopping it, lugging it to a computer, etc.

My first idea was to use some WLAN-enabled embedded device, but MIDI IN would require optoisolators and some custom electronics, and more modern digital pianos often come with only USB MIDI, so it could easily become an exercise in communication protocols. Fast forward a couple of minutes to my next revelation:

Raspberry Pi Model 0 W already has USB and WLAN, and it’s small. Why not use that?

Turns out using a RaspPi as fully automated MIDI logger is really easy. Read on for instructions!

Update: Also check out my follow-up post to split the recorded MIDI files automatically!

Recording MIDI with Raspbian

Turns out recording MIDI from a USB MIDI enabled device is really easy. When I plug in my Kawai CS-11 (sorry for the unsolicited link, I love my CS11 :) to the Pi (or just turn it on when it’s plugged in), dmesg shows that the Pi automatically notices the new MIDI device:

[ 587.887059] usb 1-1.5: new full-speed USB device number 4 using dwc_otg [ 588.022788] usb 1-1.5: New USB device found, idVendor=0f54, idProduct=0101 [ 588.022800] usb 1-1.5: New USB device strings: Mfr=0, Product=2, SerialNumber=0 [ 588.022807] usb 1-1.5: Product: USB-MIDI [ 588.074579] usbcore: registered new interface driver snd-usb-audio

Once the USB MIDI device is found, you can use arecordmidi -l to list available MIDI ports:

pi@raspberrypi:~ $ arecordmidi -l Port Client name Port name 14:0 Midi Through Midi Through Port-0 20:0 USB-MIDI USB-MIDI MIDI 1

Read post

Picoscope 2208B MSO Review

There are few tools that are essential for an electronics hobbyist. When I started, I had a soldering iron, a multimeter and some components, and that was about it. That got me quite far because you can do simple debugging even with a multimeter, but once you start to do any communications, you will either work in the dark or get a signal analyzer, oscilloscope, or both. I reached that point about 9 months into my hobby, and eventually decided to get an entry-level PicoScope from Picotech. You can read the whole story from my PicoScope 2204 review from four years ago.

Long story short, I was extremely happy with my Picoscope, and I’ve been using Picotech’s products ever since in various projects. In the past years, I’ve also been collaborating with Picotech, so I’ve had the chance to use also their higher end models, including the frighteningly powerful 4-channel, 200 MHz, 16 bit PicoScope 5444B, which is really great but maybe even too hefty for my use. So when I was offered the chance to try out Picotech’s latest generation of their entry-level 2000 series published just a month ago, I was immediately in.

Without further ado, let’s get reviewing!

PicoScope 2000 series overview

The new PicoScope 2000 series is divided into roughly two groups of equipment: The entry models 2204 and 2205 range in price from 139€ for the 10 MHz 2-channel 2204A to 419€ 2205A and 2405A which are 25 MHz and have MSO (mixed-signal oscilloscope, i.e. it has 16 channel digital part as well) capability and 4-channels, respectively. Don’t let the low bandwith confuse you, even these models have sampling rates ranging from 100 MS/s to 500 MS/s, so you will get quite a lot of measuring power out of them.

Biggest limitation with 2204 and 2205 models is the buffer size, which ranges from 8 kS to 48 kS, so for longer captures than a few waveforms, only option is the continuous capture over USB which worked at a steady rate of 1 MS/s the last time I used it. So you can do unlimited capturing of signals around 100 kHz, but above that it’s the normal oscilloscope triggering business — that’s the way scopes have always worked from their beginnings, so it gets the job done as well.

2204 2205 2206 2207 2208
Bandwith 10 MHz 20 MHz 50 MHz 70 MHz 100 MHz
Sample rate 100 MS/s 200 MS/s 500 MS/s 1000 MS/s 1000 MS/s
Resolution * 8 bit 8 bit 8 bit 8 bit 8 bit
Memory 8 kS 16 kS (48 kS w. MSO/4ch) 32 MS 64 MS 128 MS
Price (2015-22-05) 139 € 209 € 319 € 459 € 629 €
Options MSO or 4ch MSO or 4ch MSO or 4ch MSO or 4ch

*) Resolution for repeating signals can be increased to 12 bit with multiple samples

Read post

New Picotech 2208B Unboxing Video!

Picotech launched a new set of very compact but powerful 2000 series oscilloscopes just a few weeks ago, and with my long-term collaboration with them (they really rock :) they were kind enough to send me a unit for reviewing! The review will hopefully come quite soon, but meanwhile, enjoy this amazing unboxing video. And with “amazing”, I mean “I did not completely fail the lighting and achieved 90 % intelligible pronunciation”.

The unit in question is the high-spec 100 MHz 2208B with 16 channel logic analyzer unit built in. I knew that this replacement line to the old light blue 2000 series scopes was small, but I was still amazed by the compactness of this beast. Having had a top end 5000 series Picoscope for a few years, I’m seriously considering the “downgrade”, as I mostly use just one or two channels of the scope, and even those are in many cases digital signals. But I’ll return to this in the review later.

Let me know what you think, either here on in the Youtube comments section!

Read post

IR signal recorder with Arduino Uno

I’ve been tinkering with IR and the TSOP38238 IR receiver modules I got from Adafruit and Sparkfun. That’s right, plural, as I burned the first one — be REALLY sure not to mix ground and VCC with this one! I ordered 10 more from AliExpress just to make sure I have spares in case I burn my second one as well…

There are IR libraries for Arduino already, but they were a bit complex to my taste, as I’m first planning just to record one IR code from my bulky Sony projector remote and make a small trinket to send that on button press. The TSOP382 already demodulates the signal, so I just want to record the times the remote IR led is on, off, on, off, and so on. So I made an Arduino sketch to do just that: Count loop cycles, detect when signal goes from high (no IR signal detected) to low and vice versa:

Read post

BeagleBone Black GPIO Benchmark

Look what the mailman brought: It’s a shiny (or maybe matte?) BeagleBone Black, freshly arrived (actually it’s been over a month, but time sure flies…) from Newark element14! I’ve been doing Raspberry Pi related hacking for a while, but especially when the Pi was still fresh and new, I did from time to time consider if the grass would be greener on other side of the fence. Or blacker, in this case, as I mean BeagleBone Black.

BeagleBone was long very much more powerful than Raspberry Pi, but now that Pi2 has come out, price and specification-wise they are closer than ever. A quick personal comparison chart:

BeagleBone Black Raspberry Pi 2 (B)
Price 46 € (Element14) 32 € (Element14)
Processor 1GHz single-core Cortex-A8 0.9GHz quad-core Cortex-A7
Memory 512MB DDR3 1GB
Connections USB host, USB device, micro-HDMI 4x USB, HDMI, 3.5mm Audio/analog video
GPIO 2x 46 pin headers (65 digital I/O) 40 GPIO pins (26 digital I/O)
Other 4GB integrated flash, works as USB device camera and display interface on board

When Pi1 was out, the BeagleBone Black with the more modern Cortex-A8 chip and higher clockrate was definitely the more powerful, but now with 4-core Pi2, the tables have somewhat turned. Still, the clockrate is higher and there’s more GPIO. And speaking of GPIO, my Raspberry Pi vs. Pi2 GPIO benchmark has gotten a lot of interest, so I thought the best way to take this black beauty for a test drive would be to benchmark BeagleBone Black GPIO in a similar way.

Test setup

Test bench

The test subject is the most recent revision C of BeagleBone Black. I followed the (a bit lacking in detail and readability) Getting Started guide and downloaded the latest Debian Jessie image (8.3, 2016-01-24), flashed it to card and ran apt-get update and apt-get dist-upgrade (2016-04-14).

Read post

Bottle.py PyMySQL Plugin

I’ve been playing around today with BottlePy, an excellent mini-framework for Python web development. However, getting Python MySQL support is always a hassle, I never know if MySQLdb has died or not, so I thought I’d try PyMySQL for a change.

In addition to being just generally awesome, Bottle has a nice plugin syntax, and even a great 60-line sample of a SQLite plugin. So I adapted it for PyMySQL, turns out this was quite easy:


import pymysql.cursors
import inspect

class PyMySQLPlugin(object):
    ''' This plugin passes a pymysql database handle to route callbacks
    that accept a `db` keyword argument. If a callback does not expect
    such a parameter, no connection is made. You can override the database
    settings on a per-route basis. '''

    name = 'pymysql'
    api = 2

    def __init__(self, db, user, password, host='localhost', charset='utf8mb4', keyword='db'):
        self.host = host
        self.user = user
        self.password = password
        self.db = db
        self.charset = charset
        self.keyword = keyword

    def setup(self, app):
        ''' Make sure that other installed plugins do not affect the same
            keyword argument.'''
        for other in app.plugins:
            if not isinstance(other, PyMySQLPlugin): continue
            if other.keyword == self.keyword:
                raise PluginError("Found another %s plugin with "\
                "conflicting settings (non-unique keyword)." % self.name)

    def apply(self, callback, context):
        # Override global configuration with route-specific values.
        #conf = context.config.get('sqlite') or {}
        #dbfile = conf.get('dbfile', self.dbfile)

        # Test if the original callback accepts a 'db' keyword.
        # Ignore it if it does not need a database handle.
        args = inspect.getargspec(context.callback)[0]
        if self.keyword not in args:
            return callback

        def wrapper(*args, **kwargs):
            # Connect to the database
            db = pymysql.connect(host=self.host,
                    user=self.user,
                    password=self.password,
                    db=self.db,
                    charset=self.charset,
                    cursorclass=pymysql.cursors.DictCursor)

            # Add the connection handle as a keyword argument.
            kwargs[self.keyword] = db

            try:
                rv = callback(*args, **kwargs)
                #if autocommit: db.commit()
            #except sqlite3.IntegrityError, e:
                #db.rollback()
                #raise HTTPError(500, "Database Error", e)
            finally:
                db.close()
            return rv

        # Replace the route callback with the wrapped one.
        return wrapper

As you may see, there is no autocommit support and graceful recovery from database errors is something that is missing as well, but it’s a great start. There were a couple of GitHub projects with similar aims, but those seemed a bit behind the times (one was adding Python 3.4 support, and I’m already on 3.5, for example). A little NIH syndrome for me, maybe. Using the above library is quite easy:


from bottle import install, route
from somefile import PyMySQLPlugin

pymysql = PyMySQLPlugin(user='dbuser',
        password='dbpass', db='dbname')
install(pymysql)

@route('/demo')
def demo(db):
    # This method has a "db" parameter, and the plugin activates
    with db.cursor() as cursor:
        sql = "SELECT `id`, `password` FROM `users` WHERE `username`=%s"
        cursor.execute(sql, ('johndoe',))
        result = cursor.fetchone()
        return str(result)

Hope you found this useful!

Read post