xxxxxxxxxx
135
let serial;
let port = "/dev/cu.usbmodem1421";
let options = {
baud: 9600
}
let data;
let wasPlaying2 = false;
let wasPlaying1 = false;
let synth;
let synth2;
let notes1 = ["E2", "C3", "A3"];
let notes2 = ["C4", "A5", "B4"];
let mic;
function setup() {
createCanvas(windowWidth, windowHeight);
background(255, 0, 0);
synth = new p5.PolySynth();
synth2 = new p5.PolySynth();
mic = new p5.AudioIn();
mic.start();
serial = new p5.SerialPort();
// Let's list the ports available
let portlist = serial.list();
serial.open(port, options);
serial.on('connected', serverConnected);
serial.on('list', gotList);
serial.on('data', gotData);
serial.on('error', gotError);
serial.on('open', gotOpen);
}
// There is data available to work with from the serial port
function gotData() {
let currentString = serial.readStringUntil("\r\n");
if (currentString) {
if (currentString == "hello") {
serial.write(1);
} else {
background(0, 255, 0);
data = split(currentString, ",");
for (let i = 0; i < data.length; i++) {
data[i] = Number(data[i]);
}
if (data[0] == 1 && !wasPlaying1) {
for (let i = 0; i < notes1.length; i++) {
synth.noteAttack(notes1[i], 0.6, 0.1, 0.3);
}
wasPlaying = true;
}
if (data[0] == 0 && wasPlaying1) {
wasPlaying = false;
}
if (data[0] == 0 && !wasPlaying1) {
synth.noteRelease();
}
if (data[1] == 1 && !wasPlaying2) {
for (let i = 0; i < notes2.length; i++) {
synth2.noteAttack(notes2[i], 0.6, 0.2, 0.93);
}
wasPlaying = true;
}
if (data[1] == 0 && wasPlaying2) {
wasPlaying = false;
}
if (data[1] == 0 && !wasPlaying2) {
synth2.noteRelease();
}
let vol = mic.getLevel();
vol = round(map(vol, 0.0,1.0, 0,255));
// console.log(data + " mic level: "+ vol);
serial.write(vol);
}
}
}
function draw() {
//background(220);
}
function mousePressed() {
//synth.noteAttack(note, 0.6, 0);
}
function mouseReleased() {
//synth.noteRelease();
playing = false;
}
// We are connected and ready to go
function serverConnected() {
console.log("We are connected!");
}
// Got the list of ports
function gotList(thelist) {
// theList is an array of their names
for (let i = 0; i < thelist.length; i++) {
// Display in the console
console.log(i + " " + thelist[i]);
}
}
// Connected to our serial device
function gotOpen() {
console.log("Serial Port is open!");
}
// Ut oh, here is an error, let's log it
function gotError(theerror) {
console.log(theerror);
}