Week 8 Lab: Lab: Two-Way (Duplex) Serial Communication Using An Arduino and the p5.webserial Library

This is was a straightforward lab.

After I got that running, I made a little musical instrument. The button triggers a note, and the potentiometer controls the pitch.

Here’s the code I wrote for it (I also imported the Tone.js script in the HTML file).

function draw() {
  ...
  // write the note text on the circle
  fill("black");
  textSize(20);
  text(note, locH - 12, locV + 7);
}

let synth = new Tone.Synth().toDestination();
let note = "C4";

function serialEvent() {
  ...
  if (inString) {
    if (inString !== "hello") {
      ...
      if (sensors.length > 2) {
        if (sensors[2] == 1) { // if button is pressed, play a note
          if (sensors[0] < 64 * 1) {
            note = "C4";
          } else if (sensors[0] < 64 * 2) {
            note = "D4";
          } else if (sensors[0] < 64 * 3) {
            note = "E4";
          } else if (sensors[0] < 64 * 4) {
            note = "F4";
          } else if (sensors[0] < 64 * 5) {
            note = "G4";
          } else if (sensors[0] < 64 * 6) {
            note = "A4";
          } else if (sensors[0] < 64 * 7) {
            note = "B4";
          } else if (sensors[0] < 64 * 8) {
            note = "C5";
          } else if (sensors[0] < 64 * 9) {
            note = "D5";
          } else if (sensors[0] < 64 * 10) {
            note = "E5";
          } else if (sensors[0] < 64 * 11) {
            note = "F5";
          } else if (sensors[0] < 64 * 12) {
            note = "G5";
          } else if (sensors[0] < 64 * 13) {
            note = "A5";
          } else if (sensors[0] < 64 * 14) {
            note = "B5";
          } else if (sensors[0] < 64 * 15) {
            note = "C6";
          } else if (sensors[0] < 64 * 16) {
            note = "D6";
          }
          synth.triggerAttackRelease(note, "4n");
        }
 ...

Leave a Reply

Your email address will not be published. Required fields are marked *