esp8266 opensound control

here some example arduino code for sending and receiving osc via the cheap esp8266 serial wifi module.

note that the opensound control messages here are very basic - only 4 bytes packed into a single 32bit integer.

* upload the code below to an arduino.

* connect esp8266 TX pin to arduino pin0.

* connect esp8299 RX to arduino pin1. it is safest to use a 3v3 lever converter for this line (or at least a voltage divider).

* power the esp8266 (VCC and GND) from an external 3v source. do not use the arduino 3v3pin as it cannot provide the required current. i used a LF33CV voltage regulator to get 3.3v from the 5v supply that also powers the arduino.

* connect esp8288 RESET pin to arduino pin4.

* and last connect esp8266 CH_PD to 3v3

optional: connect a separate usb-serial (ftdi) chip to arduino pins 2 and 3 to use software serial debugging. start debugging in terminal with something like screen /dev/tty.usbserial-A4015TKA 115200

the arduino code sits and waits for an incoming osc message (/tap). it then replies by sending out a counter message (/sti).

//f0 150705
//sending and receiving udp osc with an esp8266
//for an arduino + esp8266 with firmare 0.9.5.2

#include <SoftwareSerial.h>

#define WLAN_SSID  "SSID"
#define WLAN_PASS  "PASS"
#define WLAN_ADDR  "192.168.1.51" //laptop running sc
#define PORT  1112 //incoming osc port
String tag = "/tap"; //incoming osc addy

SoftwareSerial mySerial(2, 3);

uint8_t buf[16];
byte cnt;
byte id, on, hi, lo;
boolean resp;

void setup() {

  //--osc message
  buf[0] = 47;   // /
  buf[1] = 115;  // s
  buf[2] = 116;  // t
  buf[3] = 105;  // i
  buf[4] = 0;
  buf[5] = 0;
  buf[6] = 0;
  buf[7] = 0;
  buf[8] = 44;   // ,
  buf[9] = 105;  // i
  buf[10] = 0;
  buf[11] = 0;
  buf[12] = 4;   // a high   (id)
  buf[13] = 3;   // a low    (on)
  buf[14] = 2;   // b high   (hi)
  buf[15] = 0;   // b low    (lo)

  mySerial.begin(115200);
  Serial.begin(115200);
  Serial.setTimeout(10000);
  mySerial.println("");
  mySerial.println("starting");

  mySerial.print("hard reset...");
  digitalWrite(4, 0);
  pinMode(4, OUTPUT);
  delay(10);
  pinMode(4, INPUT);
  resp = Serial.find("ready\r\n");
  mySerial.println(resp);

  mySerial.print("mode1...");
  Serial.println("AT+CWMODE=1");
  resp = Serial.find("OK\r\n");
  mySerial.println(resp);

  mySerial.print("connecting...");
  do {
    Serial.print("AT+CWJAP=\"");
    Serial.print(WLAN_SSID);
    Serial.print("\",\"");
    Serial.print(WLAN_PASS);
    Serial.println("\"");
    resp = Serial.find("OK\r\n");
    mySerial.println(resp);
  } while (!resp);

  mySerial.print("mux1...");
  Serial.println("AT+CIPMUX=1");
  resp = Serial.find("OK\r\n");
  mySerial.println(resp);

  mySerial.print("udp...");
  Serial.print("AT+CIPSTART=4,\"UDP\",\"");
  Serial.print(WLAN_ADDR);
  Serial.print("\",57120,");
  Serial.print(PORT);
  Serial.println(",0");
  resp = Serial.find("OK\r\n");
  mySerial.println(resp);

  Serial.setTimeout(1000);
}
void loop() {
  while (Serial.available()) {
    String abc = Serial.readStringUntil('\n');
    if (abc.startsWith("+IPD,4,16:" + tag)) {
      id = abc[22];
      on = abc[23];
      hi = abc[24];
      lo = abc[25];
      mySerial.print("id:");
      mySerial.println(id);
      mySerial.print("on:");
      mySerial.println(on);
      mySerial.print("hi:");
      mySerial.println(hi);
      mySerial.print("lo:");
      mySerial.println(lo);

      buf[15] = cnt++;
      Serial.println("AT+CIPSEND=4,16");
      Serial.find(">");
      Serial.write(buf, sizeof(buf));
      resp = Serial.find("OK\r\n");
      mySerial.print("send...");
      mySerial.println(resp);
    }
  }
}

supercollider test code:

(
//--call&response
var last= Main.elapsedTime;
OSCFunc({|msg, time, addr|
        [\id, msg[1]>>24, \on, (msg[1]>>16)&255, \hi, (msg[1]>>8)&255, \lo, msg[1]&255, time-last, addr].postln;
        last= time;
}, \sti);
n= NetAddr("192.168.1.50", 1112); //esp8266 ip address
f= {|id, on, hi, lo| (id&255<<24)|(on&255<<16)|(hi&255<<8)|(lo&255)};
r= Routine.run({
        inf.do{|i|
                n.sendMsg(\tap, f.value(4, 1, i.asInteger>>8&255, i.asInteger%256));
                0.5.wait;
        };
});
)

bass!

for a project in collaboration with stine janvin motland i built this 4-channel transducer bass shaker system.

the system has four transducers (visaton bs 130, 4Ω), two class d stereo amplifiers (2x50w, tda7492 chip) and a powerful atx switching power supply (codecom pm-350c).

i modified the power supply to only give out 12v (yellow&black cables) and also made it start up automatically by shorting the green cable (ps-on) to ground (black).

transducers 1

transducers 2

there's no volume control so better take care - the system is very hot.

pd on raspberry pi

here is a quick tutorial on how to install and run puredata headless on a raspberry pi. the instructions assume you want to start with a new clean [raspbian] system image and do it all from scratch.
the instructions also assume you have a raspberry model b, an usb soundcard like terratec's aureon dual usb and an ethernet cable with internet access (just connect the cable to your router).
what you get after following the below tutorial is a sdcard with a pd patch that automatically starts when the pi is booted.

update 160109: also works great on a raspberrypi2 with 2015-11-21-raspbian-jessie.img

//--preparations:
* put the raspbian image (2014-12-24-wheezy-raspbian.img) onto a +4gb card (on osx it is easily done with PiFiller).
* insert the sdcard+ethernet+usbsoundcard and power up the rpi
* open the terminal application on your laptop and type...
$ ssh pi@raspberrypi.local #log in from laptop with pi/raspberry (see notes below if fail)

//--setup
$ sudo raspi-config #run this on the rpi and do the following system configurations
* select expand filesystem
* change user password
* optionally lower the gpu memory under advanced / memory split
* select finish and reboot

$ ssh pi@raspberrypi.local #log in again from laptop
$ sudo apt-get update #on the rpi. check for new updates
$ sudo apt-get upgrade #update any old packages

//--test sound
$ lsusb #should list the usb soundcard
$ aplay -l #should also list the soundcard
$ sudo speaker-test -t sine -c 2 -Ddefault:CARD=Device #should sound if headphones connected. stop with ctrl+c
# note this assume that your usb soundcard name is Device - check what aplay and edit the CARD= in the line above if needed.

//--install pd
$ sudo apt-get install puredata #download and install puredata + required packages

//--test pd patches
copy the following two example pd patches (or download the attachments below) and save them on your laptop (here assume on the desktop). to copy pd patches just paste the cryptic text into a plain text editor and save with .pd file extension.

//--testsines.pd

#N canvas 1068 88 450 300 10;
#X obj 238 159 dac~;
#X obj 235 73 osc~ 400;
#X obj 289 73 osc~ 404;
#X msg 126 154 \; pd dsp 1;
#X obj 126 83 loadbang;
#X obj 126 123 del 100;
#X text 42 122 important ->;
#X obj 238 111 *~ 0.2;
#X obj 280 111 *~ 0.2;
#X connect 1 0 7 0;
#X connect 2 0 8 0;
#X connect 4 0 5 0;
#X connect 5 0 3 0;
#X connect 7 0 0 0;
#X connect 8 0 0 1;

//--testmic.pd

#N canvas 1068 88 450 300 10;
#X obj 238 230 dac~;
#X msg 126 154 \; pd dsp 1;
#X obj 126 83 loadbang;
#X obj 126 123 del 100;
#X text 42 122 important ->;
#X obj 238 24 adc~;
#X obj 238 53 delwrite~ del1 500;
#X obj 238 123 delread~ del1 500;
#X obj 259 80 delwrite~ del2 750;
#X obj 280 144 delread~ del2 750;
#X obj 238 182 *~ 0.2;
#X obj 280 182 *~ 0.2;
#X connect 2 0 3 0;
#X connect 3 0 1 0;
#X connect 5 0 6 0;
#X connect 5 1 8 0;
#X connect 7 0 10 0;
#X connect 9 0 11 0;
#X connect 10 0 0 0;
#X connect 11 0 0 1;

//--copy pd files to rpi
$ exit #log out from the rpi
# run the two lines below on your laptop to copy the two example patches to your rpi. (this is also how you can transfer more pd patches later on.)
$ scp ~/Desktop/testsines.pd pi@raspberrypi.local:/home/pi/
$ scp ~/Desktop/testmic.pd pi@raspberrypi.local:/home/pi/

//--run puredata
$ ssh pi@raspberrypi.local #log in from laptop again
$ pd -stderr -nogui -verbose -audiodev 4 testsines.pd #stop with ctrl+c
$ pd -stderr -nogui -verbose -audiodev 4 testmic.pd #stop with ctrl+c
# note: you will need to connect headphones or speakers for the first example to work. and some kind of audio input (e.g. electret mic or line-in from mp3 player) for the second example patch to work.

//--autostart
$ nano autostart.sh #creates a new file. copy the two lines below into this new file.

#!/bin/bash
pd -nogui -audiodev 4 /home/pi/testsines.pd

# save and exit with ctrl+o, return, ctrl+x
$ chmod +x autostart.sh #make the autostart.sh file executable
$ sudo crontab -e #and add at the end...

@reboot /bin/bash /home/pi/autostart.sh

# again save and exit with ctrl+o, return, ctrl+x
$ sudo reboot #restarts the rpi. after booting the sine tones patch should have started automatically.

//--stopping
$ ssh pi@raspberrypi.local #log in from laptop once more
$ sudo pkill pd #stop pd
$ sudo halt #turn off the rpi safely

//--notes
* if you cannot log in and you get ssh: Could not resolve hostname raspberrypi.local, you might need to replace raspberrypi.local with the exact ip address of the rpi (e.g. ssh pi@192.168.1.51). the exact address will vary and can be found in your router setup.
* note: if you get WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! then run the command $ ssh-keygen -R raspberrypi.local to reset the ssh key.
* when ready with everything and you have the correct pd patch autostarting you can [physically] lock the sd-card. this will put it in no-write mode and possibly prolong its life (specially if you cut the power without properly turning off the system with sudo halt)
* if you experience audio dropouts you might try the suggestions here... http://wiki.linuxaudio.org/wiki/raspberrypi. most important force usb1.1 and set cpu governor to performance mode.
* if you get ALSA output error Device or resource busy when trying to start pd, then delay the ';pd dsp 1' message in your pd patch with about 100 milliseconds.
* to remove the autostart just delete the file autostart.sh and go into cron again and remove the last line you added with sudo crontab -e

AttachmentSize
Binary Data testsines.pd370 bytes
Binary Data testmic.pd522 bytes

supercollider firmata

clean-up: #57

just cleaned up an example for supercollider and arduino that i found on my computer. it is demonstrating the SCFirmata class by Eirik Arthur Blekesaune.

//how to read pin A0 with SCFirmata...

//for Arduino1.0.6 and SC3.6.6
//first in Arduino IDE:
//  * select File / Examples / Firmata / StandardFirmata
//  * upload this example to an arduino
//then in SC install the SCFirmata classes
//  * download zip file https://github.com/blacksound/SCFirmata
//  * extract files and put them in your sc application support directory
//  * recompile sc

SerialPort.devices
d= SerialPort.devices[0]; // or d= "/dev/tty.usbserial-A1001NeZ" - edit number (or string) to match your arduino
f= FirmataDevice(d);//if it works it should post 'Protocol version: 2.3' after a few seconds

s.boot
Ndef(\snd, {|freq= 400, amp= 0.5| SinOsc.ar([freq, freq+4].lag(0.08), 0, amp.lag(0.08)).tanh}).play;
f.reportAnalogPin(0, true)      //start reading A0
f.analogPinAction= ({|num, val| [num, val].postln; Ndef(\snd).set(\freq, val.linexp(0, 1023, 400, 800))})//control freq
f.analogPinAction= ({|num, val| [num, val].postln; Ndef(\snd).set(\amp, val.linexp(0, 1023, 0.001, 1))})//control amp instead

Ndef(\snd).stop
f.reportAnalogPin(0, false)     //stop reading A0
f.end
f.close

audioSerial

clean-up: #56

compared to generating a serial bitstream in audio, analyzing and extract serial data from audio is much harder. the supercollider code below does it, but the program has limitations and is quite sensitive for noise.

the code takes a string, chops it up into groups of six 8bit bytes and generates a serial audio bitstream from that. another part listens to this sound and tries to decode it. if it finds six full bytes it sends the result back to sclang via osc where it is printed.
to test the example connect an audio cable directly from your computer's output to its input (preferably via a small mixer), or change the audioSerial synthdef to use an internal audio bus. i can also imagine it could function with a mic next to the speakers - but i didn't test this.
if it only prints gibberish try with a different threshold setting, different volume on you computer or use a lower baud rate.

(
s.waitForBoot{
        var baudrate= 9600;
        SynthDef(\serialAudio, {|out= 0, amp= -0.5|                     //for sending out serial via audio
                var data= Control.names([\data]).kr(Array.fill(60, 0)); //max 6 bytes
                var src= Duty.ar(1/baudrate, 0, Dseq(data), 2);
                OffsetOut.ar(out, src*amp);
        }).add;
        SynthDef(\audioSerial, {|in= 0, thresh= 0.05|           //for receiving serial via audio
                var raw= 0-SoundIn.ar(in); //here change to In.ar if trying internal audio bus
                var src= raw>thresh;
                var reading= DelayC.ar(Trig1.ar(src, 1/baudrate*9), 1/baudrate/2, 1/baudrate/2);
                var osc= Phasor.ar(reading, baudrate/SampleRate.ir);
                var clock= (osc-Delay1.ar(osc))<0+Impulse.ar(0);
                var index= PulseCount.ar(clock, reading);
                var stopTrig= index>7;
                var data= Latch.ar(src, index>=#[7, 6, 5, 4, 3, 2, 1]);
                var byte= (1-data).sum{|x, i| 2**(6-i)*x};
                SendReply.ar(stopTrig, '/data', byte);
                DC.ar(0);
        }).add;
        OSCFunc({|msg| msg[3].asInteger.asAscii.post}, '/data');
        s.sync;
        Synth(\audioSerial);
};
)

(
var str= "hello supercollider!";
var baudrate= 9600;
fork{
        1.wait;
        str.ascii.clump(6).do{|bytes|
                var data= bytes.collect{|x| [1]++(1-x.asBinaryDigits.reverse)++[0]}.flat;
                s.bind{
                        Synth(\serialAudio, [\data, data]);
                };
                (1/baudrate*60+0.005).wait;
        };
};
)

one can use this technique to communicate with another computer via audio. to communicate with a microcontroller (e.g. an arduino), one needs additional electronics (amplification, rectification). here's schematics for a bi-directional circuit for talking to a 5v arduino.

this audio-to-serial technique was used to get input from rfid, touch and bend sensors in our reflect installation. i.e. sc is running on an ipod touch and receives all sensor data via audio from an atmega168 microcontroller.

serialAudio

clean-up: #55

another way (compared to fsk in my previous blog entry) of sending data via audio is to directly generate the serial bit stream using supercollider.

to test and learn about these things i first wrote and uploaded a very simple program to an arduino board. the program just transmitted the bytes 128, 10, 20, 30, 40 and 50.

//arduino testcode
void setup() {
  Serial.begin(9600);
}
void loop() {
  delay(1000);
  Serial.write(128);
  Serial.write(10);
  Serial.write(20);
  Serial.write(30);
  Serial.write(40);
  Serial.write(50);
}

then i connected the arduino serial tx pin (pin1) to the audio line-in of my laptop (via a 1k + 10k voltage divider) and recorded the sound of the serial transmission.

i then analyzed the sound by hand and wrote a little program in sc that could generate similar waveforms.

s.boot;
o= {|chr| [1]++(1-chr.asBinaryDigits.reverse)++[0]};
(
SynthDef(\serialAudio, {|amp= -0.5|     //for sending out serial via audio
        var data= Control.names([\data]).kr(Array.fill(60, 0));//max 6 bytes
        var src= Duty.ar(1/9600, 0, Dseq(data), 2);     //baudrate
        OffsetOut.ar(1, src*amp);
}).add;
)
Synth(\serialAudio, [\data, [128, 10, 20, 30, 40, 50].collect{|c| o.value(c)}.flat, \amp, -0.5]);

this screenshot show the signal recorded from the arduino in the first channel, and the supercollider generated one in the second.

after all this i could reverse the process, generate any serial data and send it back to the arduino rx pin (pin0). a small amplifier circuit in between helped to get a more stable communication going.

this serial-to-audio technique was used to control the 24 leds (6 pwm channels) in our reflect installation. i.e. sc is running on an ipod touch and sends out serial audio to an atmega168 microcontroller.

here is another example that can fade a single led by sending serial commands over audio. includes schematics for an amplifier circuit plus sc and pd example code.

and for a more advanced (actually using a much better technique) example see here

fsk

clean-up: #54

for a few projects in the past i had to communicate data bidirectionally via sound. it involved for example hooking up a microcontroller to an ipod touch (running supercollider) so that the device could read sensors and/or control leds. one successful method was to do frequency-shift keying. see here for another blog entry on that.
i've published fsk pure data code for that before, and also some supercollider code for generating/encoding fsk, but never the decoding part i think.
so below is some old code i've cleaned up a bit. it just demonstrates sending audio via internal sc busses at a very low baudrate. for good baudrate and min/max frequency settings see here

(
s.latency= 0.05;
s.waitForBoot{
        SynthDef(\redFSKdecode, {|in= 20, thresh= 0.1, baudrate= 126, lo= 882, hi= 1764|
                var sig= InFeedback.ar(in, 1);
                var sigActive= Amplitude.ar(sig, 0.01, 0.01)>thresh;
                var fre= 1/Timer.ar(sig*sigActive);
                var trg= Schmidt.ar(fre, lo+(baudrate*0.5), hi-(baudrate*0.5)); //0= lo, 1= hi
                var trgLo= trg<0.5;
                var trgHi= 1-trgLo;
                var trgCarr= Sweep.ar(trgHi, 1)>(1/baudrate*16); //when found more than 16bits high in a row
                var trgData= SetResetFF.ar(trgLo*trgCarr, trgCarr);
                var imp= Phasor.ar(trgData, baudrate/SampleRate.ir);
                var writeTrg= (imp-Delay1.ar(imp))<0+Impulse.ar(0);
                var writePos= PulseCount.ar(writeTrg, trgData);
                var writeVal= Median.ar(31, trg);
                var ok, done= 1-trgData;
                var buf= LocalBuf(13).clear;
                Demand.ar(writeTrg, 0, Dbufwr(writeVal, buf, writePos, 0));
                ok= done*(1-Demand.ar(done, 0, Dbufrd(buf, 1, 0)))*Demand.ar(done, 0, Dbufrd(buf, 11, 0));
                SendReply.ar(ok, '/data', Demand.ar(ok, 0, Dbufrd(buf, (2..9), 0)));
                DC.ar(0);
        }).add;
        SynthDef(\redFSKencode, {|out= 0, amp= 0.6, minFreq= 4900, maxFreq= 7350, invBaudrate= 0.008|
                var data= Control.names([\data]).ir(Array.fill(8, 0));
                var env= EnvGen.ar(Env(#[1, 1, 0], [invBaudrate*(16+11), 0]), doneAction:2);
                var parity= data.sum+1;
                var freq= Duty.ar(Dseq([invBaudrate*16]++invBaudrate.dup(11)), 0, Dseq(#[1, 0]++data++[parity%2, 1]));
                var src= SinOsc.ar(freq*(maxFreq-minFreq)+minFreq, 0, amp);
                OffsetOut.ar(out, src*env);
        }).add;
};
)

//test sending a simple counter
(
var baudrate= 126;
var lo= 882;
var hi= 1764;
OSCFunc({|msg|
        var byte;
        //("received:"+msg[3..]).postln;
        byte= msg[3..].sum{|x, i| 2**i*x};
        ("received:"+byte).postln;
}, '/data');
Routine.run({
        Synth(\redFSKdecode, [\in, 20]); //bus 20
        inf.do{|i|
                var byte= (i%256).asInteger;
                var data= byte.asBinaryDigits.reverse;
                s.bind{
                        ("sending :"+byte).postln;
                        Synth(\redFSKencode, [\minFreq, lo, \maxFreq, hi, \data, data, \out, 20, \invBaudrate, 1/baudrate]); //bus 20
                        Synth(\redFSKencode, [\minFreq, lo, \maxFreq, hi, \data, data, \out, 0, \invBaudrate, 1/baudrate]); //monitor
                };
                (1/baudrate*(11+16)).wait;
        };
})
)

//test a string of text
(
var baudrate= 126;
var lo= 882;
var hi= 1764;
OSCFunc({|msg|
        var byte;
        //("received:"+msg[3..]).postln;
        byte= msg[3..].sum{|x, i| 2**i*x};
        ("received:"+byte.asInteger.asAscii).postln;
}, '/data');
Routine.run({
        Synth(\redFSKdecode, [\in, 20]); //bus 20
        "hello supercollider!".do{|x|
                var byte= x.ascii.clip(0, 255);
                var data= byte.asBinaryDigits.reverse;
                s.bind{
                        //("sending :"+x+byte+data).postln;
                        Synth(\redFSKencode, [\minFreq, lo, \maxFreq, hi, \data, data, \out, 20, \invBaudrate, 1/baudrate]); //bus 20
                        Synth(\redFSKencode, [\minFreq, lo, \maxFreq, hi, \data, data, \out, 0, \invBaudrate, 1/baudrate]); //monitor
                };
                (1/baudrate*(11+16)).wait;
        };
})
)

this fsk technique was used in many projects to control leds. e.g. most of the 3rd gen projects listed here are running supercollider on an ipod touch with the 6 channels led brightness data being sent via fsk on one of the audio output channels.

androsensor

clean-up: #53

below some code for reading and parsing data from the android app AndroSensor.
with this free app you can record a lot of different sensors in your android phone (like gps, accel, mic, battery, light etc etc) and save it to a comma separated file (csv). later one can copy over the data file from the android phone to a computer and read it in supercollider. the csv files are normally stored on the sd card in a folder called AndroSensor.

by default the app only save and display data at slow update rates, so go into the AndroSensor's settings and change update interval to very fast and recording interval to for example 0.05 seconds (the fastest).

// https://play.google.com/store/apps/details?id=com.fivasim.androsensor

//--read the data - edit the path to your csv file
(
var path= "~/Desktop/Sensor_record_20141018_115750_AndroSensor.csv"; //edit here
var data= CSVFileReader.read(path.standardizePath, delimiter:$;, startRow:1);
var data2= data.flop;
var dict= ();
data2.do{|x|
        var key= x[0];
        var val= x.copyRange(1, x.size-1);
        while({key.last==Char.space or:{key.last==$:}}, {
                key= key.copyRange(0, key.size-2);
        });
        if(val[0].any{|x| #[$:, $/].includes(x)}.not, {
                val= val.asFloat; //make single numbers into floats
        //}, { //else do nothing - keep date and satellites as strings
        });
        dict.put(key.asSymbol, val);
};
~dict= dict; //handle
)

//--list all stored keys...
~dict.keys.do{|x| x.postln}

//--access data stored at keys...
~dict['ACCELEROMETER X (m/s²)']
~dict['ACCELEROMETER Y (m/s²)']
~dict['ACCELEROMETER Z (m/s²)']
~dict['GRAVITY X (m/s²)']
~dict['GRAVITY Y (m/s²)']
~dict['GRAVITY Z (m/s²)']
~dict['GYROSCOPE X (rad/s)']
~dict['GYROSCOPE Y (rad/s)']
~dict['GYROSCOPE Z (rad/s)']
~dict['LIGHT (lux)']
~dict['MAGNETIC FIELD X (μT)']
~dict['MAGNETIC FIELD Y (μT)']
~dict['MAGNETIC FIELD Z (μT)']
~dict['ORIENTATION X (°)']
~dict['ORIENTATION Y (°)']
~dict['ORIENTATION Z (°)']
~dict['PROXIMITY (i)']
~dict['SOUND LEVEL (dB)']
~dict['LOCATION Latitude']
~dict['LOCATION Longitude']
~dict['LOCATION Altitude ( m)']
~dict['LOCATION Speed ( Kmh)']
~dict['LOCATION Accuracy ( m)']
~dict['Satellites in range'] //note as strings
~dict['Temperature (F)']
~dict['Level (%)']
~dict['Voltage (Volt)']
~dict['Time since start in ms'] //timestamps in milliseconds
~dict['YYYY-MO-DD HH-MI-SS_SSS'] //absolute timestamps - note as strings

//--plot the xyz accelerometer data...
(
[
        ~dict['ACCELEROMETER X (m/s²)'],
        ~dict['ACCELEROMETER Y (m/s²)'],
        ~dict['ACCELEROMETER Z (m/s²)']
].plot
)

//--plot the xyz orientation data...
(
[
        ~dict['ORIENTATION X (°)'],
        ~dict['ORIENTATION Y (°)'],
        ~dict['ORIENTATION Z (°)']
].plot
)

//--plot a lot of data (but not all)...
(
[
        'ACCELEROMETER X (m/s²)',
        'ACCELEROMETER Y (m/s²)',
        'ACCELEROMETER Z (m/s²)',
        'GRAVITY X (m/s²)',
        'GRAVITY Y (m/s²)',
        'GRAVITY Z (m/s²)',
        'GYROSCOPE X (rad/s)',
        'GYROSCOPE Y (rad/s)',
        'GYROSCOPE Z (rad/s)',
        'LIGHT (lux)',
        'MAGNETIC FIELD X (μT)',
        'MAGNETIC FIELD Y (μT)',
        'MAGNETIC FIELD Z (μT)',
        'ORIENTATION X (°)',
        'ORIENTATION Y (°)',
        'ORIENTATION Z (°)',
        'SOUND LEVEL (dB)'
].collect{|x| ~dict[x]}.plot;
)

//--sound example mapping accelerometer to simple sound
(
s.waitForBoot{
        var a= {|freq= 500, amp= 0, pan= 0| Pan2.ar(Pulse.ar(freq.lag(0.25), 0.2, amp.lag(0.25)), pan.lag(0.25))}.play;
        s.sync;
        Routine.run({
                var prevTime= 0;
                ~dict['Time since start in ms'].do{|x, i|
                        a.set(
                                \freq, ~dict['ACCELEROMETER Y (m/s²)'][i].linexp(-20, 20, 100, 1000),
                                \amp, ~dict['ACCELEROMETER Z (m/s²)'][i].linlin(-20, 20, 0, 1),
                                \pan, ~dict['ACCELEROMETER X (m/s²)'][i].linlin(-20, 20, -1, 1)
                        );
                        (x-prevTime*0.001).wait;
                        prevTime= x;
                };
                "done".postln;
                a.release;
        });
};
)

attached is a demo csv file of me first keeping the phone still, and then shaking it a bit + turning it around. the data recording is only about eight seconds long.

if you plot for example the 3d accelerometer data it will look like this...

Pages

Subscribe to f0blog RSS