P5.js to Arduino


task: Make something move, light up, or change in the physical world using output from a P5.js sketch.

my first attempt failed. My p5 didn't responded. 



I realized that I had the p5 code wrong so it worked once I ran the right coding.



// WORKS IN CHROME
// variable to hold an instance of the serialport library
let serial;

// !! fill in your serial port name here
let portName = '/dev/tty.usbmodem24';

// for incoming serial data
let inData;                       

// for outgoing data
let outByte = 0;                     

function setup() {
 createCanvas(400, 300); // make the canvas

 // make a new instance of the serialport library
 serial = new p5.SerialPort(); 

 // callback for when new data arrives
 serial.on('data', serialEvent); 

 // callback for errors
 serial.on('error', serialError);

 // open a serial port
 serial.open(portName);         
}

function serialEvent() {
 // read a byte from the serial port:
 var inByte = serial.read();
 // store it in a global variable:
 inData = inByte;
}

function serialError(err) {
  print('Something went wrong with the serial port. ' + err);
}

function draw() {
 // black background, white text:
 background(0);
 fill(255);
 // display the incoming serial data as a string:
 text("outgoing value: " + outByte, 30, 30);
}

function mouseDragged() {
 // map the mouseY to a range from 0 to 255:
 outByte = int(map(mouseY, 0, height, 0, 255));
 // send it out the serial port:
 serial.write(outByte);
}

function keyPressed() {
 if (key >= 0 && key <= 9) { // if the user presses 0 through 9
 outByte = byte(key * 25); // map the key to a range from 0 to 225
 }
 serial.write(outByte); // send it out the serial port
}



Comments

Popular posts from this blog

Input/Output

Midterm projects, Analog output

FINAL PROJECT