xxxxxxxxxx
89
let serial; // variable for the serial object
let latestData = "waiting for data"; // variable to hold the data
function setup() {
createCanvas(400, 400);
wave = new p5.Oscillator('sine');
wave.amp(0,0);
wave.start();
// serial constructor
serial = new p5.SerialPort();
// get a list of all connected serial devices
serial.list();
// serial port to use - you'll need to change this
serial.open('COM6');
// callback for when the sketchs connects to the server
serial.on('connected', serverConnected);
// callback to print the list of serial devices
serial.on('list', gotList);
// what to do when we get serial data
serial.on('data', gotData);
// what to do when there's an error
serial.on('error', gotError);
// when to do when the serial port opens
serial.on('open', gotOpen);
// what to do when the port closes
serial.on('close', gotClose);
}
function serverConnected() {
console.log("Connected to Server");
}
// list the ports
function gotList(thelist) {
console.log("List of Serial Ports:");
for (let i = 0; i < thelist.length; i++) {
console.log(i + " " + thelist[i]);
}
}
function gotOpen() {
console.log("Serial Port is Open");
}
function gotClose() {
console.log("Serial Port is Closed");
latestData = "Serial Port is Closed";
}
function gotError(theerror) {
console.log(theerror);
}
// when data is received in the serial buffer
function gotData() {
let currentString = serial.readLine(); // store the data in a variable
trim(currentString); // get rid of whitespace
if (!currentString) return; // if there's nothing in there, ignore it
console.log(currentString); // print it out
latestData = currentString; // save it to the global variable
}
function draw() {
background(220);
text(latestData, 10, 10); // print the data to the sketch
mapData = map(latestData, 100, 500, 0.5, 1.5);
//mapData = round(mapData,1);
//wave.freq(1174.66*mapData);
if(latestData >300){
wave.freq(783.99) //G5
}else if(latestData > 200 && latestData < 300){
wave.freq(880.00) //A5
}else{
wave.freq(659.26) //E5
}
//gagE
wave.amp(1,0.5);
}