When I typed in the code in arudino ide, and opened the serial monitor, it always shows lots of ??????????, I checked the circuit and nothing was wrong, so I changed the wires and potentiometer, it works now!
p5 code:
et serial; // variable to hold an instance of the serialport library
let portName = '/dev/tty.usbmodem144301'; // fill in your serial port name here
let inData; // for incoming serial data
// let options = { baudrate: 9600}; // change the data rate to whatever you wish
// serial.open(portName, options);
function setup() {
createCanvas(400, 300);
serial = new p5.SerialPort(); // make a new instance of the serialport library
serial.on('list', printList); // set a callback function for the serialport list event
serial.on('connected', serverConnected); // callback for connecting to the server
serial.on('open', portOpen); // callback for the port opening
serial.on('data', serialEvent); // callback for when new data arrives
serial.on('error', serialError); // callback for errors
serial.on('close', portClose); // callback for the port closing
serial.list(); // list the serial ports
serial.open(portName); // open a serial port
}
function serverConnected() {
console.log('connected to server.');
}
function portOpen() {
console.log('the serial port opened.')
}
function serialEvent() {
inData = Number(serial.read());
}
function serialError(err) {
console.log('Something went wrong with the serial port. ' + err);
}
function portClose() {
console.log('The serial port closed.');
}
function printList(portList) {
// portList is an array of serial port names
for (var i = 0; i < portList.length; i++) {
// Display the list the console:
console.log(i + portList[i]);
}
}
function draw() {
background(0);
fill(255);
text("sensor value: " + inData, 30, 50);
}
arduino code:
void setup() {
Serial.begin(9600); // initialize serial communications
}
void loop() {
// read the input pin:
int potentiometer = analogRead(A0);
// remap the pot value to fit in 1 byte:
int mappedPot = map(potentiometer, 0, 1023, 0, 255);
// print it out the serial port:
Serial.write(mappedPot);
// slight delay to stabilize the ADC:
delay(1);
}