Graph + Sound code
by leah
Libraries you’ll need:
Sonia
JSyn
Arduino code:
int sensorPin = A2;
int sensorValue;
void setup()
{
Serial.begin(9600);
pinMode(sensorPin, INPUT);
digitalWrite(sensorPin,HIGH);
}
void loop()
{
sensorValue = analogRead(sensorPin);
Serial.println(sensorValue);
delay(10);
}
Processing code:
Download code + example sound file
import processing.serial.*;
import pitaru.sonia_v2_9.*;
Serial myPort; // The serial port
int xPos = 1; // horizontal position of the graph
Sample tone;
void setup () {
// set the window size:
size(400, 300);
// List all the available serial ports
println(Serial.list());
// I know that the first port in the serial list on my mac
// is always my Arduino, so I open Serial.list()[0].
// Open whatever port is the one you're using.
myPort = new Serial(this, Serial.list()[0], 9600);
// don't generate a serialEvent() unless you get a newline character:
myPort.bufferUntil('\n');
// set inital background:
background(0);
Sonia.start(this);
// Create a new sample object.
tone = new Sample( "tone.wav" );
// Loop the sound forever
// (well, at least until stop() is called)
tone.repeat();
tone.setVolume(1);
smooth();
}
void draw () {
// everything happens in the serialEvent()
}
void serialEvent (Serial myPort) {
// get the ASCII string:
String inString = myPort.readStringUntil('\n');
if (inString != null) {
// trim off any whitespace:
inString = trim(inString);
// convert to an int and map to the screen height:
float inByte = float(inString);
inByte = map(inByte, 0, 1023, 0, height);
// draw the line:
stroke(127,34,255);
line(xPos, height, xPos, height - inByte);
// change the playback speed using the incoming data
float ratio = (float) inByte/height;
//println(ratio);
tone.setRate(ratio*88200, 0);
//tone.setVolume(ratio);
// at the edge of the screen, go back to the beginning:
if (xPos >= width) {
xPos = 0;
background(0);
}
else {
// increment the horizontal position:
xPos++;
}
}
}
// Pressing the mouse stops and starts the sound
void mousePressed() {
if (tone.isPlaying()) {
tone.stop(); // The sound can be stopped with the function stop().
} else {
tone.repeat();
}
}
// Close the sound engine
public void stop() {
Sonia.stop();
super.stop();
}