All chapters
Cookbook · Chapter 10

Connectivity — MIDI, OSC, and devices

Talk to the outside world — MIDI controllers, OSC over the network, serial ports, and game controllers.

Umfeld talks to the outside world out of the box: MIDI controllers, OSC over the network, serial devices, and game controllers — no extra libraries to add.

MIDI input

Open a port by name in setup(), then handle the note callbacks. print_available_ports() lists what is connected so you can copy the exact name.

#include "MIDI.h"

MIDI midi;

void setup() {
    midi.print_available_ports();
    midi.open_input_port("Arturia BeatStep");
}

void note_on(int channel, int note, int velocity) {
    println("note on:", note, velocity);
}

void note_off(int channel, int note) {
    println("note off:", note);
}

For raw access, midi_message() hands you every incoming MIDI byte:

void midi_message(const std::vector<unsigned char>& message) {
    for (unsigned char b : message) print((int) b, " ");
    println();
}

OSC over the network

Create an OSC connection with the target address plus receive and send ports. Send with send(); handle incoming messages in oscEvent().

#include "OSC.h"

OSC mOSC{"127.0.0.1", 7000, 7001};   // address, receive port, send port

void keyPressed() {
    mOSC.send("/test", 23, "hello", 42);

    OscMessage msg("/mouse");
    msg.add(mouseY);
    mOSC.send(msg, NetAddress("localhost", 8000));
}

void oscEvent(const OscMessage& message) {
    println("addr:", message.addrPattern(), " types:", message.typetag());
}

Serial ports

Serial opens a port at a baud rate. Poll it (in update()), then read what arrived:

#include "Serial.h"

Serial serial("/dev/ttys002", 115200);

void setup() {
    printArray(Serial::list());     // list available ports
}

void update() {
    serial.poll();                  // required to receive data
}

void draw() {
    background(216);
    if (serial.available() > 0) {
        std::string message = serial.readString();
        console("Received: ", message.c_str());
    }
}

void keyPressed() {
    if (key == 's') serial.write("hello world\n");
}

Game controllers

Enable gamepads in settings(), then read axes and buttons each frame:

#include "Gamepad.h"

using namespace umfeld::subsystem;

void settings() {
    size(1024, 768);
    enable_gamepads();
    gamepad_resync();
}

The Advanced/gamepads example shows reading a connected controller’s sticks and buttons to move objects around (GAMEPAD_NOT_CONNECTED flags when none is attached).