About half a year ago I wrote a few silly SuperCollider classes that show sound as ASCII graphics. There are two types of level meters, a spectrogram and a stethoscope.
Below is some SuperCollider code for sending and receiving data from an Arduino. It is a good example I think and worth sharing. It can be used as a template for when you want to read and write at the same time.
As the example is written SuperCollider writes data to six PWM channels (0-255) and reads data from six analogue inputs (also 0-255). The sliders are the PWM output controllers, and the sensor input data is just posted as an array.
//supercolliderArduino_sendAndReceive /f0
// controlling 6 PWM channels and reading 6 analogue inputs at the same time
// use with SC code supercolliderArduino_sendAndReceive.scd
//--serial protocol
// PWM SC->Arduino: 10 nn nn nn nn nn nn 11 (nn bytes 1-6= PWM channels 0-5)
// ADC Arduino->SC: 20 nn nn nn nn nn nn 21 (nn bytes 1-6= analogue channels 0-5)
//--settings
byte pwmPins[]= {5, 3, 9, 6, 11, 10};
byte adcPins[]= {0, 1, 2, 3, 4, 5}; //A0-A5
//--variables
boolean changed;
byte val, cnt= 0;
byte pwmData[]= {0, 0, 0, 0, 0, 0, 0, 0};
byte adcData[]= {0, 0, 0, 0, 0, 0, 0, 0}; //for detecting change and filter out repetitions
void setup() {
Serial.begin(38400); //baud rate must match in SC
for(byte i= 0; i<6; i++) {
pinMode(pwmPins[i], OUTPUT);
pinMode(adcPins[i], INPUT);
}
}
void loop() {
//--from SC
while(Serial.available()) {
val= Serial.read();
if(cnt==0) {
if(val==10) { //beginning of message found
cnt= 1; //start counter
}
} else if(cnt<7) { //between 1 and 6 means message started and that bytes should be saved
pwmData[cnt-1]= val; //saving incoming bytes in temporary data array
cnt++;
} else {
if(val==11) {
for(byte i= 0; i<6; i++) {
analogWrite(pwmPins[i], pwmData[i]); //output read message to PWM pins
}
} else {
//serial read error
}
cnt= 0; //reset byte counter
}
}
//--to SC
changed= false;
for(byte i= 0; i<6; i++) {
val= analogRead(adcPins[i])>>4; //scale from 10 to 8 bits
if(val!=adcData[i]) {
adcData[i]= val;
changed= true;
}
}
if(changed) { //check if any sensor changed
Serial.write(20);
Serial.write(adcData[0]);
Serial.write(adcData[1]);
Serial.write(adcData[2]);
Serial.write(adcData[3]);
Serial.write(adcData[4]);
Serial.write(adcData[5]);
Serial.write(21);
}
delay(10); //wait 10 milliseconds
}
//--use with supercolliderArduino_sendAndReceive.ino
//SuperCollider code for reading 6 analogue sensors and sending out to 6 PWM channels
SerialPort.listDevices; //run this and see post window for the name of serial device
//--GUI code for sending 6 PWM
(
var name= "/dev/tty.usbserial-A101NB76"; //edit to match your serial device
var port= SerialPort(name, 38400, crtscts: true);
var pwm= [10, 0, 0, 0, 0, 0, 0, 11];
var win= Window("pwm", Rect(99, 99, 260, 200), false);
Slider(win, Rect(10, 10, 30, 170)).action_{|view| pwm.put(1, (view.value*255).asInteger); port.putAll(pwm.postln)};
Slider(win, Rect(50, 10, 30, 170)).action_{|view| pwm.put(2, (view.value*255).asInteger); port.putAll(pwm.postln)};
Slider(win, Rect(90, 10, 30, 170)).action_{|view| pwm.put(3, (view.value*255).asInteger); port.putAll(pwm.postln)};
Slider(win, Rect(130, 10, 30, 170)).action_{|view| pwm.put(4, (view.value*255).asInteger); port.putAll(pwm.postln)};
Slider(win, Rect(170, 10, 30, 170)).action_{|view| pwm.put(5, (view.value*255).asInteger); port.putAll(pwm.postln)};
Slider(win, Rect(210, 10, 30, 170)).action_{|view| pwm.put(6, (view.value*255).asInteger); port.putAll(pwm.postln)};
win.front;
CmdPeriod.doOnce({port.putAll([10, 0, 0, 0, 0, 0, 0, 11]); port.close; win.close});
//press cmd+. to stop and close window and serial port
s.waitForBoot{
var byte, num= 6, index= 0, data= Array.newClear(num);
Ndef(\arduino, {|data= #[0, 0, 0, 0, 0, 0]| Splay.ar(SinOsc.ar(data.lag(0.02)+500, 0, 0.4))}).play; //temp sound
Routine.run({
inf.do{
while({byte= port.read; byte.notNil}, {
//byte.postln; //debug
if(index==0 and:{byte==20}, { //check if first byte is 20
index= 1;
}, {
if(index>=1 and:{index<(num+1)}, { //ok, now start collecting bytes
data[index-1]= byte;
index= index+1;
}, {
if(index==(num+1) and:{byte==21}, { //until last data byte
data.postln; //debug
Ndef(\arduino).setn(\data, data);
index= 0; //done. reset index to prepare for new message
}, {
//something broke or beginning - restart
"restart".postln; //debug
index= 0;
});
});
});
});
};
});
};
)
I also attached the complete example as a zip file.
SuperCollider 2 (SC2) was such a great piece of software. Thank you, James McCartney. I plan to go back one day and I already have two old mac ti-books that still boot OS9 natively. I also have a lot of patches for max/nato that I still think produces great graphics/video under OS9 - so that's another reason for 'downgrading'.
Below is one of my first posts to sc-users. I gathered some courage and sent this mail in August 2001.
(Here is the full thread.) If you play the below sound in the newer SuperCollider versions it doesn't sound nearly as good (in my ears). To get a few steps closer to that SC2 sound, try replacing the RHPF with GlitchRHPF from SC3-plugins. Still, it isn't the same. Listen to the attached MP3 recorded with SC2 to hear these five lines of code go wild in SC2.
------------------------------
Date: Thu, 16 Aug 2001 21:12:27 +0200
From: Fredrik Olofsson <---@---.--->
Subject: noisy instr.
hello
this works... (sc 2.2.11)
({
RHPF.ar(
BrownNoise.ar([1,1]),
LFSaw.ar(1,0.99,2),
0.24).clip2(0.5)
}.scope
)
this doesn't...
({
RHPF.ar(
BrownNoise.ar([1,1]),
LFSaw.ar(1,0.99,1), //note add difference
0.24).clip2(0.5)
}.scope
)
how come the latter example runs fine for about 40 seconds and then
both channels 'get stuck' at +1, one after the other? i've had the
former playing for at least 9 min.
confused/fredrik
31jan 2003 I released two MaxMSP objects that could convert video from Jitter to nato and back. Jitter is the official library for doing video and graphics in MaxMSP. But before that was nato, or more precisely Nato.0+55+3d. Nato was a totally amazing piece of software and with it you could do similar things as with Jitter. It was mac OS9 only but super poetic and unique in all kinds of ways. I used it a lot for my live video works (klipp av tours, VJ-ing etc) and played my last gig using it as late as 2007 (at club Maria in Berlin). I still miss playing with it.
The binary OS9 objects themselves have been available for download since 2003, but I never released the C source code.
As I wasn't so good with C back then, it took weeks for me to reverse engineer the nato video format. Lots of trial-and-error using Metrowerk's CodeWarrior.
Releasing the objects to the public was scary. I risked losing my software license. n.n., the author of nato, was notorious for humiliating and threatening nato users online. And even terminating licenses if one said the wrong thing in public. One of the replies I got after the release was "!m go!ng 2 eat u". See plot.bek.no/pipermail/55/2003-March.txt. And another one was plot.bek.no/pipermail/55/2003-June/005486.html. Luckily my license didn't stop working.
For an upcoming performance, I've revisited the electronics for my redUniform piece. My old setup used a Nordic nRF24L01 wireless chip but now I changed to WiFi and the Adafruit CC3000 module.
The circuit is minimal and simple. It's just the CC3000 WiFi module, an ATmega328, a 16Mhz crystal, an on/off switch, one 1000mAh Li-ion and last two 6p connectors for the sensors.
For a new piece I'm working on (redAlert), I wanted hundreds of red LEDs attached to special 'blobs' or lamps spread out on stage (designed by Jenny Michel). Each led should be able to be freely placed and controlled individually and they had to be fairly bright. And because of the custom led placement I couldn't have used led strips - strips have a fixed distance between the LEDs.
So I built three circuits that could drive 32 PWM channels each and thereby got 96 PWM channels in total. Each channel connects three LEDs in series (in a single package) and a resistor. That makes in total 288 LEDs.
The led I selected was the LED 5252 uh rt/1700mcd. It has 120 degrees spread angle and comes in a 5x5mm 6pin SMD package that's possible to solder by hand. I bought it from Segor where it costs 0.42 Euro if you buy +100.
Here a picture of it from the backside. The 270 Ohm resistor is chosen to match 12V and the three LEDs are connected in series using thin copper wire.
The three boards are controlled wirelessly and I send OSC commands from SuperCollider to control all the LEDs. There's a class for SuperCollider attached below that helps with addressing and packaging of the network data. One can build and connect as many of these 32ch boards as one likes.
For actually generating the 12V PWM I used on each board two TLC5490 in combination with four ULN2803a. and I also added a barebone Arduino to get a stable SPI communication with the TLC5490.
Backside...
For receiving wireless OSC data I added a Raspberry Pi (model A) with an USB WLAN stick. On the RPi there's just a small Python program that receives OSC and sends out serial commands to the Arduino.
Last I have a TP-link TL-WR703N with Open WRT installed acting as a router. When the boards start, they try to connect to this router and gets an IP assigned dynamically. This IP I use in SuperCollider to differentiate between the three boards.
Installation instructions
* put 2013-09-25-wheezy-raspbian.img on an SD card with Pi Filler
* put the card in a Raspberry Pi MODEL B, connect ethernet and 5V
* find the IP with LanScan.app
(* ssh-keygen -R 192.168.1.51)
* ssh pi@192.168.1.51
* default password: raspberry
* sudo raspi-config
* select 'Expand Filesystem', change password, reboot and log in with SSH again
* sudo apt-get update
* sudo apt-get upgrade
* sudo pico /etc/inittab
* comment out the line 'T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100' near the bottom and save
* sudo pico /boot/cmdline.txt
* remove 'console=ttyAMA0,115200 kgdboc=ttyAMA0,115200' and save
* sudo reboot
* sudo apt-get install python-serial
* git clone git://gitorious.org/pyosc/devel.git
* cd devel
* sudo ./setup.py install
* cd ~
//--set up WLAN on the RPi
* sudo nano /etc/network/interfaces
* edit to say...
auto wlan0
allow-hotplug wlan0
iface wlan0 inet dhcp
wpa-ssid SSID_NAME
wpa-psk SSID_PASS
wireless-power off
* sudo ifdown wlan0
* sudo ifup wlan0
//--copy file from laptop to RPi
* scp redAlertLight.py pi@192.168.1.51:/home/pi/
//--automatically start the Python program at startup
* sudo pico /etc/rc.local
* add the following before the exit line: (sleep 1; python /home/pi/redAlertLight.py) & # autostart
//now move the SD card over to model A, connect the circuit and try
//--useful if you log in via SSH and want to stop the Python program
* sudo pkill python
Here is the Python code...
#redFrik 2013
import serial
import socket
import OSC
import threading
import time
import os
addy= '0.0.0.0', 15000 #from SC
osc_server= OSC.OSCServer(addy)
port= serial.Serial('/dev/ttyAMA0', 115200) #to ATmega168
port.open()
def osc_led(addr, tags, data, source):
#print tags
#print "incoming OSC data: %s" % data
arr= bytearray()
arr.append(254)
for val in data: #data has size 16 (24bit ints)
hi_val= val>>12
lo_val= val&4095
#here can be optimized later to send fewer bytes (48 instead of 64)
arr.append(hi_val>>8)
arr.append(hi_val&255)
arr.append(lo_val>>8)
arr.append(lo_val&255)
arr.append(255)
port.write(arr)
osc_server.addMsgHandler("/led", osc_led)
def osc_stop(addr, tags, data, source):
#print tags
#print "shutting down"
shutdown()
osc_server.addMsgHandler("/stop", osc_stop)
thread= threading.Thread(target= osc_server.serve_forever)
thread.start()
def all_led_off():
osc_led(None, None, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], None)
def shutdown():
close()
os.system("sudo halt")
exit()
def close():
print "\nclosing"
osc_server.close()
all_led_off()
port.close()
#thread.join()
def main():
try:
while True:
line= port.readline()
if line.startswith("stop"):
shutdown()
except KeyboardInterrupt:
close()
if __name__ == "__main__":
main()
Attached are schematics, Arduino firmware, parts list...