In this lab we are using P5 to control Arduino serially.
We start by programming our board to change LED brightness
if you press “H” for high or “L”for low. It looks like this, in Arduino code:.
constintledPin = 5; // the pin that the LED is attached toint incomingByte; // a variable to read incoming serial data intovoid setup() { Serial.begin(9600); // initialize serial communication pinMode(ledPin, OUTPUT); // initialize the LED pin as an output}void loop() { if (Serial.available() > 0) { // see if there's incoming serial data incomingByte = Serial.read(); // read it if (incomingByte == 'H') { // if it's a capital H (ASCII 72), digitalWrite(ledPin, HIGH); // turn on the LED } if (incomingByte == 'L') { // if it's an L (ASCII 76) digitalWrite(ledPin, LOW); // turn off the LED } }}In P5.js, We can use H and L to control the intensity of the LED by writing
function keyPressed() { if (key ==='H' || key ==='L') { // if the user presses H or L serial.write(key); // send it out the serial port }} |
Here’s the result: