Button
This chapter will show you how to connect a simple push-button to your Arduino board and trigger an event in JavaScript when the button is pressed or released.
Connecting the Button with p5js
The basic syntax is:
let button = connectSensor( SENSOR_BUTTON, pin );
If you connected a button to the digital pin 2
then you would register the button by writing this:
let button = connectSensor( SENSOR_BUTTON, 2 );
If you would like to call a function when the button is pressed, use the button.pressed( callback )
method:
button.pressed( myPressedFunc )
Same can be done, if the button is released. Use the button.released( callback )
method:
button.released( myReleasedFunc )
To check if the button is currently pressed (e.g. in the draw()
function) you can use:
if (button.isPressed) {
// ... do something
}
// alternative:
if (button.value() == 1) {
// ... do something
}
Hardware
1x 10 kΩ resistor – see colorcode
Wiring

Code
let button;
function setup () {
createCanvas(400, 400);
button = connectSensor( SENSOR_BUTTON, 2 );
button.pressed( buttonPressed );
button.released( buttonReleased );
}
function draw () {
background( 255 );
let size = 50;
if (button.value() == 1) {
size = 20
}
circle( 200, 200, size );
}
function buttonPressed() {
console.log('PRESS');
}
function buttonReleased() {
console.log('RELEASED');
}