Mads Kjeldgaard

November 9, 2020

breadboarded esp32

Lately I have started experimenting with the very cheap and powerful ESP32 microcontrollers.

Today I made a simple example of a firmware which receives OSC from a computer and then blinks the on-board LED according to the incoming message and I packaged it all as an easy to clone/copy/use platformio project (mostly for myself).

The firmware uses CNMAT’s OSC library:

#include "Arduino.h"
#include "WiFi.h"
#include <OSCMessage.h>

WiFiUDP Udp; // A UDP instance to let us send and receive packets over UDP
int LED_BUILTIN = 2;

// Options
int update_rate = 16;

// Network settings
char ssid[] = "wifiname"; // your network SSID (name)
char pass[] = "wifipassword";  // your network password
unsigned int localPort = 8888; // local port to listen for OSC packets

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);

  /* setup wifi */
  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }

  Udp.begin(localPort);
}

void ledtoggle(OSCMessage &msg) {
  switch (msg.getInt(0)) {
  case 0:
    digitalWrite(LED_BUILTIN, LOW);
    break;
  case 1:
    digitalWrite(LED_BUILTIN, HIGH);
    break;
  }
}

void receiveMessage() {
  OSCMessage inmsg;
  int size = Udp.parsePacket();

  if (size > 0) {
    while (size--) {
      inmsg.fill(Udp.read());
    }
    if (!inmsg.hasError()) {
      inmsg.dispatch("/led", ledtoggle);
    } 
    //else { auto error = inmsg.getError(); }
  }
}

void loop() {
  receiveMessage();
  delay(update_rate);
}

And here is some SuperCollider code to play around with:

(
// Target IP. Change the IP address accordingly
~ip = "10.0.0.11";
~port = 8888;
t = NetAddr.new(~ip, ~port);

)

// Turn led on
t.sendMsg("/led", 1)

// Turn led off
t.sendMsg("/led", 0)

// Or do it with a pattern
(

Pbind(
	\dur, Prand([0.25, 0.125, 0.5, 0.0125, 0.025], inf), 
	\led, Pxrand([1,0],inf),
	\play, Pfunc({|ev| t.sendMsg("/led", ev[\led])}),
).play

)
Tags: