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

Introduction

In the Introduction to Asynchronous Serial Communication lab, you learned about various methods for managing the communications between computers via asynchronous serial communication. These included formatting your data as ASCII-encoded strings or raw serial bytes and managing the flow of data using handshaking. In the P5.js WebSerial Input Lab, you sent data from one sensor to a personal computer. In this lab, you’ll send data from multiple sensors to a program in p5.js. using the  p5.WebSerial library. You’ll use the data from the sensors to create a pointing-and-selecting device (i.e. a mouse).

What You Should Know

To get the most out of this tutorial, you should know what a microcontroller is and how to program them. You should also understand asynchronous serial communication between microcontrollers and personal computers. You should also understand the basics of P5.js. It would also help to go through the following labs first:

These videos might help in understanding this lab as well:

Things You’ll Need

For this lab, you’ll need the hardware below, and you’ll need the same software setup as the WebSerial Input to P5.js lab: You’ll create a p5.js sketch. You’ll also use the p5.WebSerial library. You can use the p5.js web editor or your favorite text editor for this (the Visual Studio Code editor works well).

Figures 1-5 below are the parts you’ll need for this exercise. Click on any image for a larger view.

Photo of an Arduino Nano 33 IoT module. The USB connector is at the top of the image, and the physical pins are numbered in a U-shape from top left to bottom left, then from bottom right to top right.
Figure 1. Microcontroller. Shown here is an Arduino Nano 33 IoT
Photo of flexible jumper wires
Figure 2. Jumper wires.  You can also use pre-cut solid-core jumper wires.
Photo of a solderless breadboard
Figure 3. A solderless breadboard
Photo of four breadboard-mounted pushbuttons
Figure 4. A pushbutton
Photo of two potentiometers
Figure 5. two potentiometers. You can use any two analog sensors in place of these if you prefer.

Connect the Sensors

For this exercise, you’re going to need two analog inputs to your microcontroller, and one digital input. It doesn’t matter what they are, so use something that’s easy for you to set up. The photos and schematic in this lab show potentiometers and a pushbutton. You don’t have to use these, though. Any three sensor inputs will do the job. If you’re looking for options, consider:

Photo of a breadboard-mountable joystick, This component is mounted on a printed circuit board that's about 4cm on each side. The joystick itself is about 6cm tall, controllable by a thumb. There are five pins on one side of the PCB for mounting on the breadboard.
Figure 6. A joystick, which consists of two potentiometers and a pushbutton
Photo of a rotary encoder
Figure 7. Rotary encoders, which include a built-in pushbutton
Photo of the IMU sensor on teh Nano 33 IoT. It's the small rectangular chip above and to the left of the main processor.
Figure 8. The built-in accelerometer on the Arduino Nano 33 IoT, which measures acceleration on three axes

As long as you have three sensors that will output changing readings, you can follow this lab.

Connect the two analog sensors to analog pins 0 and 1 like you did in the analog input to Arduino lab. Connect a pushbutton to digital pin 2 like you did in the digital input and output with Arduino lab.

Schematic view of an Arduino attached to two potentiometers and a pushbutton. The potentiometers' center pins are connected to the Arduino's A0 and A1 inputs, respectively.
Figure 9. Schematic view of an Arduino attached to two potentiometers and a pushbutton. The potentiometers’ center pins are connected to the Arduino’s A0 and A1 inputs, respectively. Their left pins are connected to the voltage bus, and the right pins are connected to the ground bus, respectively. The pushbutton is connected from the Arduino’s voltage output to pin D2. a 10-kilohm connects the junction of the switch and pin D2 to ground.
Breadboard view of an Arduino Uno attached to two potentiometers and a pushbutton.
Figure 10. Breadboard view of an Arduino Uno attached to two potentiometers and a pushbutton. The potentiometers’ center pins are connected to the Arduino’s A0 and A1 inputs, respectively. Their left pins are connected to the voltage bus, and the right pins are connected to the ground bus, respectively. The pushbutton is connected from the Arduino’s voltage output to pin D2. a 10-kilohm connects the junction of the switch and pin D2 to ground.

Breadboard view of an Arduino Nano attached to two potentiometers and a pushbutton
Figure 11. Breadboard view of an Arduino Nano attached to two potentiometers and a pushbutton. The potentiometers’ center pins are connected to the Arduino’s A0 and A1 inputs, respectively. Their left pins are connected to the voltage bus, and the right pins are connected to the ground bus, respectively. The pushbutton is connected from the Arduino’s voltage output to pin D2. a 10-kilohm connects the junction of the switch and pin D2 to ground.

(Diagrams made with Fritzing, a circuit design program)


Sending Multiple Serial Data using Punctuation

You’re going to program the microcontroller to read the pushbutton and two analog sensors just like you did in the Intro to Serial Communications Lab. When you have to send multiple data items, you need a way to separate them. If you’re sending them as ASCII-encoded strings, it’s simple: you can just put non-numeric punctuation bytes between them (like a comma or a space) and a unique termination punctuation at the end (like a newline and/or carriage return).

This program will send the two analog sensor values and then the pushbutton. All three will be ASCII-encoded numeric strings, separated by commas. The whole line of sensor values will be terminated by carriage return (\r, ASCII 13) and newline (\n, ASCII 10).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const int buttonPin = 2;      // digital input
 
void setup() {
  // configure the serial connection:
  Serial.begin(9600);
  // configure the digital input:
  pinMode(buttonPin, INPUT);
}
 
void loop() {
  // read the first analog sensor:
  int sensorValue = analogRead(A0);
  // print the results:
  Serial.print(sensorValue);
  Serial.print(",");
 
  // read the second analog sensor:
  sensorValue = analogRead(A1);
  // print the results:
  Serial.print(sensorValue);
  Serial.print(",");
 
  // read the button:
  sensorValue = digitalRead(buttonPin);
  // print the results:
  Serial.println(sensorValue);
}

When you run this and output it to the Serial Monitor, you should see something like this:

348,363,1
344,362,1
345,363,1
344,375,0
365,374,0
358,369,0
355,369,0
352,373,0
356,373,0

Turn the potentiometers (or tweak the analog sensors) and push the button. Now you’ve got a data format: three sensors, comma-separated, terminated by carriage return and newline. This means that you already have an algorithm for how you’re going to program p5.js to read the serial input. You’ll see that algorithm in the next section.

Receive the data in P5.js

Now write a P5.js sketch that reads the data as formatted by the Arduino program above. The setup will be the same as it was in the Serial Input to p5.js using WebSerial lab. The checklist from that lab lays out all the important parts you need.

The sketch you’re going to write will:

  • Read the incoming serial data into a string until a carriage return and newline appear
  • split the string into substrings on the commas
  • convert the substrings into numbers
  • assign the numbers to variables to change your programNow that you’ve got a plan, put it into action.

Make a P5.js sketch. If you’re using the p5.js web editor, make a new sketch. Click the Sketch Files tab, and then choose the index.html file. Edit the head of the document as you did for the other p5.webserial labs. It should look like this:

The setup of your sketch will initialize the P5.webserial library and define your callback functions for serial events as you did in other sketches. It should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// variable to hold an instance of the p5.webserial library:
const serial = new p5.WebSerial();
 
// HTML button object:
let portButton;
let inData;                      // for incoming serial data
let outData;                     // for outgoing data
 
function setup() {
  createCanvas(400, 300);          // make the canvas
  // check to see if serial is available:
  if (!navigator.serial) {
    alert("WebSerial is not supported in this browser. Try Chrome or MS Edge.");
  }
  // if serial is available, add connect/disconnect listeners:
  navigator.serial.addEventListener("connect", portConnect);
  navigator.serial.addEventListener("disconnect", portDisconnect);
  // check for any ports that are available:
  serial.getPorts();
  // if there's no port chosen, choose one:
  serial.on("noport", makePortButton);
  // open whatever port is available:
  serial.on("portavailable", openPort);
  // handle serial errors:
  serial.on("requesterror", portError);
  // handle any incoming serial data:
  serial.on("data", serialEvent);
  serial.on("close", makePortButton);
}
function draw() {
 
}
 
// if there's no port selected,
// make a port select button appear:
function makePortButton() {
  // create and position a port chooser button:
  portButton = createButton('choose port');
  portButton.position(10, 10);
  // give the port button a mousepressed handler:
  portButton.mousePressed(choosePort);
}
 
// make the port selector window appear:
function choosePort() {
  serial.requestPort();
}
 
// open the selected port, and make the port
// button invisible:
function openPort() {
  // wait for the serial.open promise to return,
  // then call the initiateSerial function
  serial.open().then(initiateSerial);
 
  // once the port opens, let the user know:
  function initiateSerial() {
    console.log("port open");
  }
  // hide the port button once a port is chosen:
  if (portButton) portButton.hide();
}
 
// read any incoming data as a byte:
function serialEvent() {
  
}
 
// pop up an alert if there's a port error:
function portError(err) {
  alert("Serial port error: " + err);
}
 
// try to connect if a new serial port
// gets added (i.e. plugged in via USB):
function portConnect() {
  console.log("port connected");
  serial.getPorts();
}
 
// if a port is disconnected:
function portDisconnect() {
  serial.close();
  console.log("port disconnected");
}

Change the serialEvent() function to read the incoming serial data as a string until it encounters a carriage return and newline (“\r\n”). Then check to see that the resulting string has a length greater than 0 bytes. If it does, use the split() function to split it in to an array of strings. If the resulting array is at least three elements long, you have your three sensor readings. The first reading is the first analog sensor, and can be mapped to the horizontal movement using the locH variable. The second is the second analog sensor and can be mapped to the locV variable. The third is the button. When it’s 0, set the circleColor variable equal to 255 and when it’s 1, set the variable to 0. Here’s how:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function serialEvent() {
  // read a string from the serial port
  // until you get carriage return and newline:
  var inString = serial.readStringUntil("\r\n");
  //check to see that there's actually a string there:
  if (inString) {
    // split the string on the commas:
    var sensors = split(inString, ",");
    if (sensors.length > 2) {
      // if there are three elements
      // element 0 is the locH:
      locH = map(sensors[0], 0, 1023, 0, width);
      // element 1 is the locV:
      locV = map(sensors[1], 0, 1023, 0, height);
      // element 2 is the button:
      circleColor = 255 - sensors[2] * 255;
    }
  }
}

Note the mappings of sensors[0] and sensors[1]. If you’re not using potentiometers as the first two inputs on your Arduino, then you should use the input mappings for your sensors instead of 0 and 1023. If your analog values are greater than the width of the sketch or the height, the circle will be offscreen, which is why you have to map your sensor range to the screen size.

Program the draw() function to draw a circle that’s dependent on three global variables, locH, locV, and circleColor. Add these three globals to the top of the program:

1
2
3
// variables for the circle to be drawn:
let locH, locV;
let circleColor = 255;

Finally, here is the draw function:

1
2
3
4
5
function draw() {
  background(0);               // black background
  fill(circleColor);           // fill depends on the button
  ellipse(locH, locV, 50, 50); // draw the circle
}

If you run this, you should see the circle moving onscreen whenever you change your sensors. When you press the pushbutton, the circle will disappear. Okay, it’s not exactly a  mouse, but you are controlling an animation from a device that you built.

Flow Control: Call and Response (Handshaking)

You’ve seen now that by coming up with a serial format (called a protocol), you can write the algorithm for receiving it even before you see any data. You can send multiple pieces of data this way, as long as you format it consistently.

Sometimes you can run into a problem when the sender sends faster than the receiver can read. When this happens, the receiver program slows down as the serial buffer fills up. You can manage this by implementing some form of flow control. The simplest way do to this is using a call-and-response method, where the sending program only sends when it’s told to do so, and the receiving program has to request new data every time it finishes reading what it’s got.

You can add handshaking to the code above fairly simply. Modify the Arduino code as follows. First, add a a new block of code in the setup() This block sends out a message until it gets a byte of data from the remote computer:

1
2
3
4
5
6
7
void setup() {
  Serial.begin(9600);
  while (Serial.available() <= 0) {
    Serial.println("hello"); // send a starting message
    delay(300);              // wait 1/3 second
  }
}

Now, modify the loop() by adding an if() statement to look for incoming serial data and read it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void loop() {
  if (Serial.available() > 0) {
    // read the incoming byte:
    int inByte = Serial.read();
    // read the sensor:
    int sensorValue = analogRead(A0);
    // print the results:
    Serial.print(sensorValue);
    Serial.print(",");
 
    // read the sensor:
    sensorValue = analogRead(A1);
    // print the results:
    Serial.print(sensorValue);
    Serial.print(",");
 
    // read the sensor:
    sensorValue = digitalRead(buttonPin);
    // print the results:
    Serial.println(sensorValue);
  }
}

The rest of the sketch remains the same. When you run this and open the serial monitor, you’ll see:

hello
hello
hello
hello

Type any character in the output box and click Send. You’ll get a string of sensor values at the end of your hellos:

510,497,0

Type another character and click Send. It doesn’t matter what character you send, but the loop will always wait for an incoming byte before sending a new set of sensor values. When you write a program to receive this format, it just has to behave the same way you did:

  • Open the serial port
  • Wait for a hello
  • Send a byte to request data
  • Begin loop:
  • Wait for one set of data
  • Send a byte to request new data
  • end loop

Next, modify the P5.js sketch.  Most of the changes are in the serialEvent() function. The initial “hello” messages will trigger this function, so when you get a “hello” or any other string, you need to send a byte back so that the Arduino has a byte available to read. Here’s the new serialEvent():

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function serialEvent() {
  // read a string from the serial port
  // until you get carriage return and newline:
  var inString = serial.readStringUntil("\r\n");
  //check to see that there's actually a string there:
  if (inString) {
    if (inString !== "hello") {
      // if you get hello, ignore it
      // split the string on the commas:
      var sensors = split(inString, ",");
      if (sensors.length > 2) {
        // if there are three elements
        // element 0 is the locH:
        locH = map(sensors[0], 0, 1023, 0, width);
        // element 1 is the locV:
        locV = map(sensors[1], 0, 1023, 0, height);
        // element 2 is the button:
        circleColor = 255 - sensors[2] * 255;
        // send a byte back to prompt for more data:
        serial.print('x');
      }
    }
  }
}

You also need to add a line to the initiateSerial() function (which is inside the openPort() function) like so:

1
2
3
4
5
function initiateSerial() {
   console.log("port open");
   // send a byte to start the microcontroller sending:
   serial.print("x");
 }

The reason for this is that if your Arduino is still in the setup() waiting for a byte to arrive, then it needs p5.js to send something when the port is opened. If the Arduino has already broken out of the loop (let’s say you opened the Serial monitor to check), then it is waiting for a byte from p5.js to send the next block of code. Whether it’s in the initiateSerial() function or at the end of the serialEvent() function, by sending a byte when you know the port has just been opened in p5.js, you force the Arduino to send you new data.

That’s it. Your sketch should still run just as it did before, though the serial communication is managed better now, because Arduino’s only sending when P5.js is ready to receive.

You can see the sketch running on GitHub at this link. You can see the source files for copying into the p5.js editor at this link.

Advantages of Raw Binary vs. ASCII

All the examples shown here sent the sensor values as ASCII-encoded strings. As mentioned above, that means you sent three bytes to send a three-digit value. If that same value was less than 255, you could send it in one raw binary byte. So ASCII is definitely less efficient. However, it’s more readable for debugging purposes, and if the receiving program is well-suited to convert strings to numbers, then ASCII is a good way to go. If the receiver’s not so good at converting strings to numbers (for example, it’s more challenging to read a multiple byte string in Arduino than in Processing) then you may want to send your data as binary values.

Advantages of Punctuation or Call-and-Response

The punctuation method for sending multiple serial values may seem simpler, but it has its limitations. You can’t easily use it to send binary values, because you need to have a byte with a unique value for the punctuation. In the example above, you’re using the value 10 (ASCII newline) as punctuation, so if you were sending your sensor values as raw bytes, you’d be in trouble when the sensor’s value is 10. The receiver would interpret the 10 as punctuation, not as a sensor value. In contrast, call-and-response can be used whether you’re sending data as raw binary values or as ASCII-encoded values.

Sometimes the receiver reads serial data slower than the sender sends it. For example, if you have a program that does a lot of graphic work, it may only read serial data every few milliseconds. The serial buffer will get full in that case, you’ll notice a lag in response time. This is when it’s good to switch to a call-and-response method.

Build an Application of Your Own

You just duplicated the basic functionality of a mouse; that is, a device with two analog sensors that affect X and Y, and a digital sensor (mouse button). What applications can you think of that could use a better physical interface for a mouse? A video editor that scrubs forward and back when you tilt a wand? An action game that reacts to how hard you hit a punching bag? An instructional presentation that speeds up if you shift in your chair too much? A music program driven by a custom musical instrument that you design?

Create a prototype in Arduino and P5.js, Node.js, Processing, or whatever programming environment you choose. Come up with a physical interface that makes it clear what actions map to what movements and actions. Figure out which actions can and should be possible at the same time. Present a working software and hardware model of your idea.

Lab: Serial Output From p5.js Using the p5.webserial Library

In this lab you’ll learn how to send data from p5.js to a microcontroller using asynchronous serial communication.

Overview

When you use the p5.webserial library for P5.js, it uses the W3C’s WebSerial API to allow your browser to communicate with serial ports on your computer. This lab shows you how to use P5 to control a microcontroller using asynchronous serial communication. WebSerial is currently only available in the Chrome and Chromium browsers and the Microsoft Edge browser, so make sure you’re using one of those to do this lab.

To get the most out of this tutorial, you should know what a microcontroller is and how to program them. You should also understand asynchronous serial communication between microcontrollers and personal computers. You should also understand the basics of P5.js, and should have tried the WebSerial Input to P5.js lab.

Things You’ll Need

For this lab, you’ll need the hardware below,

For this lab, you’ll need the hardware below, and you’ll need the same software setup as the WebSerial Input to P5.js lab: You’ll create a p5.js sketch. You’ll also use the p5.WebSerial library. You can use the p5.js web editor or your favorite text editor for this (the Visual Studio Code editor works well).

Photo of an Arduino Nano 33 IoT module. The USB connector is at the top of the image, and the physical pins are numbered in a U-shape from top left to bottom left, then from bottom right to top right.
Figure 1. Microcontroller.  Arduino Nano 33 IoT
LEDs. Shown here are four LEDs. The one on the right is an RGB LED. You can tell this because it has four legs, while the others have only two legs.
Figure 2. LEDs. Shown here are four LEDs. The one on the right is an RGB LED. You can tell this because it has four legs, while the others have only two legs.
Resistors. Shown here are 220-ohm resistors. You can tell this because they have two red and one brown band, followed by a gold band.
Figure 3. Resistors. Shown here are 220-ohm resistors. You can tell this because they have two red and one brown band, followed by a gold band.
An 8 ohm speaker with 2 wires solder to the speakers leads
Figure 4. An 8 ohm speaker (optional).This is a good alternate to the LED if you prefer audible output.

Prepare the breadboard

Connect power and ground on the breadboard to power and ground from the microcontroller. On the Arduino Uno, use the 5V and any of the ground connections. On the Nano, use 3.3V and the ground connections:

An Arduino Uno on the left connected to a solderless breadboard, right. The Uno's 5V output hole is connected to the red column of holes on the far left side of the breadboard. The Uno's ground hole is connected to the blue column on the left of the board. The red and blue columns on the left of the breadboard are connected to the red and blue columns on the right side of the breadboard with red and black wires, respectively. These columns on the side of a breadboard are commonly called the buses. The red line is the voltage bus, and the black or blue line is the ground bus.
Figure 5. An Arduino Uno on the left connected to a solderless breadboard, right.
Arduino Nano on a breadboard.
Figure 6. Breadboard view of an Arduino Nano mounted on a breadboard.

The +3.3 volts and ground pins of the Arduino Nano are connected by red and black wires(Figure 6), respectively, to the left side rows of the breadboard. +3.3 volts is connected to the left outer side row (the voltage bus) and ground is connected to the left inner side row (the ground bus). The side rows on the left are connected to the side rows on the right using red and black wires, respectively, creating a voltage bus and a ground bus on both sides of the board.Figure 5. Breadboard view of an Arduino Nano connected to a breadboard. The +3.3 volts and ground pins of the Arduino are connected by red and black wires, respectively, to the left side rows of the breadboard. +3.3 volts is connected to the left outer side row (the voltage bus) and ground is connected to the left inner side row (the ground bus). The side rows on the left are connected to the side rows on the right using red and black wires, respectively, creating a voltage bus and a ground bus on both sides of the board.

Made with Fritzing

Add an LED

Connect the LED and resistor to digital I/O pin 11 of the module(Figure 7-8). Alternately, you can replace the 220-ohm LED with a speaker (Figure 9-10). You’ll find code below that uses tones instead of LEDs where appropriate. For more on how to do that, see the Tone Output lab:

Schematic view of an Arduino connected to an LED. Digital pin 5 is connected to a 22-ohm resistor. The other side of the resistor is connected to the anode (long leg) of an LED. The cathode of the LED is connected to ground.
Figure 7. Schematic view of an Arduino connected to an LED.
Breadboard view of an Arduino connected to an LED. The +5 volts and ground pins of the Arduino are connected by red and black wires, respectively, to the left side rows of the breadboard. +5 volts is connected to the left outer side row (the voltage bus) and ground is connected to the left inner side row (the ground bus). The side rows on the left are connected to the side rows on the right using red and black wires, respectively, creating a voltage bus and a ground bus on both sides of the board. A blue wire connects Digital to a 22-ohm resistor that straddles the center divide of the breadboard in row 17. The other side of the resistor is connected to the anode (long leg) of an LED. The LED is mounted in rowsd 16 and 17 of the right side of the center section of the board. a black wire connects the cathode's row, row 16, to the ground bus on the right side of the board.
Figure 8. Breadboard view of an Arduino connected to an LED.

Breadboard view of an LED connected to digital pin 5 of an Arduino Nano.
Figure 9. Breadboard view of an LED connected to digital pin 5 of an Arduino Nano.

Figure 9 shows a breadboard view of an LED connected to digital pin 5 of an Arduino Nano. The Nano straddles the center of the breadboard in the first fifteen rows. The Nano’s voltage pin (physical pin 2) connects to the board’s voltage bus, and the Nano’s ground pin (physical pin 14) connects to the board’s ground bus. The LED is in the right center of the board, with its anode in one row and the cathode in the next. A 220-ohm resistor connects the LED’s anode to a wire connecting to digital pin 5. The LED’s cathode is connected to the ground bus.

Breadboard view of an Arduino Nano connected to two force sensing resistors (FSRs) and a speaker. The Nano’s 3.3 Volts (physical pin 2) and ground (physical pin 14) are connected to the voltage and ground buses of the breadboard as usual. The red positive wire of the speaker is connected to digital pin 5 of the Arduino. The black ground wire of the speaker is connected to one leg of a 100 ohm resistor. The other leg of the resistor connects to ground.
Figure 10. Breadboard view of an Arduino Nano connected to a speaker to digital pin 5.

Figure 10 shows a breadboard view of an Arduino Nano connected to a speaker. The Nano’s ground (physical pin 14) is connected to the ground bus of the breadboard as usual. The red positive wire of the speaker is connected to digital pin 5 of the Arduino. The black ground wire of the speaker is connected to one leg of a 100 ohm resistor. The other leg of the resistor connects to ground.

Program the Microcontroller

Program your Arduino to read the analog input as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void setup() {
  Serial.begin(9600);     // initialize serial communications
  pinMode(5, OUTPUT);
}
 
void loop() {
  if (Serial.available() > 0) { // if there's serial data available
    int inByte = Serial.read();   // read it
    Serial.write(inByte);         // send it back out as raw binary data
    analogWrite(5, inByte);       // use it to set the LED brightness
    // if you're using a speaker instead of an LED, uncomment line below  and comment out the previous line:
    //  tone(5, inByte*10);     // play tone on pin 5
  }
}

Only one port at a time can access a serial port.

As you work on this any microcontroller-to-computer application, you will be switching back and forth between the app that programs the microcontroller (in this case, the Arduino IDE) and the app that the microcontroller is communicating with (in this case, p5.js in the browser). You have to keep in mind that only one of these at a time can access a serial port.

That means that when you want to reprogram your Arduino from the Arduino IDE, you should to stop your sketch in the browser window to do so. Then, restart the browser sketch when you’re done reprogramming the Arduino. You don’t need to quit the Arduino IDE each time, because it knows to release the serial port when it’s not programming. However, you do need to close the Serial Monitor in the Arduino IDE when you are using WebSerial in the browser.

The P5.js WebSerial Library

To communicate with your microcontroller serially, you’re going to use the P5.js WebSerial library. If you’re using the p5.js web editor, make a new sketch. Click the Sketch Files tab, and then choose the index.html file. In the head of the document, look for this line:

Right after that line, add this line:

The P5.js Sketch

The sketch you’re going to write will control the microcontroller’s LED from P5.js. Dragging the mouse up and down the canvas will dim or brighten the LED, and typing 0 through 9 will set the LED’s brightness in increments from off (0) through almost full brightness (9). There’s an alternate sketch that will make changing tones if you prefer that instead of a changing LED. The sketch will also receive serial input from the microcontroller just as in the WebSerial Input to P5.js lab, so that you can see that the microcontroller is getting the same values you’re sending.

The setup of your sketch will initialize the P5.webserial library and define your callback functions for serial events. Program the global variables and setup() function as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// variable to hold an instance of the p5.webserial library:
const serial = new p5.WebSerial();
 
// HTML button object:
let portButton;
let inData;                            // for incoming serial data
let outByte = 0;                       // for outgoing data
 
function setup() {
  createCanvas(400, 300);          // make the canvas
  // check to see if serial is available:
  if (!navigator.serial) {
    alert("WebSerial is not supported in this browser. Try Chrome or MS Edge.");
  }
  // if serial is available, add connect/disconnect listeners:
  navigator.serial.addEventListener("connect", portConnect);
  navigator.serial.addEventListener("disconnect", portDisconnect);
  // check for any ports that are available:
  serial.getPorts();
  // if there's no port chosen, choose one:
  serial.on("noport", makePortButton);
  // open whatever port is available:
  serial.on("portavailable", openPort);
  // handle serial errors:
  serial.on("requesterror", portError);
  // handle any incoming serial data:
  serial.on("data", serialEvent);
  serial.on("close", makePortButton);
}
 
function draw() {
 
}

For now you’re leaving the draw() function empty. You’ll fill it in later. You’ll be adding some functions to read mouse dragging and key pressing as well.

Program the handler functions similarly to those in the WebSerial Input to P5.js lab:

55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
// if there's no port selected,
// make a port select button appear:
function makePortButton() {
  // create and position a port chooser button:
  portButton = createButton("choose port");
  portButton.position(10, 10);
  // give the port button a mousepressed handler:
  portButton.mousePressed(choosePort);
}
 
// make the port selector window appear:
function choosePort() {
  serial.requestPort();
}
 
// open the selected port, and make the port
// button invisible:
function openPort() {
  // wait for the serial.open promise to return,
  // then call the initiateSerial function
  serial.open().then(initiateSerial);
 
  // once the port opens, let the user know:
  function initiateSerial() {
    console.log("port open");
  }
  // hide the port button once a port is chosen:
  if (portButton) portButton.hide();
}
 
// read any incoming data as a byte:
function serialEvent() {
  // read a byte from the serial port:
  var inByte = serial.read();
  // store it in a global variable:
  inData = inByte;
}
 
// pop up an alert if there's a port error:
function portError(err) {
  alert("Serial port error: " + err);
}
 
// try to connect if a new serial port
// gets added (i.e. plugged in via USB):
function portConnect() {
  console.log("port connected");
  serial.getPorts();
}
 
// if a port is disconnected:
function portDisconnect() {
  serial.close();
  console.log("port disconnected");
}
 
function closePort() {
  serial.close();
}

Program the  draw() function to display the value of any incoming serial bytes. Here it is:

31
32
33
34
35
36
37
function draw() {
  // black background, white text:
  background(0);
  fill(255);
  // display the incoming serial data as a string:
  text("incoming value: " + inData, 30, 30);
}

To read the mouse and keyboard, you’ll need to write functions to respond to the ‘mouseDragged’ and ‘keyPressed’ events. ‘MouseDragged’ will happen whenever you click and drag the mouse on the canvas. When that happens, read the mouseY, and map its position on the canvas to a value from 0 to 255. Convert the result to a number using the int() function. Then send it out the serial port using the serial.write() function:

39
40
41
42
43
44
function mouseDragged() {
  // map the mouseY to a range from 0 to 255:
  outByte = byte(map(mouseY, 0, height, 0, 255));
  // send it out the serial port:
  serial.write(outByte);
}

The serial.write() function is versatile. If you give it a variable or literal that’s a numeric data type, it will send it as its raw binary value. In the code above, note how you’re converting the output of the map() function to a number using the int() function.  If you give it a string, however, it will send out that ASCII string. So be aware of the difference, and make sure you know whether your serial receiving device wants raw binary or ASCII-encoded data.

Program the keyPressed() function similarly to the mouseDragged() function. You want it to read the key strokes, convert them to raw bytes, and send them out the serial port. But you only want to send them if they key hit was 0 through 9. The P5.js variable key returns a numeric value, so you can do math on it and convert it like so:

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

That’s all you want your sketch to do, so try running it now. You should see that the initial incoming serial value is undefined, but when you drag the mouse up and down, or type 0 through 9, it will update when the Arduino program returns what it received. The LED will also change with these actions.

You can see this sketch running on gitHub at this link. You can get the full text of it at this link.

Sending ASCII-Encoded Serial Data

When you send data from p5.js using p5.webserial, the serial.write() function works like it does in Arduino: it sends numbers as binary data. In the programs above, you’re sending binary data from p5.js and reading it as binary in Arduino.

If you want to send ASCII-encoded serial data from P5.js instead, all you have to do is to serial.print() or serial.println() your string. On the Arduino side, you can read single characters one byte at a time simply as well. However, if you want to convert multi-byte number strings to numeric values, you’ll need a new function to read ASCII encoded numeric strings called parseInt().

Program the Microcontroller Again

To start off with, load a sketch from the Arduino examples called PhysicalPixel. You can find it in the File Menu -> Examples -> Communication -> PhysicalPixel. Here’s what it looks like. Change the LED pin number to pin 5 as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const int ledPin = 5; // the pin that the LED is attached to
int incomingByte;     // a variable to read incoming serial data into
 
void 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 you're using a speaker instead of an LED, uncomment line below  and comment out the previous line:
      //  tone(5, 440);           // play middle A on pin 5
    }
    if (incomingByte == 'L') {    // if it's an L (ASCII 76)
      digitalWrite(ledPin, LOW);  // turn off the LED
      // if you're using a speaker instead of an LED, uncomment line below  and comment out the previous line:
      // noTone(5);
    }
  }
}

When you run this, open the serial monitor and type H or L, and the LED will go on or off.  Try typing h or l instead. The LED won’t change, because H and h have different ASCII values, as do L and l. But you can see from this that you don’t need to memorize the ASCII chart to check for character values in your code. Put the character you want to read in single quotes, and the Arduino compiler will automatically convert the character to its ASCII value for you. It only works for single characters, though.

Program P5.js To Control the LED

To get P5.js to control this Arduino program serially, you only need to add to the keyPressed() function to read H or L in addition to 0 through 9. Here’s your new mousePressed() function:

1
2
3
4
5
6
7
8
9
10
11
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
  }
  if (key === "H" || key === "L") {
    // if the user presses H or L
    serial.write(key); // send it out the serial port
  }
}

Because the key is already a single character, P5.js sends it out as is, and Arduino reads it as a single byte, looking for the ASCII value of H or L. Notice how the values returned to P5.js are 72 and 76, the ASCII values for H and L. For single characters like this, exchanging data is simple.

If you tried to change the LED with the mouse, you didn’t see anything happen unless your output value was 72 or 76. Why is that?

To see the sketch running on GitHub at this link. You can see the source files for copying into the p5.js editor at this link.

Processing ASCII-Encoded Strings With Arduino

It is also possible to read and interpret ASCII-encoded strings in Arduino. The String.parseInt() function reads an incoming string until it finds a non-numeric character, then converts the numeric string that it read into a long integer. This is a blocking function, meaning that String.parseInt() stops the program and does nothing until it sees a non-numeric character, or until a timeout passes. The timeout is normally one second (or 1000 milliseconds), but you can set it to a lower number of milliseconds using Serial.setTimeout(). Here’s a variation on the original Arduino sketch from above, using Serial.parseInt() this time:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void setup() {
  Serial.begin(9600);    // initialize serial communications
  Serial.setTimeout(10); // set the timeout for parseInt
  pinMode(5, OUTPUT);
}
 
void loop() {
  if (Serial.available() > 0) { // if there's serial data available
    int inByte = Serial.parseInt(); // read it
    if (inByte > 0) {
      Serial.write(inByte);      // send it back out as raw binary data
      analogWrite(5, inByte);    // use it to set the LED brightness
      // if you're using a speaker instead of an LED, uncomment line below  and comment out the previous line:
      //  tone(5, inByte*10);     // play tone on pin 5
    }
  }
}

Upload this to your microcontroller, then open the Serial Monitor and send in some ASCII numeric strings. You’ll see the character that’s represented by the string’s value. For example, 65 will return A, 34 will return “, and so forth.Notice that this version of the sketch has a conditional statement to check if the incoming byte is 0. This is because of a quirk of the parseInt() function. It returns 0 if the timeout is hit, or if the string is legitimately 0. This means you can’t really parse for a string like this: "0\n".

Program p5.js To Send a String

Now that your microcontroller is expecting a string, program P5.js to send one. This means changing the mouseDragged() function. Program it to print a string with a newline at the end using the serial.println() command like so:

1
serial.println(outByte);

Since the newline added at the end by serial.println() is a non-numeric character, the Serial.parseInt() function will see it and parse the string, not waiting for the timeout.

To see the sketch running on GitHub at this link. You can see the source files for copying into the p5.js editor at this link.

Conclusion

When you’re sending data between two computers using asynchronous serial communication, you have to make sure that what the sender is sending is formatted the same as what the receiver is listening for. See Table 1 to review what are suitable data formats for different types/sizes of data and which functions to use on p5.js and Arduino for serial communication.

Number of Bytes
1 Byte
Multi Bytes
Data to Send
A single number < 255
A single character
A single number > 255, multiple values
Send as:
Binary
Ascii
Ascii
p5.js ->
serial.write(integer)
serial.write(string)
serial.write
(valueToSend + ",")
-> Arduino
Serial.read()
Serial.parseInt()

Table 1. Serial Communication: p5.js to Arduino

Think this out in advance before you code, then consider what functions you’ve got on both computers to convert data from strings to raw binary numbers and back. Test with fixed values at first, so you know you’re getting what you think you should. For example, sending an ASCII-encoded numeric string like this:

1023\n

Will always result in these six bytes:

49 48 50 51 10

Likewise, this text string:

Hello\n

will always be:

72 101 108 108 111 10

By sending a string you know both the ASCII and raw binary representations of, you can test your code easier, because what you’re sending won’t change. Once you know the sending and receiving works, then you can send variable strings.

The more you work with serial data, the more you’ll become familiar with the methods for handling it.

For more on serial flow control in P5.js, see the Two-Way Duplex Serial Communication Using p5.WebSerial Lab.

Lab: Serial Input to p5.js Using the p5.webserial Library

This lab uses a p5.js library called p5.WebSerial to make it easy in p5.js. In this lab, you’ll generate an analog output value from a potentiometer, then send that value via asynchronous serial communication to P5.js. You’ll use that value in P5.js to draw a graph.

Web browsers have traditionally been designed to be separate from the rest of a computer’s operating system, not able to connect to the computer’s hardware ports for security reasons. Recently, however, the W3C developed the WebSerial API in JavaScript, which allows browsers to communicate with a computer’s serial ports. WebSerial is currently only available in the Chrome and Chromium browsers and the Microsoft Edge browser, so make sure you’re using one of those to do this lab.

To get the most out of this tutorial, you should know what a microcontroller is and how to program them. You should also understand asynchronous serial communication between microcontrollers and personal computers. You should also understand the basics of P5.js.

Once you gain an understanding of serial communication, you can use any program that can connect with your computer’s serial ports to communicate with a microcontroller. In addition to the WebSerial API you’ll see here, you can use other programming environments to communicate serially. Processing, Max/MSP, and OpenFrameworks are three other popular multimedia programming environments that can communicate via the serial ports. You can also do this with Unity, Unreal, or any other programming environment that can access the serial ports.

Things You’ll Need

For this lab, you’ll need the hardware below, and you’ll need to create a p5.js sketch. You’ll also use the p5.WebSerial library. You can use the p5.js web editor or your favorite text editor for this (the Visual Studio Code editor works well).

Figures 1-4 below show the parts you’ll need for this exercise. Click on any image for a larger view.

Photo of an Arduino Nano 33 IoT module. The USB connector is at the top of the image, and the physical pins are numbered in a U-shape from top left to bottom left, then from bottom right to top right.
Figure 1. Microcontroller. Shown here is an Arduino Nano 33 IoT
Photo of flexible jumper wires
Figure 2. Jumper wires.  You can also use pre-cut solid-core jumper wires.
Photo of a solderless breadboard
Figure 3. A solderless breadboard
Photo of two potentiometers
Figure 4. Potentiometer

Prepare the Breadboard

For this exercise you’re going to attach a potentiometer as an analog input to your microcontroller, and send the sensor’s reading serially to p5.js via the p5.serialcontrol app.

Connect power and ground on the breadboard to the microcontroller. On the Arduino module, use the 5V or 3.3V (depending on your model) and any of the ground connections. Figures 5 and 6 show connections for an Arduino Uno and a Nano, respectively.

An Arduino Uno on the left connected to a solderless breadboard, right. The Uno's 5V output hole is connected to the red column of holes on the far left side of the breadboard. The Uno's ground hole is connected to the blue column on the left of the board. The red and blue columns on the left of the breadboard are connected to the red and blue columns on the right side of the breadboard with red and black wires, respectively. These columns on the side of a breadboard are commonly called the buses. The red line is the voltage bus, and the black or blue line is the ground bus.
Figure 5. An Arduino Uno on the left connected to a solderless breadboard, right.

The Uno’s 5V output hole is connected to the red column of holes on the far left side of the breadboard (Figure 5). The Uno’s ground hole is connected to the blue column on the left of the board. The red and blue columns on the left of the breadboard are connected to the red and blue columns on the right side of the breadboard with red and black wires, respectively. These columns on the side of a breadboard are commonly called the buses. The red line is the voltage bus, and the black or blue line is the ground bus.


Arduino Nano on a breadboard.
Figure 6. Breadboard view of an Arduino Nano mounted on a breadboard.

Images made with Fritzing, a circuit drawing application

The Nano is mounted at the top of the breadboard (Figure 6), straddling the center divide, with its USB connector facing up. The top pins of the Nano are in row 1 of the breadboard.

The Nano, like all Dual-Inline Package (DIP) modules, has its physical pins numbered in a U shape, from top left to bottom left, to bottom right to top right. The Nano’s 3.3V pin (physical pin 2) is connected to the left side red column of the breadboard. The Nano’s GND pin (physical pin 14) is connected to the left side black column. These columns on the side of a breadboard are commonly called the buses. The red line is the voltage bus, and the black or blue line is the ground bus. The blue columns (ground buses) are connected together at the bottom of the breadboard with a black wire. The red columns (voltage buses) are connected together at the bottom of the breadboard with a red wire.


Add a Potentiometer

Connect a potentiometer to analog in pin 0 of the module. Figure 7 shows the schematic and figures 8 and 9 show the potentiometer connected to an Arduino and Nano, respectively.

Schematic view of a potentiometer. First leg of the potentiometer is connected to +5 volts. The second leg connected to analog in 0 of the Arduino. The third leg is connected to ground.
Figure 7. Schematic view of a potentiometer connected to analog in 0 of the Arduino
Breadboard view of a potentiometer. First leg of the potentiometer is connected to +5 volts. The second leg connected to analog in 0 of the Arduino. The third leg is connected to ground.
Figure 8. Breadboard view of a potentiometer connected to analog in 0 of an Arduino. The potentiometer is connected to three rows in the left center section of the breadboard. The two outside pins are connected to voltage and ground. The center pin is connected to the Arduino’s analog in 0.

Breadboard view of Arduino Nano with an potentiometer input.
Figure 9. Breadboard view of a potentiometer connected to analog in 0 of an Arduino Nano. The Nano is connected as usual, straddling the first fifteen rows of the breadboard with the USB connector facing up. Voltage (physical pin 2) is connected to the breadboard’s voltage bus, and ground (physical pin 14) is connected to the breadboard’s ground bus. The potentiometer is connected to three rows in the left center section of the breadboard. The two outside pins are connected to voltage and ground. The center pin is connected to the Nano’s analog in 0.

Program the Microcontroller

Program your Arduino to read the analog input as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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);                                           
}

Only one port at a time can access a serial port.

As you work on this any microcontroller-to-computer application, you will be switching back and forth between the app that programs the microcontroller (in this case, the Arduino IDE) and the app that the microcontroller is communicating with (in this case, p5.js in the browser). You have to keep in mind that only one of these at a time can access a serial port.

That means that when you want to reprogram your Arduino from the Arduino IDE, you should to stop your sketch in the browser window to do so. Then, restart the browser sketch when you’re done reprogramming the Arduino. You don’t need to quit the Arduino IDE each time, because it knows to release the serial port when it’s not programming. However, you do need to close the Serial Monitor in the Arduino IDE when you are using WebSerial in the browser.

The P5.js WebSerial Library

To communicate with your microcontroller serially, you’re going to use the P5.js WebSerial library. If you’re using the p5.js web editor, make a new sketch. Click the Sketch Files tab, and then choose the index.html file. In the head of the document, look for this line:

Right after that line, add this line:

The p5.js Sketch

To start off, you need to know if WebSerial is supported in the browser you’re using. Open the sketch.js file and change it to the following:

1
2
3
4
5
6
7
8
9
// variable to hold an instance of the p5.webserial library:
const serial = new p5.WebSerial();
 
function setup() {
   // check to see if serial is available:
   if (!navigator.serial) {
    alert("WebSerial is not supported in this browser. Try Chrome or MS Edge.");
  }
}

When you run this p5.js sketch in a browser, you’ll get a message letting you know whether or not this browser supports WebSerial. In a browser that supports WebSerial, you may want to delete the else clause.

Serial Events

JavaScript, the language on which p5.js is based, relies heavily on events and callback functions. An event is generated by the operating system when something significant happens, like a serial port opening, or new data arriving in the port. In your sketch, you write a callback function to respond to that event. The p5.webserial library uses events and callback functions as well. It can listen for the following serialport events:

  • noport – when there is no selected serial port
  • portavailable – when a serial port becomes available
  • data – new data arrives in a serial port
  • close – the serial port is closed
  • requesterror – something goes wrong when you request a serial port.

The WebSerial API on which the p5.webserial library is based also has connect and disconnect events for when a serial port is physically disconnected (or in the case of a USB-native device like the Nano 33 IoT, when it is reset). You’ll see those below as well, and you’ll see them run whenever the serial connection to the Arduino is reset.

To use the the webserial library’s events, you need to set callback functions for them. Change your sketch to include a port chooser button and a variable for incoming data, then in the setup() function, add callbacks for open, close, and data, and error like so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// variable to hold an instance of the p5.webserial library:
const serial = new p5.WebSerial();
 
// HTML button object:
let portButton;
let inData;                   // for incoming serial data
let outByte = 0;              // for outgoing data
 
function setup() {
  createCanvas(400, 300);          // make the canvas
  // check to see if serial is available:
  if (!navigator.serial) {
    alert("WebSerial is not supported in this browser. Try Chrome or MS Edge.");
  }
  // if serial is available, add connect/disconnect listeners:
  navigator.serial.addEventListener("connect", portConnect);
  navigator.serial.addEventListener("disconnect", portDisconnect);
  // check for any ports that are available:
  serial.getPorts();
  // if there's no port chosen, choose one:
  serial.on("noport", makePortButton);
  // open whatever port is available:
  serial.on("portavailable", openPort);
  // handle serial errors:
  serial.on("requesterror", portError);
  // handle any incoming serial data:
  serial.on("data", serialEvent);
  serial.on("close", makePortButton);
}
 
function draw() {
  
 
 
}

The draw() function is empty for the moment. You’ll come back and fill that in later.

Now that you’ve set listeners for the events, you need to add the callback functions. Here they are. Add these after the draw() function:

36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// if there's no port selected,
// make a port select button appear:
function makePortButton() {
  // create and position a port chooser button:
  portButton = createButton("choose port");
  portButton.position(10, 10);
  // give the port button a mousepressed handler:
  portButton.mousePressed(choosePort);
}
 
// make the port selector window appear:
function choosePort() {
  if (portButton) portButton.show();
  serial.requestPort();
}
 
// open the selected port, and make the port
// button invisible:
function openPort() {
  // wait for the serial.open promise to return,
  // then call the initiateSerial function
  serial.open().then(initiateSerial);
 
  // once the port opens, let the user know:
  function initiateSerial() {
    console.log("port open");
  }
  // hide the port button once a port is chosen:
  if (portButton) portButton.hide();
}
 
// pop up an alert if there's a port error:
function portError(err) {
  alert("Serial port error: " + err);
}
// read any incoming data as a string
// (assumes a newline at the end of it):
function serialEvent() {
  inData = Number(serial.read());
  console.log(inData);
}
 
// try to connect if a new serial port
// gets added (i.e. plugged in via USB):
function portConnect() {
  console.log("port connected");
  serial.getPorts();
}
 
// if a port is disconnected:
function portDisconnect() {
  serial.close();
  console.log("port disconnected");
}
 
function closePort() {
  serial.close();
}

Wait a Minute! Don’t I have to Set the Data Rate When I Open the Port?

In asynchronous serial communications, both computers have to set the same data rate in order to communicate. In Arduino, you set the data rate with Serial.begin(9600); In p5.webserial, 9600 bits per second is the default, so you don’t have to set the rate if you want 9600bps. But if you want to set the rate to another value, change your serial.open() call in the openPort() function as follows:

1
2
let options = { baudrate: 9600}; // change the data rate to whatever you wish
serial.open(portName, options);

There are other port options you can set using p5.webserial, including baudRate, bufferSize,  dataBits,  flowControl,  parity and  stopBits. These are all standard serialport options, and most programming environments which support serial communication will have them. You can get details of these in the p5.webserial documentation.

p5.WebSerial Sketch Checklist

Most p5.WebSerial sketches that you write will have a similar structure to this one. The main difference between them all will be how you read and interpret incoming serial data, and how and when you send and format outgoing serial data. Here’s a checklist of the pieces you’re likely to see in every sketch:

  • In the HTML file, include the p5.webserial library
  • In the global variables of the sketch,
    • make a new instance of the library
    • include a port selector button or some way to invoke the serial port chooser dialogue box
  • In the setup:
    • Make sure WebSerial is supported in this browser
    • Include a call to serial.getPorts() to check for available ports.
    • include serial.on() listeners for these events:
      • noport
      • portavailable
      • data
      • close
      • requesterror
    • include navigator listeners for connect and disconnect
  • Define handler functions for all of the events above. Most of these can be simple alerts or console.log messages
  • Customize the function that responds to the data listener (usually called serialEvent() in these examples), as you’ll see below.
  • Decide when and how you’ll send serial data out, as you’ll see in the other p5.webserial labs.

The last two items of this list are the ones on which you’ll spend most of your time. The rest of the items are things you’re likely to copy from one sketch to another.

Reading Incoming Serial Data

The event that that you’ll use the most is the data event, which calls the serialEvent() function. Each time a new byte arrives in the serial port, this function is called. Now it’s time to make serialEvent() do some work. Add a new global variable at the top of your sketch called inData like so:

The serialEvent() function you added above looks like this:

1
2
3
4
function serialEvent() {
  inData = Number(serial.read());
  console.log(inData);
}

It’s reading the incoming data byte by byte, and interpreting each byte as a number. That’s why the Number() function surrounds the read() function. Since you’re sending the data from the Arduino as a binary value (using the Serial.write() function), you have to interpret it in p5.js as a binary value as well.

Next, make the draw() function to print the sensor value to the screen like so:

1
2
3
4
5
function draw() {
   background(0);
   fill(255);
   text("sensor value: " + inData, 30, 50);
}
A screenshot of the sketch running in a browser.
Figure 10. A screenshot of the sketch running in a browser. The sketch prints the sensor value in text on the screen.

When you run your sketch now, you should get something like the sketch shown in Figure 10.

To see the sketch running on GitHub at this link. You can see the source files for copying into the p5.js editor at this link.

The sensor value onscreen should change as you turn your potentiometer. Congratulations! You’ve got P5.js talking to your microcontroller.

What’s Happening Here

Every time your microcontroller sends a byte serially using Serial.write(), the computer receives it and generates a ‘data’ event. Then your serialEvent() function is called. It reads the byte as a number, and stores it in the global variable inData. The draw() method just uses the latest value of inData in the text string it displays on the screen.

You may be wondering why you’re mapping the sensor value or dividing it by 4 in the Arduino sketch above. That’s because in order to send the sensor value as a single byte, it must be between 0 and 255, or no more than 28 bits.

P5.js Console.log() and Arduino delay(): a Tricky Combination

In testing this, you may have put a console.log() statement in the serialEvent() function in your P5.js sketch. When you did, you would have noticed that it causes a lag in the sketch, and the console.log() statements continue even after you stop the sketch. This is because the operating system keeps the incoming serial data in a buffer, and P5.js isn’t reading and printing it as fast as Arduino is sending it.

You might think, “Okay, then I’ll just put a delay() in my Arduino sketch to slow it down.” That’s a bad idea. When you put in a delay, it means you’re only reading your sensor when that delay is not running.  You can miss critical sensor events while that delay is in progress. Even a relatively small delay, for example 30ms, can make it difficult to reliably read state changes in a switch or peaks in an analog sensor. Don’t use delays if you can avoid it. For more on how to handle the flow of serial data from Arduino to P5.js and back, see the Duplex Serial Flow using WebSerial in P5.js lab.

Draw a Graph With the Sensor Values

It would be useful to see a graph of the sensor values over time. You can do that by modifying the draw() method to draw the graph. To do this, add a new global variable at the top of your sketch called xPos. You’ll use this to keep track of the x position of the latest graph line:

1
let xPos = 0;                     // x position of the graph

Because of the way the graphing function below works, you can’t reset the background every time through the draw() loop. So take the background() command and put it in the setup() function instead of the draw(), as shown below. That way it runs once, then not again. As long as you’re at it, switch from black & white to a nice blue color:

1
2
3
function setup() {
  createCanvas(400, 300);
  background(0x08, 0x16, 0x40);

Now make a new function called graphData(). It’ll take a number value as a parameter, and it will draw a line on the screen that’s mapped to the number value. Then it will increment xPos so that the next line is drawn further along. It will also check if the xPos is at the right edge of the screen, and reset the screen by calling background() again if it is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function graphData(newData) {
  // map the range of the input to the window height:
  var yPos = map(newData, 0, 255, 0, height);
  // draw the line in a pretty color:
  stroke(0xA8, 0xD9, 0xA7);
  line(xPos, height, xPos, height - yPos);
  // at the edge of the screen, go back to the beginning:
  if (xPos >= width) {
    xPos = 0;
    // clear the screen by resetting the background:
    background(0x08, 0x16, 0x40);
  } else {
    // increment the horizontal position for the next reading:
    xPos++;
  }
}

Finally, take everything out of the draw() function and just call graphData() from there:

1
2
3
function draw() {
  graphData(inData);
}

When you run the sketch now, you should get a graph, as shown in Figure 11.

Screenshot of the serial graph p5.js sketch.
Figure 11. Screenshot of the serial graph p5.js sketch. The sensor’s values are graphed on the screen

To see the sketch running on GitHub at this link. You can see the source files for copying into the p5.js editor at this link.

Reading Serial Data as a String

This works well if you want to read your sensor values as a single byte, but what if you want a larger range of numbers?  What if you want the full 0 to 1023 that analogRead() can output instead of just 0 to 255?  To do this, you need to send the data as an ASCII-encoded numeric string from the microcontroller, and you need to read and interpret the incoming data in P5 as an ASCII-encoded numeric string as well.

Change your Arduino program to the following:

1
2
3
4
5
6
7
8
9
10
void setup() {
 Serial.begin(9600); // initialize serial communications
}
 
void loop() {
 int potentiometer = analogRead(A0);                  // read the input pin
 int mappedPot = map(potentiometer, 0, 1023, 0, 255); // remap the pot value to fit in 1 byte
 Serial.println(mappedPot);                           // print it out the serial port
 delay(1);                                            // slight delay to stabilize the ADC
}

Now it will print the potentiometer’s value as an ASCII-encoded numeric string, and it will add a carriage return byte and a newline byte at the end, because that’s what println() does.

Once you’ve uploaded this to your Arduino, run your P5 sketch again. Try adding println(inData); at the end of your serialEvent() function. When your P5 sketch reads the data from this Arduino program, you get very low values, and every so often you see the value 10 followed by the value 13. What’s going on?

When a computer ASCII-encodes a number, it converts that number to a string of bytes, each of which is the ASCII value for a numeral in the number. For example, the number 865 gets converted to three bytes, as shown in Figure 12.

ASCII representation of a three-digit number.
Figure 12. The decimal number 865 when sent serially as ASCII is three bytes long. The first byte representing digit, 8, has the ASCII value 58. The second byte representing the digit 6 has the ASCII value 54. The third byte representing the digit 5 has the ASCII value 53.

If there’s a carriage return byte and a newline byte after this, the string is five bytes, and the last two bytes’ values are 13 (carriage return, or \r in most programming languages) and 10 (newline or \n in most programming languages), respectively.

Your P5.js sketch is reading every byte’s value and graphing it. That’s why you get a graph of very low values, with a bunch of them being 13 and 10. The Arduino is ASCII-encoding the potentiometer values, but the P5 sketch is interpreting the bytes as if they’re not encoded that way.

Now change the serialEvent() function like so:

1
2
3
4
function serialEvent() {
  // read a byte from the serial port, convert it to a number:
  inData = serial.readLine();
}

Run it again. What’s changed? Now you’re getting a graph kind of like you were before. The serial.readLine(); command reads the incoming serial data as a string, and when that string happens to be all-numeric, it converts it to a number. So you’re getting the ASCII-encoded string as a number again. But sometimes there are gaps. Why?

Remember, the ‘data’ event occurs every time a new byte comes in the serial port. Now that you’re sending an ASCII-encoded string, every potentiometer reading is several bytes long. So you only get a complete string every three to six bytes (three for “0\r\n” and six for “1023\r\n”). Sometimes, when the serialEvent() function calls serial.readLine(); it gets nothing. That’s when draw() draws the gaps. You need to change your function to check that the resulting string is actually a valid number before you put the string into inData. First, create a local variable to get the string, then check to see if the string’s length is greater than zero. If it is, then put it into inData so that the other functions in the sketch can use the new data. Here’s how you do that:

1
2
3
4
5
6
7
8
9
function serialEvent() {
  // read a string from the serial port:
  var inString = serial.readLine();
  // check to see that there's actually a string there:
  if (inString) {
  // convert it to a number:
  inData = Number(inString);
  }
}

Now you’re able to send in a number of any value to P5.js. You don’t have to limit your input to a 0-255 value range. See if you can modify the Arduino sketch and the P5.js sketch to exchange a potentiometer value that spans the whole range from 0 to 1023.

note: readLine() is the same as readStringUntil(‘\r\n’);

You can see the sketch running on GitHub at this link. You can see the source files for copying into the p5.js editor at this link.

Conclusion

In this lab, you saw how to connect an Arduino microcontroller to a P5.js sketch using a webSocket-to-serial server, P5.serialserver, and the P5.serialport library. You sent data from Arduino to the sketch as a raw binary value — that is, a single byte ranging from 0 to 255 — and you sent it as an ASCII-encoded numeric string with a carriage return and newline at the end. See Table 1 below to review what are suitable data formats for different types/sizes of data and which functions to use on p5.js and Arduino for serial communication.


Table 1. Serial Communication: Arduino to p5.js

Notes about sending ASCII-encoded data:

  • Using Serial.println() on Arduino and serial.readLine() on p5.js is one of many different ways of sending data from Arduino to p5.js via serial communication.
  • If you want to read an ASCII-encoded numeric string as a number and not a string, convert the value into number by using Number()

Understanding the difference between ASCII-encoded strings and raw binary data is central to all serial communications. For more examples of this in action, see the WebSerial Output from P5.js lab.

Lab: Serial IMU Output to p5.js Using p5.webserial

In this exercise you’ll read the built-in Inertial Motion Unit on the Arduino Nano 33 IoT, then feed its output into a Madgwick filter to determine heading, pitch, and roll of the board. Then you’ll send the output of that serially to p5.js and use it to move a virtual version of the Nano onscreen.

Introduction

In this exercise you’ll read the built-in Inertial Motion Unit on the Arduino Nano 33 IoT, then feed its output into a Madgwick filter to determine heading, pitch, and roll of the board. Then you’ll send the output of that serially to p5.js and use it to move a virtual version of the Nano onscreen.

What You’ll Need to Know

To get the most out of this lab, you should be familiar with the following concepts and you should install the Arduino IDE on your computer. You can check how to do so in the links below:

Things You’ll Need

The only part you’ll need for this exercise is an Arduino Nano 33 IoT and its built-in IMU, as shown in Figure 1. You can modify this exercise to work with other IMUs, however. There are details on various IMUs on the accelerometers, gyrometers, and IMUs page.

Photo of an Arduino Nano 33 IoT module. The USB connector is at the top of the image, and the physical pins are numbered in a U-shape from top left to bottom left, then from bottom right to top right.
Figure 1. Microcontroller. Shown here is an Arduino Nano 33 IoT.

Prepare the Breadboard

because the Nano 33 IoT has a built-in IMU, there is no additional circuit needed for this exercise. However, there are two libraries you’ll need to install: the Arduino_LSM6DS3 library, which allows you to read the IMU, and the MadgwickAHRS library, which takes the raw accelerometer and gyrometer inputs and provides heading, pitch, and roll outputs. Both libraries can be found in the Library Manager of the Arduino IDE. Install them before proceeding.

Program the Microcontroller to Read the IMU

The first thing to do in the microcontroller code is to confirm that your accelerometer and gyrometer are working. Start with the code below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include "Arduino_LSM6DS3.h"
 
void setup() {
  Serial.begin(9600);
  // attempt to start the IMU:
  if (!IMU.begin()) {
    Serial.println("Failed to initialize IMU");
    // stop here if you can't access the IMU:
    while (true);
  }
}
 
void loop() {
  // values for acceleration and rotation:
  float xAcc, yAcc, zAcc;
  float xGyro, yGyro, zGyro;
 
  // check if the IMU is ready to read:
  if (IMU.accelerationAvailable() && IMU.gyroscopeAvailable()) {
    // read accelerometer and gyrometer:
    IMU.readAcceleration(xAcc, yAcc, zAcc);
    IMU.readGyroscope(xGyro, yGyro, zGyro);
 
    Serial.print("sensors: ");
    Serial.print(xAcc);
    Serial.print(",");
    Serial.print(yAcc);
    Serial.print(",");
    Serial.print(zAcc);
    Serial.print(",");
    Serial.print(xGyro);
    Serial.print(",");
    Serial.print(yGyro);
    Serial.print(",");
    Serial.println(zGyro);
  }
}

When you run this sketch and open the Serial Monitor, you should see a printout with six values per line. The first three are your accelerometer values, and the next three are your gyrometer values. The following reading is typical:

sensors: 0.04,-0.05,1.02,3.05,-3.72,-1.77

The Nano 33 IoT’s accelerometer’s range is fixed at +/-4G by this library, and its gyrometer’s range is set at +/-2000 degrees per second (dps). The sampling rate for both is set to 104 Hz by the library. Other IMUs may have differing ranges. You need to know at least the sampling rate when you want to use a different IMU with this exercise. If you know that information, though, it’s easy to swap one IMU for another in the Madgwick library.

Add the Madgwick Library to Get Orientation

The MadgwickAHRS library can work with any accelerometer/gyrometer combination. It expects the acceleration in Gs and the rotation in degrees per second as input, and uses the sensors’ sampling rate when you initialize it. Add a few lines to the code before your setup() as follows:

1
2
3
4
5
6
7
8
9
10
11
12
#include "Arduino_LSM6DS3.h"
#include "MadgwickAHRS.h"
 
// initialize a Madgwick filter:
Madgwick filter;
// sensor's sample rate is fixed at 104 Hz:
const float sensorRate = 104.00;
 
// values for orientation:
float roll = 0.0;
float pitch = 0.0;
float heading = 0.0;

Next, add the following line at the end of the setup() to initialize the Madgwick filter:

1
2
// start the filter to run at the sample rate:
filter.begin(sensorRate);

Now change the main loop so that you’re sending the sensor readings into the Madgwick filter. You’ll do this inside of the if statement that checks if the sensors are ready:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// check if the IMU is ready to read:
if (IMU.accelerationAvailable() &&
IMU.gyroscopeAvailable()) {
  // read accelerometer and gyrometer:
  IMU.readAcceleration(xAcc, yAcc, zAcc);
  IMU.readGyroscope(xGyro, yGyro, zGyro);
 
  // update the filter, which computes orientation:
  filter.updateIMU(xGyro, yGyro, zGyro, xAcc, yAcc, zAcc);
 
  // print the heading, pitch and roll
  roll = filter.getRoll();
  pitch = filter.getPitch();
  heading = filter.getYaw();
 
  // print the filter's results:
  Serial.print(heading);
  Serial.print(",");
  Serial.print(pitch);
  Serial.print(",");
  Serial.println(roll);
}

Now when you run the sketch, you’ll get heading, pitch, and roll instead of the raw sensor readings. Here’s a typical output you might see:

167.59,-2.50,-2.52In this case, the readings are all in degrees. The first is the heading angle, around the Z axis. The second two are the pitch, around the x axis, and roll, around the Y axis.

Add Serial Handshaking

Reading these values in p5.js will work smoother if you add handshaking, also known as call-and-response, to your serial communications protocol. Modify the loop() so that the sketch sends the latest heading, pitch, and roll whenever a new byte comes in the serial port. Here’s the final version of the loop():

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
void loop() {
  // values for acceleration and rotation:
  float xAcc, yAcc, zAcc;
  float xGyro, yGyro, zGyro;
 
  // check if the IMU is ready to read:
  if (IMU.accelerationAvailable() & amp; & amp;
      IMU.gyroscopeAvailable()) {
    // read accelerometer and gyrometer:
    IMU.readAcceleration(xAcc, yAcc, zAcc);
    IMU.readGyroscope(xGyro, yGyro, zGyro);
 
    // update the filter, which computes orientation:
    filter.updateIMU(xGyro, yGyro, zGyro, xAcc, yAcc, zAcc);
 
    // print the heading, pitch and roll
    roll = filter.getRoll();
    pitch = filter.getPitch();
    heading = filter.getYaw();
  }
 
  // if you get a byte in the serial port,
  // send the latest heading, pitch, and roll:
  if (Serial.available()) {
    char input = Serial.read();
    Serial.print(heading);
    Serial.print(",");
    Serial.print(pitch);
    Serial.print(",");
    Serial.println(roll);
  }
}

this link. When you have this much working, and you’ve tested it in the Serial Monitor, you can close Arduino and work on the p5.js sketch.

Program p5.js to Read the Incoming Serial Data

Now it’s time to write a p5.js sketch to read this data.   The setup will be the same as it was in the Serial Input to p5.js using WebSerial lab. The checklist from that lab lays out all the important parts you need.

Make a P5.js sketch. If you’re using the p5.js web editor, make a new sketch. Click the Sketch Files tab, and then choose the index.html file. Edit the head of the document as you did for the other p5.webserial labs. It should look like this:

Start your sketch with some code to initialize the serial library:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// variable to hold an instance of the p5.webserial library:
const serial = new p5.WebSerial();
  
// HTML button object:
let portButton;
 
function setup() {
    createCanvas(500, 600, WEBGL);     // make the canvas
  // check to see if serial is available:
  if (!navigator.serial) {
    alert("WebSerial is not supported in this browser. Try Chrome or MS Edge.");
  }
  // if serial is available, add connect/disconnect listeners:
  navigator.serial.addEventListener("connect", portConnect);
  navigator.serial.addEventListener("disconnect", portDisconnect);
  // check for any ports that are available:
  serial.getPorts();
  // if there's no port chosen, choose one:
  serial.on("noport", makePortButton);
  // open whatever port is available:
  serial.on("portavailable", openPort);
  // handle serial errors:
  serial.on("requesterror", portError);
  // handle any incoming serial data:
  serial.on("data", serialEvent);
  serial.on("close", makePortButton);
}
function draw() {
  
}
  
// if there's no port selected,
// make a port select button appear:
function makePortButton() {
  // create and position a port chooser button:
  portButton = createButton('choose port');
  portButton.position(10, 10);
  // give the port button a mousepressed handler:
  portButton.mousePressed(choosePort);
}
  
// make the port selector window appear:
function choosePort() {
  serial.requestPort();
}
  
// open the selected port, and make the port
// button invisible:
function openPort() {
  // wait for the serial.open promise to return,
  // then call the initiateSerial function
  serial.open().then(initiateSerial);
  
  // once the port opens, let the user know:
  function initiateSerial() {
    console.log("port open");
    serial.write("x");
  }
  // hide the port button once a port is chosen:
  if (portButton) portButton.hide();
}
  
// read any incoming data:
function serialEvent() {
  // read a string from the serial port
  // until you get carriage return and newline:
  var inString = serial.readStringUntil("\r\n");
  console.log(inString);
}
  
// pop up an alert if there's a port error:
function portError(err) {
  alert("Serial port error: " + err);
}
  
// try to connect if a new serial port
// gets added (i.e. plugged in via USB):
function portConnect() {
  console.log("port connected");
  serial.getPorts();
}
  
// if a port is disconnected:
function portDisconnect() {
  serial.close();
  console.log("port disconnected");
}

Save this as sketch.js, then open p5.serialcontrol. Then open the sketch in a browser. Open the JavaScript console, and you should see the first set of data printed out. This is because the initiateSerial() function sent a single byte to the Nano when the port opened, and the Nano sent one set of readings. That generated a serial data event in p5.js, and called the serialEvent() function, which printed out the results.You need this to happen repeatedly: p5.js sends a byte when it wants new data, then the Nano sends the data, then waits for another byte from p5.js.

Add Serial Handshaking

To make this happen, you need to add a few things to your p5.js sketch. You can assume that if you saw the message in the console, then you’re ready for new data. That’s when you should send a byte back to the microcontroller to request new data. Add one line to the serialEvent() function to make this happen:

1
2
3
4
5
6
7
8
9
10
// callback function for incoming serial data:
ffunction serialEvent() {
  // read a string from the serial port
  // until you get carriage return and newline:
  var inString = serial.readStringUntil("\r\n");
  if (inString != null) {
    console.log(inString);
    serial.write("x");
  }
}

When you run the sketch with this update, you should see a continuous flow of new data from the microcontroller.

Next, you need to break the string up into parts and convert them into floating point numbers so you can use them as heading, pitch, and roll. Start by adding three new variables at the top of your sketch as global variables, because you’ll need them when you draw the virtual Arduino:

1
2
3
4
// orientation variables:
let heading = 0.0;
let pitch = 0.0;
let roll = 0.0;

Next, in the serialEvent() function, use the JavaScript trim() function to get rid of any extraneous characters at the end of the message string, like carriage returns or newlines. Then use the split() function to split the string into a list of elements separated by commas. Then convert them to floating point numbers. Once you know you have three valid numbers for heading, pitch, and roll, send another byte to the microcontroller to get a new reading. Here’s what the new version of serialEvent() looks like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function serialEvent() {
  // read from port until new line:
  let inString = serial.readStringUntil("\r\n");
  if (inString != null) {
    let list = split(trim(inString), ",");
    if (list.length > 2) {
      // conver list items to floats:
      heading = float(list[0]);
      pitch = float(list[2]);
      roll = float(list[1]);
      console.log(heading + "," + pitch + "," + roll);
      // send a byte to the microcontroller to get new data:
      serial.write("x");
    }
  }
}

When you reload the sketch after making these changes, you should be getting floating point numbers for heading, pitch and roll. Once you have these values coming in consistently, it’s a good idea to comment out the console.log() statement, as shown above, as it slows down the sketch considerably.

Now that you have serial communication working properly, it’s time to write the code to draw the virtual microcontroller.

Draw the Virtual Arduino

Add the function below to draw a virtual Arduino. It draws in three dimensions, using the WEBGL framework you chose in createCanvas() above in the setup() function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// draws the Arduino Nano:
function drawArduino() {
   // the base board:
   stroke(0, 90, 90); // set outline color to darker teal
   fill(0, 130, 130); // set fill color to lighter teal
   box(300, 10, 120); // draw Arduino board base shape
 
   // the CPU:
   stroke(0);         // set outline color to black
   fill(80);          // set fill color to dark grey
   translate(30, -6, 0); // move to correct position
   box(60, 0, 60);    // draw box
 
   // the radio module:
   stroke(80);       // set outline color to grey
   fill(180);        // set fill color to light grey
   translate(80, 0, 0); // move to correct position
   box(60, 15, 60);  // draw box
 
   // the USB connector:
   translate(-245, 0, 0); // move to correct position
   box(35, 15, 40);   // draw box
}

You haven’t added a draw() function yet, so add it now, as follows:

1
2
3
4
5
6
7
function draw() {
   background(255); // set background to white
   push();          // begin object to draw
   // draw arduino board:
   drawArduino();
   pop();           // end of object
}

When you reload the sketch, you’ll see a drawing like that in Figure 4. It won’t change.

A virtual Arduino Nano 33 IoT, drawn in in p5.js.
Figure 4. A virtual Arduino Nano 33 IoT, drawn in in p5.js. The Nano is seen from the side, with the USB connector on the right, and the radio on the right.

To make it change its orientation, you need to use the heading, pitch, and roll values to rotate the object. You get the sine and cosine of each angle, and use them to generate a matrix for translation. The math below was worked out by Helena Bisby based on the Madgwick algorithm. p5.js’ applyMatrix() function does the matrix math for you to rotate in all three dimensions.  Modify the draw() function as shown below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function draw() {
   // update the drawing:
   background(255); // set background to white
   push();          // begin object to draw
 
   // variables for matrix translation:
   let c1 = cos(radians(roll));
   let s1 = sin(radians(roll));
   let c2 = cos(radians(pitch));
   let s2 = sin(radians(pitch));
   let c3 = cos(radians(heading));
   let s3 = sin(radians(heading));
   applyMatrix(c2 * c3, s1 * s3 + c1 * c3 * s2,
      c3 * s1 * s2 - c1 * s3, 0, -s2, c1 * c2,
      c2 * s1, 0, c2 * s3, c1 * s2 * s3 - c3 * s1,
      c1 * c3 + s1 * s2 * s3, 0, 0, 0, 0, 1);
 
   // draw arduino board:
   drawArduino();
   pop(); // end of object
}

When you reload the sketch after making these changes, the virtual Arduino should change its position as you move the physical Arduino. That’s the whole application! Figure 5 shows the virtual Arduino in motion.

You can see the sketch running on GitHub at this link. You can see the source files for copying into the p5.js editor at this link.

Moving GIF of a virtual Arduino Nano turning in three dimensions
Figure 5. This virtual Arduino Nano, written in p5.js, moves in three dimensions as you move a real Nano connected to the sketch serially.

Conclusion

If you followed along all of the steps to this application, you probably hit a number of places where communication broke down. There are a lot of pieces to this application, and they all need to work together.

Get the Sensors Working

When you’re dealing with IMU sensors, no data will be perfect, because the sensor’s measurement is always relative. You’ll notice, for example, that the position of the virtual Arduino drifts a bit the longer you run the sketch. Heading, in particular, tends to drift. In real-world applications, this is often adjusted by using a magnetometer as a compass in addition to the accelerometer and gyrometer. It’s also wise to provide ways for a human to calibrate the system, perhaps by pressing a button when the sensor is level in order to calculate offset values for the sensors. For many interactive applications, though, even an imperfect measurement of orientation will do the job well.

Test the Hardware

If you’re using serial communication that’s ASCII-encoded like this, you can always use the Serial Monitor or another serial terminal application to test the Arduino sketch before you ever begin working on the multimedia programming. Ideally, you don’t need to change the Arduino sketch at all once your communication is working as planned.

Get the Communication Working

Whenever you’re building an application that incorporates asynchronous serial communication, it’s best to get the communication working correctly before you build the animation or other parts of the interaction. Once the communication protocol is known, you can even divide the work, with one team developing the hardware and another developing the media programming.

This exercise shows the value of using handshaking (aka call-and-response) in serial communication. Because the drawing of the microcontroller takes time, the p5.js sketch reads data less frequently than the microcontroller can send it. If you simply allow the microcontroller to send data continuously, the serial buffer on the p5.js side will fill up, and the movement of the virtual Arduino will become sluggish. This is why you only send back to the microcontroller when you know you have a set of valid data, in the serialEvent() function.

Test the Incoming Data

You don’t need to do anything with your incoming serial data to know it’s valid, if you’ve thought through the protocol well. In this case, if you see you’re getting three separate values and they’re all in a range of 0 to 360 (indicating degrees of the heading, pitch, and roll angles), you know it’ll work.

Program the Interface, Animation, etc.

Once you know the communication is good, and you’re getting accurate values, you can program  the parts of your final application that use that data. In this case, you didn’t even start on the movement of the virtual Arduino until you knew you had communication working. Drawing of the virtual model was separated from moving it, using the push(), pop(), and translation functions, like applyMatrix(), in p5.js. That separation makes the programming easier to do, and easier to debug.

Accelerometers, Gyros, and IMUs: The Basics

Introduction

Inertial Motion Units (IMUs) are sensors that measure movement in multiple axes. Accelerometers measure a changing acceleration on the sensor. They can be used to measure the tilt of the sensor with respect of the Earth, or the force of a hit. They are common in mobile devices and automobiles. Gyrometers measure changing angular motion. They can be used to measure rotation. Magnetometers measure the magnetic force on a sensor. These are usually used to measure the Earth’s gravitational field in order to determine compass heading. IMUs have become increasingly common in microcontroller projects, to the point where they are built into some microcontroller boards like the Arduino 33 IoT and BLE Sense, and the Arduino 101. In this lesson, you’ll learn a few principles of working with these sensors, and see some examples.

What You’ll Need to Know

To get the most out of this lab, you should be familiar with the following concepts and you should install the Arduino IDE on your computer. You can check how to do so in the links below:

Things You’ll Need

Figures 1-4 below show the parts you’ll need for this exercise. Click on any image for a larger view.

Photo of an Arduino Nano 33 IoT module. The USB connector is at the top of the image, and the physical pins are numbered in a U-shape from top left to bottom left, then from bottom right to top right.
Figure 1. Microcontroller. Shown here is an Arduino Nano 33 IoT. An Uno will do for some of the examples here, though.
Photo of flexible jumper wires
Figure 2. Jumper wires.  You can also use pre-cut solid-core jumper wires.
Photo of a solderless breadboard
Figure 3. A solderless breadboard
Photo of an accelerometer, model LIS3DH
Figure 4. An accelerometer. Shown here is an ST Microelectronics LIS3DH accelerometer. Others will be mentioned below.

Orientation, Position, and Degrees of Freedom

“Orientation, or compass heading, is how you determine your direction if you’re level with the earth. If you’ve ever used an analog compass, you know how important it is to keep the compass level in order to get an accurate reading. If you’re not level, you need to know your tilt relative to the earth as well. In navigational terms, your tilt is called your attitude, and there are two major aspects to it: roll and pitch. Roll refers to how you’re tilted side-to-side. Pitch refers to how you’re tilted front-to-back.

“Pitch and roll are only two of six navigational terms used to refer to movement. Pitch, roll, and yaw refer to angular motion around the X, Y, and Z axes. These are called rotations. Surge, sway, and heave refer to linear motion along those same axes. These are called translations.  These are often referred to as six degrees of freedom. Degrees of freedom refer to how many different parameters the sensor is tracking in order to determine your orientation.

“You’ll hear a number of different terms for these sensors. The combination of an accelerometer and gyrometer is sometimes referred to as an inertial measurement unit, or IMU… When an IMU is combined with a magnetometer, the combination is referred to as an attitude and heading reference system, or AHRS. Sometimes they’re also called magnetic, angular rate, and gravity, or MARG, sensors. You’ll also hear them referred to as 6-degree of freedom, or 6-DOF, sensors. There are also 9-DOF sensors that incorporate all three types of sensors. Each axis of measurement is another degree of freedom. [There are] even has 10-DOF sensor[s] that add barometric pressure sensor[s] for determining altitude.”

From Making Things Talk, 3rd edition

Features of an IMU

Whether you’re dealing with an accelerometer, gyrometer, or magentometer, there are a few features you’ll need to consider:

  • Range – IMU sensors come in different ranges of sensitivity.
    • Acceleration is generally measured in meters per second squared (m/s^2) or g’s, which are multiples of the acceleration due to gravity. 1g = 9.8 m/s^2. Accelerometers come in ranges from 2g to 250g and beyond. the force of gravity is 1g, but a human punch can be upwards of 100g
    • Angular motion is measured in degrees per second (dps). Gyro ranges of 125dps to 2000 dps are not uncommon.
    • Magnetic force is measured in Teslas. In most direction applications, the important measurement, however is the relative magnetic field strength on each axis.
  • Number of axes – Almost all IMU sensors can sense their respective properties on multiple axes. Whatever activity you’re measuring, you’ll most likely want to know the acceleration, rotational speed, or magnetic force in horizontal and vertical directions. Most sensors give results for the X, Y, and Z axes. Z is typically perpendicular to the Earth, and the other two are parallel to it, but perpendicular to each other.
  • Electrical Characteristics – as with any electronic sensor, you should pay attention to current consumption and make sure the rated voltage of your IMU is compatible with your microcontroller.
  • Interface – IMUs come with a variety of interfaces. Some provide a changing analog voltage on each axis. Others will provide an I2C or SPI synchronous serial interface. Older IMUs will provide a changing pulse width that corresponds with the changing properties of the sensor. Nowadays, most IMUs are either I2C, SPI, or analog.
  • Extra Features – in addition to the basic physical properties, many IMUs will have additional features, like freefall detection or  tap detection, or additional control features like the ability to set the sensing rate.

For more on choosing an IMU, Sparkfun has an excellent introductory guide.

Most vendors of accelerometer modules do not actually make the sensors themselves, they just put them on a breakout board along with the reference circuit, for convenience. While you might buy your IMU from Sparkfun, Adafruit, Seeed Studio, or Pololu, for example, the chances are the actual sensor is manufactured by another company like Analog Devices, ST Microelectronics, or Bosch. When you shop for a sensor module, check out the manufacturer’s datasheet in addition to the vendor’s tech specs.

Analog IMUs

Analog IMU sensors typically have an output pin for each axis that outputs a range from 0 volts to the sensor’s maximum voltage. Most of them only have one form of sensor (accelerometer, gyrometer, magnetometer). Having multiple pins for each type of sensor would be unweildy.

Since it’s possible to have both positive and negative change in a given sensor’s range, the rest value for each output pin is usually in the middle of the voltage range. You need to understand this in order to read the sensor.

Analog Devices’ ADXL series of accelerometers are useful examples of this kind of sensor. There are two similar models, the ADXL335 and the ADXL377. The former is good for simple range of motion applications, and latter is designed for high-acceleration applications, like crashes, punches, and so forth.  Both operate at 3.3V. Both output analog voltages for X, Y, and Z. Both output their midrange voltage, about 1.65V,  on each axis when it’s at rest (at 0g). The ADXL335 is a +/-3g accelerometer, and the ADXL377 is a +/- 200g accelerometer.  While you’d see a significant change on the ADXL335’s axes when you simply tilt the sensor, you’d see barely any when you simply tilt the ADXL377. Why? Consider the math:

The ADXL335 outputs 0V at -3g, 3.3V at +3g, and 1.65V at 0g. That means that 1g of acceleration changes the analog output by 1/6 of its range. If you’re using analogRead() on an Arduino with a 3.3V analog reference voltage, that means you’ve got a range of about 341 points per g of acceleration (1024 / 6).  When you tilt the accelerometer to 90 degrees, you’re getting +1g on the X or Y axis. That’s a reading of about 682 using analogRead() on an Arduino. When you tilt it 90 degrees the other way, you’re getting -1g on the same axis, or  about 341 using analogRead().

The ADXL377 outputs 0V at -200g, 3.3V at +200g, and 1.65V at 0g. That means 1g of acceleration changes the output by only 1/400 of its range. The same tilting action described above would give you a change from about 510 to 514 using analogRead(),using the same math as above.

This lesson applies whether you’re measuring acceleration, rotation, or magnetic field strength. Make sure to use a sensor that matches the required range otherwise you won’t see much change, particularly with an analog sensor.

Analog Accelerometer Example

Figure 5 shows the schematic for connecting an ADXL335 to an Arduino, and Figures 6 and 7 show the breadboard view for the Uno and the Nano, respectively. For both boards, the accelerometer’s Vcc pin is connected to the voltage bus, and its ground pin is connected to the ground bus. The X axis pin is connected to the Uno’s analog in 2, the Y axis pin is connected to the Uno’s analog in 1, and the Z axis pin is connected to the Uno’s analog in 0.

Other analog IMUs are wired similarly.

Schematic view of an Arduino connected to an ADXL3xx accelerometer.
Figure 5. Schematic view of an Arduino connected to an ADXL3xx accelerometer. The accelerometer’s Vcc pin is connected to 3.3V on the Arduino, and its ground pin is connected to ground . The X axis pin is connected to the Arduino’s analog in 2, the Y axis pin is connected to the Arduino’s analog in 1, and the Z axis pin is connected to the Arduino’s analog in 0.
Breadboard view of an Arduino Uno connected to an ADXL3xx accelerometer.
Figure 6. Breadboard view of an Arduino Uno connected to an ADXL3xx accelerometer. The Uno is connected to a breadboard, with its 3.3V pin (not 5V as in other examples) connected to the voltage bus and its ground pin connected to the ground bus. The accelerometer is connected to six rows in the left center section of the breadboard beside the Uno.
Breadboard view of an Arduino Nano connected to an ADXL3xx accelerometer.
Figure 7. Breadboard view of an Arduino Nano connected to an ADXL3xx accelerometer. The Nano is connected as usual, straddling the first fifteen rows of the breadboard with the USB connector facing up. Voltage (physical pin 2) is connected to the breadboard’s voltage bus, and ground (physical pin 14) is connected to the breadboard’s ground bus. The accelerometer is connected to six rows in the left center section of the board below the pushbutton.

The code below will read the accelerometer and print out the values of the three axes:

void setup() {
  Serial.begin(9600);
}

void loop() {
  int xAxis = analogRead(A2); // Xout pin of accelerometer
  Serial.print(xAxis);

  int yAxis = analogRead(A1); // Yout pin of accelerometer
  Serial.print(",");
  Serial.print(yAxis);

  int zAxis = analogRead(A0); // Zout pin of accelerometer
  Serial.print(",");
  Serial.println(zAxis);
}

Digital IMUs

Digital IMUs output a digital data stream via a serial interface, typically SPI or I2C. Unlike analog IMUs, these sensors can be configured digitally as well. Most support changing the sensitivity and the sampling rate, and some allow you to turn on and off features like tap detection or freefall detection.

Many digital IMUs are truly IMUs, in that they combine multiple sensors: accelerometer/gyrometer, accelerometer/gyrometer/magnetometer, and so forth.

Another advantage of digital IMUs is that they tend to convert their sensor readings at a higher level of resolution than a microcontroller’s analog input. While a microcontroller’s ADC is typically 10-bit (0-1023), many digital IMUs read their sensors into a 16-bit or even 32-bit result. This gives you greater sensitivity than an analog IMU.

Digital Accelerometer Example

Figure 8 shows the schematic for connecting a LIS3DH accelerometer to an Arduino, and Figures 9 and 10 show the breadboard view for the Uno and the Nano, respectively. For both the Uno and the nano, the accelerometer’s Vcc pin is connected to the voltage bus, and its ground pin is connected to the ground bus. The SDA pin is connected to the microcontroller’s analog in 4, the SCL pin is connected to the microcontroller’s analog in 5 , and the SDO is connected to the ground bus. Other digital IMUs are wired similarly.

Schematic view of an Arduino Nano connected to an LIS3DH accelerometer
Figure 8. Schematic view of an Arduino connected to an LIS3DH accelerometer. The accelerometer’s Vcc pin is connected to 3.3V on the Arduino, and its ground pin is connected to the Arduino’s ground. The SDA pin is connected to the Uno’s analog in 4, the SCL pin is connected to the Uno’s analog in 5, and the SDO is connected to ground.
Breadboard view of an Arduino Uno connected to an LIS3DH accelerometer
Figure 9. Breadboard view of an Arduino Uno connected to an LIS3DH accelerometer. The Uno is connected to a breadboard, with its 3.3V pin (not 5V as in other examples) connected to the voltage bus and its ground pin connected to the ground bus. The accelerometer is straddling the center of the board.

Breadboard view of an Arduino Nano connected to an LIS3DH accelerometer
Figure 10. Breadboard view of an Arduino Nano connected to an LIS3DH accelerometer. The Nano is connected as usual, straddling the first fifteen rows of the breadboard with the USB connector facing up. Voltage (physical pin 2) is connected to the breadboard’s voltage bus, and ground (physical pin 14) is connected to the breadboard’s ground bus. The accelerometer is straddling the center of the board below the Nano.

The following code will read the accelerometer and print out the acceleration on each axis in g’s. This accelerometer has a 14-bit range of sensitivity. The code below configures the accelerometer for a 2g range, and converts the 14-bit range to -2 to 2g. This is a simplification of one of the LIS3DH library examples by Kevin Townsend.  It uses Adafruit’s LIS3DH library, but will work for any breakout board for the LIS3DH. It’s been tested with both Sparkfun’s and Adafruit’s boards for this sensor:

#include "Wire.h"
#include "Adafruit_LIS3DH.h"

Adafruit_LIS3DH accelerometer = Adafruit_LIS3DH();

void setup() {
  Serial.begin(9600);
  while (!Serial);
  if (! accelerometer.begin(0x18)) {
    Serial.println("Couldn't start accelerometer. Check wiring.");
    while (true);     // stop here and do nothing
  }
  accelerometer.setRange(LIS3DH_RANGE_8_G);   // 2, 4, 8 or 16 G
}

void loop() {
  accelerometer.read();      // get X, Y, and Z data
  // Then print out the raw data
  Serial.print(convertReading(accelerometer.x));
  Serial.print(",");
  Serial.print(convertReading(accelerometer.y));
  Serial.print(",");
  Serial.println(convertReading(accelerometer.z));
}

// convert reading to a floating point number in G's:
float convertReading(int reading) {
  float divisor = 2 <<; (13 - accelerometer.getRange());
  float result = (float)reading / divisor;
  return result;
}

Here’s a link to some more examples for the LIS3DH which work with either Adafruit’s or Sparkfun’s LIS3DH board.


Built-in IMUs

Some microcontroller boards, like the Nano 33 IoT and Nano 33 BLE sense and the 101, have built-in IMUs. These are digital IMUs, and they’re connected to either the SPI or  I2C bus of the microcontroller. This means you might have conflicts if you’re using them along with an external I2C or SPI sensor. For example, when you’re using them as an I2C sensor, you need to know their I2C address so you don’t try to use another I2C sensor with the same address.

Most built-in IMUs will come with a board-specific library, like the 101’s CurieBLE or the Nano 33 IoT’s Arduino_LSM6DS3 library. Otherwise, they will be identical to the digital IMUs, so even with a built-in accelerometer, you can get more information from the accelerometer’s datasheet or the library’s header files.

Nano 33 IoT Built-In IMU Example

The LSM6DS3 IMU that’s on the Nano 33 IoT is an accelerometer/gyrometer combination. You can get both acceleration and rotation from it. The IMU is built into the board, so there is no additional circuit.

The code example below will read the accelerometer in g’s and the gyrometer in degrees per second and print them both out:

#include "Arduino_LSM6DS3.h"

void setup() {
  Serial.begin(9600);
  // start the IMU:
  if (!IMU.begin()) {
    Serial.println("Failed to initialize IMU");
    // stop here if you can't access the IMU:
    while (true);
  }
}

void loop() {
  // values for acceleration and rotation:
  float xAcc, yAcc, zAcc;
  float xGyro, yGyro, zGyro;

  // if both accelerometer and gyrometer are ready to be read:
  if (IMU.accelerationAvailable() &&
      IMU.gyroscopeAvailable()) {
    // read accelerometer and gyrometer:
    IMU.readAcceleration(xAcc, yAcc, zAcc);

    // print the results:
    IMU.readGyroscope(xGyro, yGyro, zGyro);
    Serial.print(xAcc);
    Serial.print(",");
    Serial.print(yAcc);
    Serial.print(",");
    Serial.print(zAcc);
    Serial.print(",");
    Serial.print(xGyro);
    Serial.print(",");
    Serial.print(yGyro);
    Serial.print(",");
    Serial.println(zGyro);
  }
}

What To Look For in an IMU Library

Different vendors will generally write their own libraries for the IMUs they sell. When you’re looking at a given vendor’s product, take a look at the properties of the sensor in the vendor’s datasheet, and the list of public functions in the library’s API. Does the library give you the functions of the sensor that you need? If the sensor supports multiple sensing ranges, does the library give you access to setting and getting the range? Is it well-documented, and well-commented? Are there simple, clear, well-commented examples?

For example, both Sparkfun and Adafruit make breakout boards for the LIS3SH accelerometer. This accelerometer is typical for a digital accelerometer; it’s got I2C and SPI interfaces, operates at 3.3V, and has a range of acceleration sensitivity, from 2g to 16g. The Adafruit getting started guide and the Sparkfun getting started guide get you up and running, but neither provides a summary of all the functions in their libraries. To see that, you need to look at the header files for each library. Adafruit’s header file is exhaustively commented, which can take time to get through. The key public functions start around line 344. It relies on their Unified Sensor library, which adds some complexity, but there are some nice additions, like the click functionality that the accelerometer supports. Sparkfun’s header file is less thoroughly commented, but shorter. The key public functions start about line 116.  If you only need the basic acceleration functions, it’s easier to use because of less dependency on other libraries. Both are good libraries, though, and you should choose based on the features you want and how easy you find each to use.

You could use either library with either breakout board, but there is one catch: when you’re using the board’s I2C synchronous serial interface, you have to pay attention to the address you use in the the Adafruit board defaults to a different I2C address than the Sparkfun one. SparkFun defaults to 0x19, while Adafruit defaults to 0x18. In I2C mode, the SDO pin switches the I2C default address between 0x18 and 0x19. Taking this pin HIGH sets the address to 0x19, while taking it LOW sets it to 0x18, so by changing this pin, you can choose which library you prefer. Both libraries also have the ability to change the address they use for the accelerometer as well.

Determining Orientation

Determining orientation from an IMU takes some advanced math. Fortunately, there are a few algorithms for doing it. In 2010, Sebastian Madgwick developed and published a more efficient set of algorithms for determining yaw, pitch, and roll using the data from IMU sensors. Helena Bisby converted Madgwick’s algorithms into a Madgwick library for Arduino, improved upon by Paul Stoffregen and members of the Arduino staff. Though it was originally written for the Arduino 101, it can work with any IMU as long as you know the IMU’s sample rate and sensitivity ranges. Here’s an example that uses the Madgwick library and the Nano 33 IoT’s LSM6DS3 IMU to determine heading, pitch, and roll:

#include "Arduino_LSM6DS3.h"
#include "MadgwickAHRS.h"

// initialize a Madgwick filter:
Madgwick filter;
// sensor's sample rate is fixed at 104 Hz:
const float sensorRate = 104.00;

void setup() {
  Serial.begin(9600);
  // attempt to start the IMU:
  if (!IMU.begin()) {
    Serial.println("Failed to initialize IMU");
    // stop here if you can't access the IMU:
    while (true);
  }
  // start the filter to run at the sample rate:
  filter.begin(sensorRate);
}

void loop() {
  // values for acceleration and rotation:
  float xAcc, yAcc, zAcc;
  float xGyro, yGyro, zGyro;

  // values for orientation:
  float roll, pitch, heading;
  // check if the IMU is ready to read:
  if (IMU.accelerationAvailable() &&
      IMU.gyroscopeAvailable()) {
    // read accelerometer &and gyrometer:
    IMU.readAcceleration(xAcc, yAcc, zAcc);
    IMU.readGyroscope(xGyro, yGyro, zGyro);

    // update the filter, which computes orientation:
    filter.updateIMU(xGyro, yGyro, zGyro, xAcc, yAcc, zAcc);

    // print the heading, pitch and roll
    roll = filter.getRoll();
    pitch = filter.getPitch();
    heading = filter.getYaw();
    Serial.print("Orientation: ");
    Serial.print(heading);
    Serial.print(" ");
    Serial.print(pitch);
    Serial.print(" ");
    Serial.println(roll);
  }
}

Conclusion

There are dozens of accelerometers, gyrometers, and IMUs on the market, and as they become more ubiquitous in electronic devices, they continue to get smaller, cheaper, and more power-efficient. The principles laid out here should give you a basis for getting to know new ones as needed.

Lab: Bluetooth LE and p5.ble

This exercise introduces you to how to communicate between a Bluetooth LE-equipped microcontroller and p5.js using the p5.ble library.

Introduction

Bluetooth has been a popular method for wireless communication between devices for many years now. It’s a good way to communicate between two devices directly over a distance of 10 meters or less. Version 4.0 of the Bluetooth specification, also known as Bluetooth LE, introduced some changes to Bluetooth, and made it more power-efficient. There are many Bluetooth LE-equipped microcontroller modules on the market, and they all follow the same general patterns of communication. This exercise introduces you to how to communicate between a Bluetooth LE-equipped microcontroller and p5.js using the p5.ble library.

What You’ll Need to Know

To get the most out of this tutorial, you should know what a microcontroller is and how to program them. You should also understand asynchronous serial communication between microcontrollers and personal computers. You should also understand the basics of P5.js. For greater background on Bluetooth LE, see the BLEDocs repository, or the book Make: Bluetooth by Alasdair Allan, Don Coleman, and Sandeep Mistry.

Here are a few additional usedul Bluetooth LE references:

Things You’ll Need

In order to use the ArduinoBLE library, as shown in Figure 1-2, both Arduino  MKR 1010 and the Arduino Nano 33 IoT boards, among others, work for this tutorial. You could also do this on the Nano 33 BLE.

You might need external components for your own Bluetooth LE project, but for this introduction, you won’t need any external components.

Photo of an Arduino Nano 33 IoT module. The USB connector is at the top of the image, and the physical pins are numbered in a U-shape from top left to bottom left, then from bottom right to top right.
Figure 1. Arduino Nano 33 IoT or Nano 33 BLE or…
Photo of an Arduino MKR 1010 module. The USB connector is at the top of the image, and the physical pins are numbered in a U-shape from top left to bottom left, then from bottom right to top right.
Figure 2. Arduino MKR 1010 module.

Bluetooth LE Concepts

Bluetooth LE devices can be either central devices, or peripherals. Peripheral devices offer Bluetooth services that central devices can receive. For example, your fitness device is a peripheral device and the mobile phone or laptop that connects to it is a central device.

Peripherals offer services, which consist of characteristics. For example, a light controller might offer a light service, with four characteristics: red, green, blue, and white channels. Characteristics have values, and central devices can connect to a peripheral and read, write, or subscribe to those changing values. Characteristics can be assigned any of these three capabilities.

Bluetooth LE devices, services, and characteristics are described using Universally Unique Identifiers, or UUIDs. UUIDs are 128-bit numbers, and are generally formatted like this: cc3e5f6f-9d50-43fb-86e3-1f69e3916064. You can generate UUIDs using uuidgenerator.net. You can also do it on a MacOS or Posix command line by typing uuidgen.

There are certain short UUIDs defined by the Bluetooth LE specification for well-known services and characteristics, such as battery level, Human Interface Device, and so forth. A list of the more well-known UUIDs can be found on the Bluetooth SIG Assigned Numbers page. When you’re making your own services and characteristics, you should generate long UUIDs.

All good Bluetooth LE libraries follow the device, service, characteristic model.  The general process from the peripheral side is as follows:

  • Set peripheral name
  • Establish advertised services
  • Add characteristics to services
  • Start advertising

From the central side, the process is:

  • Scan for peripherals
  • Connect to a given peripheral
  • Query for services
  • Query for characteristics
  • Read, write, or subscribe to characteristics

Bluetooth LE Central Apps

There are a number of good Bluetooth LE Central apps that let you scan for peripherals and interact with their services and characteristics. When you’re developing Bluetooth LE applications, it’s essential to have one on hand. Here are several:

Figure 3 below shows the initial scan for peripherals using BlueSee on macOS. You can see a variety of devices listed by UUID in the first column (note: this is not your service UUID, it’s an ID that MacOS assigns to the BLE device); the received signal strength (RSSI) in the second column; peripheral’s local name in the third column; and manufacturer name and info in the remaining columns. Most central scanning apps will list at least the device UUID and name, and let you connect to one device at a time.

Screenshot of the BlueSee app on MacOS scanning for peripherals.
Figure 3. BlueSee app scanning for peripherals.

Figure 4 shows the characteristic detail from BlueSee when it’s connected to a particular peripheral’s characteristic. In most apps, like in this one, if a characteristic is writable, you can write to it in either hexadecimal or text.

Screenshot of the BlueSee app's Characteristic detail screen.
Figure 4. BlueSee Characteristic detail screen.

Program the Arduino

Make sure you’re using the Arduino IDE version 1.8.10 or later. If you’ve never used the type of Arduino module that you’re using here (for example, a Nano 33 IoT), you may need to install the board definitions. Go to the Tools Menu –> Board –> Board Manager. A new window will pop up. Search for your board’s name (for example, Nano 33 IoT), and the Boards manager will filter for the correct board. Click install and it will install the board definition.

You’ll need to install the ArduinoBLE library too. Go to the Sketch menu –> Include Library… –> Manage Libraries. A new window will pop up. Search for your the name of the library (ArduinoBLE) and click the Install button. The Library manager will install the library.

Once you’ve installed the library, look in the File –> Examples submenu for the ArduinoBLE submenu. In there, look for the Peripherals submenu and open the sketch labeled LED. This sketch turns your board into a peripheral with one service called LED. That service has one characteristic, called switchCharacteristic, that is readable and writable by connected central devices. When you write the value 1 to this characteristic, the on-board LED turns on. When you write 0 to the characteristic, the LED turns off.

The beginning of the sketch establishes the service and characteristic as global variables:

1
2
3
4
5
6
7
8
#include "ArduinoBLE.h"
 
BLEService ledService("19B10000-E8F2-537E-4F6C-D104768A1214"); // BLE LED Service
 
// BLE LED Switch Characteristic - custom 128-bit UUID, read and writable by central
BLEByteCharacteristic switchCharacteristic("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
 
const int ledPin = LED_BUILTIN; // pin to use for the LED

In the setup(), you’ll follow the steps outlined above: set the name and the services, add characteristics, and advertise:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
void setup() {
  // initialize serial and wait for serial monitor to be opened:
  Serial.begin(9600);
  while (!Serial);
 
  // set LED pin to output mode:
  pinMode(ledPin, OUTPUT);
 
  // begin initialization:
  if (!BLE.begin()) {
    Serial.println("starting BLE failed!");
    while (true);
  }
 
  // set advertised local name and service UUID:
  BLE.setLocalName("LED");
  BLE.setAdvertisedService(ledService);
 
  // add the characteristic to the service
  ledService.addCharacteristic(switchCharacteristic);
 
  // add service:
  BLE.addService(ledService);
 
  // set the initial value for the characteristic:
  switchCharacteristic.writeValue(0);
 
  // start advertising
  BLE.advertise();
 
  Serial.println("BLE LED Peripheral");
}

In the loop(), you wait for a central device to connect, and only take action if it does:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
void loop() {
  // listen for BLE peripherals to connect:
  BLEDevice central = BLE.central();
 
  // if a central is connected:
  if (central) {
    Serial.print("Connected to central: ");
    // print the central's MAC address:
    Serial.println(central.address());
 
    // while the central is still connected to peripheral:
    while (central.connected()) {
      // if the central device wrote to the characteristic,
      // use the value to control the LED:
      if (switchCharacteristic.written()) {
        if (switchCharacteristic.value()) {   // any value other than 0
          Serial.println("LED on");
          digitalWrite(ledPin, HIGH);         // will turn the LED on
        } else {                              // a 0 value
          Serial.println("LED off");
          digitalWrite(ledPin, LOW);          // will turn the LED off
        }
      }
    }
 
    // when the central disconnects, print it out:
    Serial.print("Disconnected from central: ");
    Serial.println(central.address());
  }
}

Upload this to your board, then scan for it with a BLE central scanner like BlueSee or LightBlue. When you find it, connect and try to open the characteristic. Then try writing 1 and 0 to it. You should see the LED going on and off.

The general pattern of this sketch is similar for other Bluetooth LE sketches with this library; check out the other examples and you’ll see. Generally, you wait for a central to connect, then all action takes place after that. If the central is driving the action, then your Arduino sketch waits for characteristics to be written to. If your central app is waiting for action from the Arduino, then you’ll write to characteristics in your Arduino sketch, and the central app will see those changes and take action.

A Central App in p5.ble

The Chrome browser has a web bluetooth extension that enables web pages in Chrome to act as Bluetooth LE central devices. The p5.ble library is based on web-bluetooth, and compatible with p5.js. To get started quickly, disconnect your central app from your board if you’re still connected from the section above, and go to the p5.ble write one characteristic example. Click the connect button in that example, and you’ll get a popup scanner. When you see the LED peripheral, connect to it. Once you’re connected, try writing 0 or 1 to the LED. You should be able to control the LED.  The source code for this example is embedded in the example page. You can borrow from it to write your own custom BLE central p5.js sketch. You’ll need to include the p5.ble library in your index.html page as shown on the quickstart page.

In the write one characteristic sketch, you can see the pattern of activity for a central device described above:

Scan for peripherals is handled when you click the Connect button. The scan is filtered to look only for devices with the desired service UUID.

Connect to a given peripheral is handled by the connectToBle function. It connects to a device and the desired service, then runs the gotCharacteristics function as a callback to query for characteristics.

When you click the write button, the writeToBLE function writes to the characteristic to which it’s connected.

Reading and Writing Sensors in p5.ble

The Read From One Characteristic example shows how to read from a peripheral device that’s outputting a changing sensor value. Similarly, the Start and Stop Notifications example shows how to subscribe to a peripheral’s characteristic so as to get notification when it changes. Try these out along with their associated Arduino sketches to get an understanding of how to get sensor data via Bluetooth LE.

You can set up multiple characteristics in a given service, and often this is the best way to handle things. For example, if you were using the built-in accelerometer on the Nano 33 IoT, you might have three characteristics for x, y, and z acceleration all in a single accelerometer service.

Characteristic Data Types

When you initialize your peripheral’s characteristics in your Arduino sketch, you set the data type for the characteristic. Just as there are byte, bool, int, char, String and float data types, there are BLEByteCharacteristic, BLEBoolCharacteristic, BLEIntCharacteristic, BLECharCharacteristic, BLEStringCharacteristic, and BLEFloatCharacteristic data types in the ArduinoBLE library. You should pick the type appropriate for what you’re using it to do. An analog sensor might want an int, for example. A sensor value that you’ve converted to a floating point value like voltage or acceleration might want a float.

Similarly, you can read the characteristics in p5.ble differently when you know what type they might be.  You’ve got  unit8, uint16 or uint32, int8, int16, int32, float32, float64, and string. When you read, you choose the type like so:

1
myBLE.read(myCharacteristic, 'string', gotValue);

You need to match the type you read with on the central side to the type you sent with on the peripheral side. If you’re not sure what type is correct, set up your Arduino sketch to send a constant value using a type you know. Then read  it in p5.ble using the different types until the value you receive matches the value you’re sending. Make sure to test the limits of your data type. For example, in Arduino, an int can store a 16-bit value from -32,768 to 32,767 on an Uno, or a 32-bit value on a Nano 33 IoT or MKR board, from -2,147,483,648 to 2,147,483,647. A 16-bit int would be int16 in p5.ble, and a 32-bit int would be an int32. If you’re using unsigned ints on the Arduino side, then your ranges are different. A 16-bit unsigned int ranges from 0 to 65,535, and a 32-bit unsigned int goes from 0 to 4,294,967,295.

Further Reading

The ArduinoBLE reference is useful if you want to know all the commands that the library can offer. Likewise, the p5.ble reference is a valuable read as well.

The ArduinoBLE library supports both peripheral and central modes on the Nano33’s and the MKR1010. Here’s a pair of sketches that shows how to connect from a central to a peripheral.

Lab: Using a Real-Time Clock

In this lab, you’ll learn how to use a real-time clock on a microcontroller.

In this lab, you’ll learn how to use a real-time clock on a microcontroller.

Introduction

Though this is written for the Arduino Nano 33 IoT and MKR modules, the principles apply to any real-time clock.

A real-time clock (RTC) is an application-specific integrated circuit (ASIC) that’s designed to keep accurate time in hours, minutes, seconds, days, months, and years. Most real-time clocks have a synchronous serial interface to communicate with a microcontroller. The DS1307 from Dallas Semiconductor is a typical one. Each RTC generally has a library to interface with it as well.  Many microcontrollers are incorporating an RTC into the microcontroller chip itself now as well. The SAMD M0+ chip that is the CPU of the MKRs and the Nano 33 IoT has an RTC built into it.

What You’ll Need to Know

To get the most out of this lab, you should be familiar with the following concepts and you should install the Arduino IDE on your computer. You can check how to do so in the links below:

Things You’ll Need

Arduino Nano on a breadboard.
Figure 1. Breadboard view of Arduino Nano mounted on a breadboard.

Image made with Fritzing


You’ll need an Arduino Nano 33 IoT or any of the MKR series Arduinos for this exercise. You don’t need any other parts, unless you plan to connect to external sensors.

As shown in Figure 1, The Nano is mounted at the top of the breadboard, straddling the center divide, with its USB connector facing up. The top pins of the Nano are in row 1 of the breadboard.

Program the Arduino

Make sure you’re using the Arduino IDE version 1.8.9 or later. If you’ve never used the type of Arduino module that you’re using here (for example, a Nano 33 IoT), you may need to install the board definitions. Go to the Tools Menu → Board submenu → Board Manager. A new window will pop up. Search for your board’s name (for example, Nano 33 IoT), and the Boards manager will filter for the correct board. Click install and it will install the board definition.

You’ll need to install the RTC library too. Go to the Sketch menu → Include Library… Submenu → Manage Libraries. A new window will pop up. Search for your the name of the library (RTCZero) and click the Install button. The Library manager will install the library. You might want to open the RTC library documentation in a browser as well. This library should work on any board that uses the SAMD M0+ processor.

Real-time clocks are simple devices. You set the time, then it runs. When you want the time, you read the time. Depending on the software interface of the RTC you’re using, sometimes you can set the time using UNIX Epoch time as well, which is the number of seconds that have elapsed since 00:00:00 Thursday, 1 January 1970. The API may differ from one library to a next, but all RTC libraries will have commands to get and set the hour, minute, second, day, month, and year. The RTCZero is typical in that sense. Here is an example of how to set the time:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <RTCZero.h>  // include the library
RTCZero rtc;           // make an instance of the library
 
void setup() {
  Serial.begin(9600);
 
  rtc.begin(); // initialize RTC
 
  // Set the time
  rtc.setHours(12);
  rtc.setMinutes(34);
  rtc.setSeconds(56);
 
  // Set the date
  rtc.setDay(23);
  rtc.setMonth(6);
  rtc.setYear(19);
 
  // you can also set the time and date like this:
  //rtc.setTime(hours, minutes, seconds);
  //rtc.setDate(day, month, year);
 
  // if you know the epoch time, you can do this:
  rtc.setEpoch(1564069843);
}

To read the time, you use the getter methods: getSecond, getMinute, getHour, etc.:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
void loop() {
  int h = rtc.getHours();
 
  int m = rtc.getMinutes();
  int s = rtc.getSeconds();
  int d = rtc.getDay();
  int mo = rtc.getMonth();
  int yr = rtc.getYear();
  long epoch = rtc.getEpoch();
 
  // make a String for printing:
  String dateTime = "";
  if (h < 10) dateTime += "0";
  // add a zero for single-digit values:
  dateTime += h;
  dateTime += ":";
  if (m < 10) dateTime += "0";
  // add a zero for single-digit values:
  dateTime += m;
  dateTime += ":";
  if (s < 10) dateTime += "0";
  // add a zero for single-digit values:
  dateTime += s;
  dateTime += ",";
  if (d < 10) dateTime += "0";
  // add a zero for single-digit values:
  dateTime += d;
  dateTime += "/";
  if (mo < 10) dateTime += "0";
  // add a zero for single-digit values:
  dateTime += mo;
  dateTime += "/";
  if (yr < 10) dateTime += "0";
  // add a zero for single-digit values:
  dateTime += yr;
  Serial.println(dateTime);
  delay(1000);
}

Using the RTC Alarm

The RTCZero library also has the capability to set an alarm and call a function when the alarm goes off. Not all RTCs offer this feature, but since it’s built into the processor, it’s possible for the Nano 33 IoT and the MKR boards. Here’s a simple example that prints a message once a minute:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <RTCZero.h>
RTCZero rtc;
 
void setup() {
  Serial.begin(9600);
 
  rtc.begin();
  rtc.setTime(12, 23, 56);
  rtc.setDate(23, 06, 19);
 
  // set the alarm time:
  rtc.setAlarmTime(0, 0, 0);
  // alarm when seconds match the alarm time:
  rtc.enableAlarm(rtc.MATCH_SS);
  // attach a function to the alarm:
  rtc.attachInterrupt(alarm);
}
 
void loop() {
  // nothing happens here
}
 
void alarm() {
  Serial.println("Top of the minute");
}


You can match just the seconds for an alarm once a minute (rtc.MATCH_SS) or the minutes and seconds for once an hour (rtc.MATCH_MMSS) or hours, minutes, seconds for once a day (rtc.MATCH_HHMMSS).

Maintaining Time

In order to be truly “real” time, an RTC needs constant power. The built-in RTC of the SAMD M0+ microcontroller will reset to “zero” when power is interrupted (but will continue to increment through a reset provided an initial time is not hardcoded in setup).

For this reason, many RTC breakout boards, such as Adafruit’s DS3231 board, include a battery holder, typically for the kind of long lasting coin-cell batteries found in watches. RTCs powered this way can maintain accurate time for several years without additional power. The Arduino RTC page has notes on maintaining power for the built-in RTC on Arduino Zero and later boards.

Using a Programming Editor

There are many text-only programming editors on the market, designed to be used with different programming environments. When you program using many different environments, it can be helpful to have one editor that you use for all of them, so your editing interface is consistent.

Organizing Projects

Most programming editors organize files in workspaces. A workspace is basically a folder with all your project’s files in it. So to get started, either open a folder or create a new folder, then make new files in it. For example, if you have an Arduino sketch called mySketch, it consists of a folder called mySketch and a file in it called mySketch.ino. A p5.js project is usually a folder called myProject with a few files in it: sketch.js, index.js, and the p5.js libraries.

Extensions or Plugins

Programming editors usually include a way to add extensions or plugins so that you can automate common tasks, use different programming languages easily, and so forth. For example, Visual Studio Code includes two useful plugins for physical computing, the Arduino plugin, which lets you compile Arduino projects and the Live Share plugin, which lets you share code live across a network.

Visual Studio Code

Microsoft Visual Studio Code is an open source programming editor from Microsoft that’s good for many toolchains at ITP: Arduino, p5.js, node.js, Python, and more. It’s designed for keyboard-only use, through the command palette, which can execute any command in the application using keyboard alone.

There are a few main areas of the VS Code application: the editor area, the file explorer, the consoles.

The explorer (command-shift-e) is where you look for files and folders within your workspace. There’s also a tab in the explorer called Outline where you can see a list of the functions in the open code window.

The editor (command-1, 2, 3, etc) is where you edit code. There can be multiple editors open in the same workspace, if you choose to do so.

The panel (control-`) are where you see the output console, the problems console, the command line terminal, serial terminals, and the debug console.

The command palette (command-shift-P) can execute any command in the application using keyboard alone. You can filter it by starting to type the name of the command you want. The Escape key dismisses the command palette.

Note that everything in VS Code is a file or a directory. Even the application Preferences are stored in a giant JSON file, and when you open preferences from the command palette, you can see this JSON file, or an abstracted HTML-style representation of it.

Keyboard Shortcuts

There are many keyboard shortcuts in VS Code, because it’s designed to be used without a mouse. If you can’t remember them all, there is a guide in the program. Type command-K-S to open it in the editor.

Shortcuts in command palette

  • Backspace, then type file name – will open any file in workspace
  • Colon, then type number – goes to line number in current editor window
  • > then type command. This is the default when you open the command palette. When you type any word, it will filter the command list to find matching commands. Then use up and down arrows to navigate the filtered list.

Getting to Files

Command-shift E shifts focus to the File explorer. The up and down arrows will move through the file names VoiceOver will read out the names. Once you know the file names, use either the file palette (command-P) or the command line terminal (described below) to open the file.

Command-P opens the File palette This is a variation on the command palette that opens files. It operates like the command palette. Type the filename to filter the available files in your current workspace.

Shortcuts in the Editor

To get to any line in the editor, open the command palette (command-shift-P), then backspace and type colon-line number to jump to any line. If you’re already in the editor, control-G-line number will do the same thing.

Working in the Panel

The Panel area contains the command line Terminal, the Output Console, the Problems Console, and the Debug Console.

Type control ` to open the terminal. This gets you to a terminal with your operating system’s command line interface in it. Here you can do all the things you can normally do on the command line: list files (ls), change directories (cd), and so forth. From the terminal,, you can also type “code <filename>” to open any file in the current directory into the editor.

Note that Control-G doesn’t jump you to a line number when you are in the terminal. Type control ` to close the terminal first.

Type control-shift-U to get to the Output console. This is where you’ll read the output of any commands run by a compiler, for example the Arduino compiler.

Extensions

Visual Studio Code lets you extend the application with additional modules downloaded from their online repository. Type control-shift-X to enter the Extensions browser. The Extensions browser works like the command palette: type a word to filter the list then use the up and down arrows to navigate the list.

Two useful plugins for physical computing are the the Arduino plugin by Microsoft and the Live Share plugin. If you have the Arduino IDE installed on your machine, the Arduino Plugin for VS Code  lets you compile and upload for all the boards you have installed.The VS Live Share Plugin allows you to share code live with other users over a network in real time. Live share takes a few steps to get it set up, including a couple of trips to the browser to enable access through your GitHub account. The details are explained in the details page for the extension. Once it’s working, it’s a handy tool for sharing code live.

A Note on Notifications

Some actions or extensions pop up notification alerts over your application. These are called toasts in UX parlance, for reasons only the Secret UX Masters of the Universe understand. You can view all current notifications from the command palette: command-shift-P, then type notifications show. You can scroll through them with arrow keys when they are open. To dismiss them, command-shift-P, then type Notifications clear.

Using the Arduino Command Line Interface

For users who prefer to use their own text editor, there is a command line interface version of the Arduino. “arduino-cli is an all-in-one solution that provides builder, boards/library manager, uploader, discovery and many other tools needed to use any Arduino compatible board and platforms.” It allows you to work with your favorite text editor, and to program in a text-only mode. The gitHub repository for the project includes a pretty good getting started guide to the arduino-cli on the main page, but there are a few extra steps you may want to take to set things up for more convenience. These instructions are written for MacOS, but should work on any POSIX operating system, and might work on Windows with the Linux Subsystem for Windows or with Cygwin, an older collection of Linux command line tools for Windows

Note that as of Sept. 2018, the arduino-cli is still in alpha, meaning that features are still subject to change.

Download the Application

From the gitHub repository, download the latest stable release of arduino-cli. Unzip the resulting download and move the unzipped application to your Applications directory (Linux users may prefer to move it to /usr/bin or /usr/local/bin). Then open the Terminal app (MacOS) or a shell window (Linux) to set things up.

Configure Your Command Line Environment

For those new to command line interfaces, there are a few terms that are helpful to know as well. The command line interface for MacOS is called a shell, specifically the bash shell.There are other shell environments for Linux and Unix (sometimes you’ll hear these collectively referred to as POSIX systems; here’s a longer introduction to command line interfaces in POSIX systems), but the bash shell is one of the most common. The parameters of the shell are called environment variables, and for the bash shell on MacOS, they are stored in a file called .bash_profile. They’re different for each user, so the .bash_profile file is kept in each user’s home directory. The path to this directory is  /Users/username on MacOS, or /home/username on Linux. The shortcut for the home directory is ~. For example, ~Documents/ is the path to your Documents folder. When you’re on the command line, you can always get back to the home directory by typing cd and then pressing enter. You can check what directory you are in by typing pwd (for print working directory)

It’s helpful to add a few modifications to your command line environment to make arduino-cli easier to work with. First, open .bash_profile in your favorite text editor. The dot at the beginning of the filename means this is hidden file, so it won’t show up when you list files. To see it using the command line list command (ls), type ls -a and you’ll see all the hidden files. To open any file in your text editor, type

open -a editorName filename

Replace editorName with the name of your editor, For example, to open the .bash profile in XCode, type open -a editorName .bash_profile.

That open trick is so useful that you’ll want to add a shortcut to your profile. At the end of the file, add the following line:

alias xcode="open -a xcode"

Change the alias name and the editor name as you see fit. Now you can open your editor from the command line. This is useful for other development activities, like working in node.js, p5.js, or Python. Next you need to add the Applications directory to your PATH environment variable so that the shell knows where to find it. Add a new line to the file as follows:

export PATH=${PATH}:/Applications

Arduino-cli does not include the built-in examples that come with the original Arduino graphic IDE. If you’ve installed the original IDE, you have them, but you might want to create an shortcut in your Arduino sketches directory to get to them. Here are the paths to the examples for MacOS, Windows, and Linux:

MacOS: (assuming you installed the Arduino IDE in your applications folder already): /Applications/Arduino.app/Contents/Java/examples

Windows 10: C:\Users\”USERNAME”\AppData\Local\Arduino15\packages\arduino

Linux: ~arduino-1.8.x/examples

To create the shortcut, change directories to your sketch directory and type:

ln -s /Applications/Arduino.app/Contents/Java/examples

and you’ll then have be able to get to them directly from the sketches directory. On Linux or Windows, change the path accordingly.

Finally, if you find the default shell prompt too long, you can add a custom shell prompt. For example, the default MacOS shell prompt is computer-name:directory username$. This appears after you run every process on the command line, before you get to run a new process. To shorten the command prompt to a single $, add this line to your .bash profile:

export PS1="$ "

The $ prompt is common enough that you’ll usually see it at the beginning of any command line instructions in tutorials. If you see it, type what follows it at your command prompt.

To put these changes into effect, save your .bash_profile file, type exit on the command line to close your command line session, then re-open a new shell window. In the new window, you should see that the command prompt is now just a $ symbol. To test your editor shortcut, type

$ touch foo.txt

This will create a new file called foo.txt in your current directory. Then type

$ xcode foo.txt

This should launch XCode (or whatever editor you chose) and open the file foo.txt.

Using arduino-cli

To use arduino-cli on the command line, type its name followed by whatever parameters you want to use. If you type arduino-cli with no parameters, you’ll get a list of the commands available. The application that you downloaded is probably not just called arduino-cli, however. It’s probably something longer, like arduino-cli-0.2.2-alpha.preview-osx. Fortunately, you don’t have to type the whole name. The shell will auto-complete any command you type if it can when you press the tab key. If you type ard then press tab, it should autocomplete the name of the program. In this tutorial, the application name will  be shortened to arduino-cli.

To create a new sketch, type:

$ arduino-cli sketch new SketchName

This will create a new sketch in the default Arduino sketch directory. On MacOS, this directory is ~Documents/Arduino/, so the sketch would be in ~Documents/Arduino/. To get to the directory to work on this new sketch, type:

$ cd ~Documents/Arduino/SketchName

Now that you’ve got your command line environment set up, the getting started with arduino-cli guide will take you through the steps of creating a new sketch, configuring the environment, and uploading it. Below is a summary of the commands you’ll use the most.

New Sketch: arduino-cli sketch new mySketch – creates a new sketch called mySketch in the default Arduino sketch directory

List Available boards: arduino-cli board list – list all boards attached to the computer. This is equivalent to getting the port list in the Arduino graphic IDE.

List All Known Boards: arduino-cli board listall – list all boards in your boards manager. This is equivalent to getting the boards list in the graphic IDE. This produces a long list, so if you wanted to search it for a particular subset, you might use the POSIX grep command like so:

$ arduino-cli board listall | grep mkr

The preceding command would list all known boards with the substring mkr in their name.

Compile: arduino-cli compile -b board:name path/to/sketch – compile the sketch for the given board name. This is equivalent to the Verify command in the graphic IDE.  You don’t need the sketch path if you’re already in the sketch directory. For example, to compile the sketch in the current directory for the Uno:

$ arduino-cli compile  -b arduino:avr:uno

Or for the MKRZero:

$ arduino-cli compile  -b arduino:samd:mkrzero

Attach Board: arduino-cli board attach board:name – attaches a specific board name to a sketch. This is equivalent to choosing a board in the graphic IDE. If you do this when you first set up a new sketch, you won’t need to give a board name every time every time you compile, you can just type

$ arduino-cli compile

Upload: arduino-cli upload -p portname – upload compiled sketch to the portname given. This is equivalent to uploading in the IDE. Note that this command does not re-compile before uploading.  For example:

$ arduino-cli upload -p /dev/cu.usbmodem1411

Find a core: arduino-cli core search coreName – searches for known processor architectures. You can search by processor type, like AVR or M0, or you can search by board name, like Mega or MKR. For example:

$ arduino-cli core search mkr

Install a core: arduino-cli core install coreName – installs a core once you find it. ou must use the full core name, though. For example the core search for MKR above resulted in a core called arduino:samd. To install it, type:

$ arduino-cli core install arduino:samd

Find a library: arduino-cli lib search libraryName – searches the Arduino library manager index for libraries containing the word libraryName. For example, the following will list all MQTT-related libraries in the index:

$arduino-cli lib search mqtt

Install a library: arduino-cli lib install libraryName – install a library that’s listed in the Arduino library manager index. For example:

$ arduino-cli lib install WiFiNINA

or for libraries with multiple word names, use double quotes around the name like so:

$ arduino-cli lib install "Arduino Low Power"

For more information, see the arduino-cli guide. Check back frequently for changing features until it is out of alpha.

Using the Serial Port

On MacOS and Linux, the command line allows you to read input from a serial port just as you would from a file, using the cat command. cat /dev/cu.usbmodemXXXX will open an Arduino’s serial port, if no other application has it open already. control-C will close it.

Lab: Arduino and p5.js using a Raspberry Pi

For some applications, you only need a computer with an operating system in order to connect a serial device like an Arduino or other microcontroller with a browser-based multimedia application like p5.js. This page introduces how to do it using node.js, p5.serialserver, and a Raspberry Pi.

Introduction

For some applications, you only need a computer with an operating system in order to connect a serial device like an Arduino or other microcontroller with a browser-based multimedia application like p5.js. Perhaps you’re planning to run the sketch on a mobile device like an iPhone or Android device, but you need it to get data from sensors on your Arduino, or to be able to control motors or other outputs on the microcontroller. For these applications, an embedded Linux processor like a Raspberry Pi or BeagleBone can do the job well. By running an HTTP server and the p5.serialserver application from the Linux command line, you can make this happen. This page introduces how to do it using node.js, p5.serialserver, and a Raspberry Pi.

To get the most out of this tutorial, you should know what a microcontroller is and how to program microcontrollers. You should also understand asynchronous serial communication between microcontrollers and personal computers. You should also understand the basics of command line interfaces. It’s helpful to know a bit about the Raspberry Pi as well, and p5.js. If you’re looking for a Raspberry Pi setup that works on the networks at ITP, try this one. Finally, this tutorial on serial communication using node.js will give you a decent intro to node.js.

System Diagram

The system for this tutorial is as follows: your microcontroller is running a sketch that communicates using asynchronous serial communication, just like many of  the other serial tutorials on this site. It’s connected to an embedded Linux processor (a Raspberry Pi, in this case), which is running p5.serialserver, a command-line version of the p5.serialcontrol app used in the other p5.js serial tutorials on the site. The Pi is also running a Python-based HTTP server, which will serve your p5.js sketch and HTML page to any browser on the same network. The p5.js sketch uses the p5.serialport library to communicate back to p5.serialserver on the Linux processor in order to read from or write to the microcontroller’s serial port. The diagram below shows the system(Figure 1):

This is a system diagram that depicts the system described in the paragraph above. The browser device is on the left. The Raspberry Pi is in the center, and the Arduino is on the right.
Figure 1. Raspberry Pi serving p5.js files and running p5.serialserver

Node.js

The JavaScript programming language is mainly used to add interactivity to web pages. All modern browsers include a JavaScript interpreter, which allows the browser to run JavaScript code that’s embedded in a web page. Google’s JavaScript engine is called v8, and it’s available under an open source license. Node.js wraps the v8 engine up in an application programming interface that can run on personal computers and servers. On your personal computer, you run it through the command line interface.

Node was originally designed as a tool for writing server programs, but it can do much more. It has a library management system called node package manager or npm that allows you to extend its functionality in many directions. There is also an online registry of node libraries, npmjs.org. You can download libraries from this registry directly using npm. Below you’ll see npm used to add both serial communication functionality and a simple server programming library to node.

Install Linux, Node.js, and p5.serialserver

To get started, you’ll need to set up a Raspberry Pi for command line access. Follow this tutorial on how to set up the Rasberry Pi with th latest Raspbian distribution of Linux, with node.js and a firewall installed.

If you’ve never used a command line interface, check out this tutorial on the Unix/Linux command line interface.  From here on out, you’ll see the command prompt indicated like this:

yourlogin@yourcomputer ~$

Any commands you need to type will follow the $ symbol. The actual command prompt will vary depending on your operating system. On Windows, it’s typically this: >. On most Unix and Linux systems, including OSX, it’s $. Since this tutorial is only for Linux, look for the $.

Post-Install Checklist

Once you’ve installed everything from the previous tutorial, run the following commands on the command line of the Pi to make sure everything you need is installed. If you get the answers below, you’re ready to move on.

To check the version of the Raspbian distribution of Linux that you’re using, type:

$ lsb_release -a

You should get something like this or later:

No LSB modules are available.
Distributor ID: Raspbian
Description: Raspbian GNU/Linux 9.1 (stretch)
Release: 9.1
Codename: stretch

To get the versions of node.js,  npm, and iptables that you’re running, type (and get the replies below, or later):

$ node -v
v6.9.5

$ npm -v
3.10.10

$ sudo iptables --version
iptables v1.6.0

To check that your iptables firewall configuration is correct, type:

$ sudo iptables -S

You should get something like this, though your IP addresses for your router and gateway on lines 9 and 10 might be different:

-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -i wlan0 -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -i wlan0 -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -i wlan0 -p tcp -m tcp --dport 8080 -j ACCEPT
-A INPUT -i wlan0 -p tcp -m tcp --dport 8081 -j ACCEPT
-A INPUT -s 192.168.0.1/32 -i tcp -p tcp -m tcp --dport 22 -j DROP
-A INPUT -s 192.168.0.0/24 -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-port-unreachable
-A FORWARD -j REJECT --reject-with icmp-port-unreachable

Get your Pi’s IP Address

It’s easy enough to run a simple HTTP server on your Pi, and then to use it to serve an HTML page with a p5.js sketch to any browser. First you’ll need to know your Pi’s IP address. You can get it like so:

$ sudo ifconfig wlan0 | grep inet

You’re using the ifconfig command to get the data on the wlan0 network interface. That’s your Pi’s WiFi radio. Then you’re passing the output from ifconfig to the grep program using a pipe (the | character). grep searches through the results for any line beginning with the string ‘inet’. Your result will look something like this:

inet 192.168.0.11 netmask 255.255.255.0 broadcast 192.168.0.255
inet6 2604:2000:c58a:da00:3b21:bed1:e1bb:8c3c prefixlen 64 scopeid 0x0<global>
inet6 fe80::52a3:f22:847f:7beb prefixlen 64 scopeid 0x20<link>

Your numbers will vary, but the one you want will be the four decimal numbers  following the first ‘inet’; 192.168.0.11 in the example above, but yours will be different depending on your network. That’s your IP address. Remember it, you’ll use it in a moment to browse files on your Pi.

Make a Simple Web Server on your Pi

To get your p5.js sketch and HTML page from the Pi, you’ll need to run a web server program. The installed version of the Python programming language includes one already. You need some content to serve. Make a p5.js project. You can download the p5.js example project. You can create all the files yourself, or you can download the files automatically using a command line tool called p5-manager. To install it, type:

$ sudo npm install -g p5-manager

This install might take awhile (45-70 minutes on a Pi Zero W), so take a break while it installs. When it’s installed, you can create a new p5 project anywhere like so:

$ p5 g -b myProject

This will generate (g -b stands for generate bundle) a directory called myProject containing all the files you need for a p5.js project. Change directories into your new project, then update your project’s p5.js files to the latest versions like so:

$ cd myProject
$ p5 update
p5-manager version 0.4.1
The latest p5.js release is version 0.5.16

The sketch.js file in this project doesn’t do anything, so you might want to edit it. You can edit it using the command line editor called nano like so:

$ nano sketch.js

You’ll get a full edit window like the one below, and you can move around the window with the arrow keys. Add the following lines to sketch.js’ draw() function:

1
2
3
4
5
function draw() {
    background('#3399FF');
    fill('#DDFFFF');
    ellipse(width / 2, height / 2, 50, 50);
}

To save the file, type control-X, then Y to confirm. The nano editor will quit and you’ll be back on the command line. Now run Python’s simpleHTTPServer like so:

sudo python -m SimpleHTTPServer 8080

You should get a reply like this:


Serving HTTP on 0.0.0.0 port 8080 ...

Now go to a web browser and enter your IP address from above like so: http://192.168.0.11:8080. You should see a page with a p5.js sketch in it like this(Figure2):

Screenshot of a p5.js sketch running in a browser. a light blue ball on a brilliant blue field fills the canvas of the sketch.
Figure 2. The p5.js serial sketch p5.js sketch running in a browser

Congratulations, your Pi is now a web server! Now you’re ready to add the serial connection.  Type control-C to quit the SimpleHTTPServer.

Add node serialport and p5.serialserver

The next pieces to add are node’s p5.serialserver, which depends on the  node serialport library. The serialport library has to be downloaded and compiled natively for your processor. As the node serialport documentation explains, you’ll need to do it as shown here. You’re enabling unsafe permissions, and building from the source code.The unsafe permissions are needed to give your user account permission to access the /dev directory, in which serial port files live. You can do this all at once, by installing p5.serialserver with the same options, like so:

$ sudo npm install -g p5.serialserver --unsafe-perm --build-from-source

This install will take a long time, so again, take a break (60-90 minutes on a Pi Zero). Once it’s successfully installed, you’ve got all the pieces you need to serve serial-enabled p5.js sketches from your Pi, supplying the serial connection via the Pi’s serial ports.

The Raspberry Pi Serial Ports

There are a couple of ways you can access a serial port on the Pi. The GPIO port for the Pi includes a serial port on pins GPIO14 and GPIO15 (Figure 3.). This port is known as /dev/ttyS0 to the operating system.

The Raspberry Pi's GPIO pin diagram
The Raspberry Pi’s GPIO pin diagram.

Table 1 below details the pin functions

Left SideRight Side
3.3V Power5V Power
GPIO 2 (SDA)5V Power
GPIO 3 (SCL)Ground
GPIO 4 (GPCLK0)GPIO 14 (TX)
GroundGPIO 15 (RX)
GPIO 17GPIO 18 (PWM0)
GPIO 27Ground
GPIO 22GPIO 23
3.3V PowerGPIO 24
GPIO 10 (SPI SDO)Ground
GPIO 9 (SPI SDI)GPIO 25
GPIO 11 (SPI SCLK)GPIO 8 (CE0)
GroundGPIO 7 (CE1)
GPIO 0 (ID_SD)GPIO 1 (ID_SC)
GPIO 5Ground
GPIO 6GPIO 12 (PWM0)
GPIO 13 (PWM1)Ground
GPIO 19 (SPI SDI)GPIO 16
GPIO 26GPIO 20 (SPI SDO)
GroundGPIO 21 (SPI SCLK)

If you’re connected to your Pi through a serial terminal connection, you’re going to have to give that up to talk to your microcontroller. To do that, first log out from the serial terminal and log in via ssh over a network connection. Once you’re logged in over the network, launch raspi-config:

$ sudo raspi-config

Pick option 5, interfacing options, and enable the serial port but disable the serial terminal. Save your choice, exit raspi-config, and restart your Pi:

$ sudo reboot

To get a list of your Pi’s ports, type the following:

$ ls /dev/tty*

You’ll get a long list, most of which are not your ports, and you’ll see the TTYS0 port toward the end. If you have an Arduino or other USB-to-serial device attached, you might see other ports marked TTYUSB0 as well. To determine which are the USB serial devices, run the ls command, then unplug the device, then run it again to see what disappears.

To connect a microcontroller to the GPIO serial port, attach the TX from your controller to the RX of the GPIO port and vice versa. Attach the ground of the GPIO port to the ground of your controller as well. The diagram below(Figure 4) shows the Pi connected to an Uno.

Pi to Uno configuration. Pi is connected to uno through ground pins, as well as, GP 14 (TX) to RX and GP 15(RX) to TX
Figure 4. Raspberry Pi connected serially to an Arduino Uno.

If you’re connecting to a Nano 33, MKRZero, MKR1000, Feather M0 Leonardo, Micro, or any of the boards based on the ARM M0 or ATMega 32U4, connect RX to TX and vice versa, but be aware that the RX and TX pins of those boards are addressed using Serial1 instead of Serial. For example, you’d call Serial1.begin(), Serial1.println(), and so forth.

You can also add serial ports as you would on a laptop, by plugging in a device that is compatible with a USB serial COM driver, like an Arduino. If you’re using a Pi Zero, you’ll need to use a USB-on-the-go adapter to connect to the Zero’s USB port.

The compatibility of your device will depend on the compatibility of the device’sUSB-to-serial chip. The official Arduino models comply with the USB standard serial COM protocol, and require no drivers. Third party and derivative models will vary depending on the hardware. If you want to avoid any driver issues and additional USB cables, use the GPIO serial port.

To test whether you’ve got control over the serial port, put a sketch on your microcontroller that sends out serial messages, like the AnalogReadSerial sketch in the Arduino Basics examples. Connect the controller to your Pi, and then use the cat command to read from the serial port like so:

$ cat /dev/ttyS0

You should see the serial data coming in just as you might in the Arduino Serial Monitor. If you do, you’re ready to build a full serial application. To quit cat, type control-C.

Making a Dynamic p5.serialport Sketch

For background on p5.serialport, see the lab on serial input to p5.js.  To start with, you’ll need a microcontroller sending out serial data. Attach a potentiometer to pin A0 of your ArduinoStart, then with this basic handshaking sketch. Using handshaking (also sometimes called call-and-response) keeps the Pi’s serial buffer from getting full:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void setup() {
  Serial.begin(9600); // initialize serial communications
  while (!Serial.available()) { // until the server responds,
    Serial.println("Hello");    // send a hello message
    delay(500);                 // every half second
  }
}
 
void loop() {
  // if there are incoming bytes:
  if (Serial.available()) {
    // read incoming byte:
    int input = Serial.read();
    // read the input on analog pin 0:
    int sensorValue = analogRead(A0);
    // print out the value you read:
    Serial.println(sensorValue);
    delay(1); // delay in between reads for stability
  }
}
Schematic view of a potentiometer. First leg of the potentiometer is connected to +5 volts. The second leg connected to analog in 0 of the Arduino. The third leg is connected to ground.
Figure 5. Schematic view of a potentiometer connected to analog in 0 of the Arduino
Breadboard view of a potentiometer. First leg of the potentiometer is connected to +5 volts. The second leg connected to analog in 0 of the Arduino. The third leg is connected to ground.
Figure 6. Breadboard view of a potentiometer connected to analog in 0 of an Arduino

On the command line, create a new p5 sketch like so, then change directories to get into the sketch, then update the libraries:

$ p5 g -b serialSketch
$ cd serialSketch
$ p5 update

You’ll need the p5.serialport library to your sketch as well. You can copy it into the libraries directory like so:

$ sudo curl https://raw.githubusercontent.com/vanevery/p5.serialport/master/lib/p5.serialport.js --output libraries/p5.serialport.js

Once you’ve done that, edit the index.html file using nano as you did for the sketch.js above, and add a script include for libraries/p5.serialport.js in the HTML document’s head, before the script include for the sketch.js.

Save the file, then edit the sketch.js as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
var serial; // instance of the serialport library
var portName = '/dev/ttyS0'; // fill in your serial port name here
 
var circleSize = 50;
 
function setup() {
  createCanvas(320, 240);
  // initalize serialport library to connect to p5.serialserver on the host:
  serial = new p5.SerialPort(document.location.hostname);
  // set callback functions for list and data events:
  serial.on('list', printList);
  serial.on('data', serialEvent);
  // open the serial port:
  serial.open(portName);
}
 
function draw() {
  background('#3399FF');
  fill('#DDFFFF');
  // draw a circle at the middle of the screen:
  ellipse(width / 2, height / 2, circleSize, circleSize);
}
 
function serialEvent() {
  // read a line of text in from the serial port:
  var data = serial.readLine();
  console.log(data);
  // if you've got a valid line, convert it to a number:
  if (data.length > 0) {
    circleSize = int(data) / 4;
  }
  // send a byte to the microcontroller
  // to prompt it to respond with another reading:
  serial.write("x");
}
 
function printList(portList) {
  // portList is an array of serial port names:
  for (var i = 0; i < portList.length; i++) {
    console.log(i + ' ' + portList[i]);
  }
}

Note that when you’re calling new SerialPort();, you’re including a parameter, document.location.hostname. This is the address from which your sketch was served, in this case, your Pi. You can enter a specific IP address or domain name if you prefer, but document.location.hostname will always return the address of the server. This is the key to making your p5.serialport sketch dynamic, so it’s not locked to localhost.

At this point you have enough of a sketch to test the system. When loaded in a browser, this sketch should look like the one above, and should print the list of serial ports to the JavaScript console.

Run python’s SimpleHTTPServer a little differently this time:

$ python -m SimpleHTTPServer 8080 &

The & makes python return control to the command line so you can do other commands while it’s running. Hit the return key to get a command prompt again, then type:

$ p5serial

You should get this response:

p5.serialserver is running

Do as you did above, and open the sketch in a browser again. This time, open your JavaScript console and you should see the following output:

ws://192.168.0.12:8081
p5.serialport.js:83 opened socket
sketch.js:20 0 /dev/ttyAMA0
sketch.js:20 1 /dev/ttyS0

You should also see the serial data coming in from the microcontroller, and if you turn the potentiometer, you should see the circle size change. If you get this, do a happy dance. You’ve got a working p5.serialserver system working.

To quit p5.serialserver, type control-C. To stop the SimpleHTTPServer, type the following to get a list of the running processes:

$ ps
PID TTY TIME CMD
785 pts/0 00:00:02 bash
8186 pts/0 00:00:00 python
8203 pts/0 00:00:00 ps

This is a list of all running user-started processes and their process numbers. The python SimpleHTTPServer is number 8186 above. To stop it, type:

$ kill 8186

with your own process number, and python will stop. In the future, you can run p5serial this way as well, to get the command line control back while it’s still running.

Once you’ve got this much working, all the same dynamics of serial communication that apply on your desktop also apply on the Pi. Only one program at a time can control the port. Both sides need to agree on electrical connections, timing, and data format. Handshaking can help manage traffic flow. The troubleshooting techniques you used in desktop serial apply here also.

The Pi isn’t perfect as a multimedia host for all projects. It’s not as good on graphics as even the most basic desktop computer, for example. It’s great as a network connector like this, though, and it’s great to serve browser-based content that needs to connect to a serial port.

For more info: