In this lab you’ll learn about converting voltage levels to make components communicate better.
In this lab you’ll learn about converting voltage levels to make components communicate better.
Introduction
Different microcontrollers and other digital devices operate on a range of different voltages. For many microcontrollers, 5V has been a common standard operating voltage for many years. Recently, however, new controllers are coming on the market that operate only at lower voltages. 3.3V has become common, and some controllers even operate as low as 1.7V. Just as microcontrollers are changing, the sensors and actuators that attach to them are changing as well. For example, many accelerometers on the market now operate at 3.3V instead of 5V. Because of this, you sometimes need to convert the output voltage of one device to match the input voltage of another. This is called level shifting. There are a number of ways to do it.
Most of the time that you need to shift voltage levels, you’re working with a voltage source that’s very low amperage, like a microcontroller’s I/O pins or the signal output from a sensor. Another common application is when you’re connecting a 5V microcontroller Like the Uno to a 3.3V board like the Raspberry Pi. You need to shift the Uno’s 5V signals to 3.3V for the Pi.
You know from the introductory electronics notes that two resistors in series can form a voltage divider (Figure 1). This is one way to reduce the voltage of a circuit. You need to calculate the ratio of the resistors based on the ratio of the input voltage to the output voltage. Here’s a handy calculator for working those values out. The tricky part about this is having the exact right resistors for the job. Also, resistors can slow down a high-speed signal because they have a built-in impedance, meaning that the voltage across them doesn’t change instantaneously. This can be a problem if you’re sending a high-speed serial signal, for example.
You can also use a zener diode to reduce the voltage. Zener diodes are diodes that allow current to flow from anode to cathode just like a regular diode, but also allows current to flow from cathode to anode up to a particular voltage, called the breakdown voltage. Zener diodes come in various breakdown voltages, so you can choose the one that works for your application. For example, the 1N5226 is a common 3.3V Zener diode, and the the 1N4733 is a common 5.1V Zener diode. When you’re using a Zener diode as a voltage shifter, you connect the cathode to the source, and the anode to the output, usually with a pulldown resistor as shown below in Figure 2.
Figure 2. This is a typical circuit for 5V-to-3.3V level shifting. If Vin is 5V, then V out will be 3.3V with this circuit.
Level Shifting With a Level Shifter IC
If you’ve got several of I/O pins to shift, then you can use a level shifter IC. These chips contain all the circuitry to shift from one level to another for you automatically. They are generally the most expensive solution, but the most reliable and convenient. Texas Instruments makes a series, the TXB010X family, that are popular in physical computing applications. The TXB chips can automatically detect the input and output levels and do the shifting for you. They come in 4-channel and 8-channel models, (TXB0104 and TXB0108) and both Sparkfun and Adafruit stock breakout boards for them. Texas Instruments has a detailed introduction to logic guide, and an application note for these chips as well. Many other manufacturers make level shifters; this family is just one convenient model. Figure 3 shows how you’d use a TXB0104 to connect an Uno to a Raspberry Pi.
Figure 3. Level shifting between an Arduino Uno and a Raspberry Pi using a TXB0108. Image made with Fritzing
The TXB101X level shifters have two voltage input pins, VccA and VccB VccB is the higher voltage input and VccA is the lower. You can see in the diagram above, VccA is connected to the Pi’s 3.3V out pin. Both devices are connected to the level shifter’s ground, so there is a common ground. Wired this way. the level shifter knows that all the A pins will be 3.3V and the B pins will be 5V, and it will convert between them. For more information, Sparkfun has a nice hookup guide for this chip. Note that their breakout board has a different pin arrangement than Adafruit’s, but operates in the same way.
In this lab, you’ll get to know serial communication from a microcontroller to your personal computer a bit more in depth, so that you’re ready to start writing programs in other languages on your computer to interact with our microcontroller.
Introduction
From the first digital I/O and analog labs, you’ve been using asynchronous serial communication in order to send data back to the Arduino Serial Monitor. In this lab, you’ll get to know serial communication from a microcontroller to your personal computer a bit more in depth.
There are many programming APIs that can communicate with your computer’s serial ports. Among them are Processing, node.js, p5.js with the p5.seriaport library and p5.serialcontrol app, or p5.js with the p5.webserial library. There are many others as well. This lab won’t introduce you to any of those just yet; instead, it’ll introduce you to serial terminal applications other than the Arduino Serial Monitor, and it will give you some background on how serial data is formatted when it’s sent from one device to another. In this lab, you’ll send data from multiple sensors from Arduino to your computer and learn how to format the data, and to manage the exchange between the two.
What You’ll Need to Know
To get the most out of this Lab, you should be familiar with how to program an Arduino, and with the basics of serial communication. If you’re not, review the links below:
Some of the examples below show you how to connect to a serial port using the Linux or Unix command line tools. Collectively, Linux, Unix, and similar systems are sometimes called POSIX systems. Unix is built in on MacOS. If you’re using Windows 10 or Window 11, you should install Windows Subsystem for Linux, which will give you a Linux command line environment on your Windows machine. Instructions and tips for setting up the environment can be found at this link: Windows Subsystem for Linux (WSL). The command line applications shown here are not part of the regular Windows OS, but they are available in wsl.
Things You’ll Need
Figures 1-5 below are the parts you’ll need for this exercise. Click on any image for a larger view.
Figure 1. Microcontroller. Shown here is an Arduino Nano 33 IoT
Figure 2. Jumper wires. You can also use pre-cut solid-core jumper wires.
Figure 3. A solderless breadboard
Figure 4. A pushbutton
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:
Figure 6. A joystick, which consists of two potentiometers and a pushbutton
Figure 7. Rotary encoders, which include a built-in pushbutton
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.
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.
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.
To get started, upload the following sketch to your Arduino board, then open the Serial Monitor:
1
2
3
4
5
6
7
8
9
voidsetup() {
// start serial port at 9600 bps:
Serial.begin(9600);
}
voidloop() {
intanalogValue =analogRead(A0);
Serial.println(analogValue);
}
This will read the value from the first potentiometer, and print it to the Serial Monitor. You’ve already done this in the earlier labs. Now let’s get a deeper understanding of what’s going on between the Arduino and your personal computer.
Serial Terminal Programs
The Arduino Serial Monitor is a good basic way to see your serial communications, but it’s not the only way to view incoming serial data on your computer. There are many different serial terminal programs. Serial terminal programs allow you to send and receive messages from your computer’s serial ports. There are both graphical serial applications like CoolTerm or Serial Studio, and there are ways to read from the serial port from the command line terminal of your computer. For a beginner, the Arduino Serial Monitor does the job fine, but as you get more familiar with serial communication, you may want to get to know some of these. If you want to know about a few of them, read on. If not, feel free to skip to the next section on initializing serial communication.
Connecting via the POSIX Command Line
You can use a command line interface as a serial terminal program on MacOS or Linux, or Windows Subsystem for Linux (WSL). The simplest thing you can do with serial ports on the command line is to listen for incoming serial messages. Make sure your Arduino is running a sketch with at least one Serial.print() or Serial.println() statement in your code, like the one above.
On MacOS, open the Terminal app, then get a list of your serial ports by typing ls -1 /dev/cu.*
On Linux, you might need to type ls -1 /dev/cu* or ls -1 /dev/tty* instead.
On Windows, once you’ve installed WSL, open the Start Menu and type wsl to open a linux command line. Then when the command line window opens, type ls -l /dev/tty*
Each tty port in WSL corresponds to a COM port in Windows. So if your Arduino is showing up as COM7 to the Arduino IDE, then it’d be /dev/ttyS7 in wsl. It’s similar in Linux.
In MacOS, the Arduino is the one labeled usbmodemXXXX, as you’ve seen before in the Arduino IDE’s Serial Monitor. To see what the Arduino is sending out, type:
cat /dev/cu.usbmodem14131
in Windows and Linux, you’ll need to run the cat command as an admin user, so type:
sudo cat /dev/ttyS6
You’ll be prompted for your admin password. Enter it, then the command will run.
The terminal will then print out whatever the Arduino is sending. It’s using a POSIX command line application called cat, short for concatenate. This same application can be used for listing the contents of a file files, like so: cat filename.txt
To close the port and quit the cat application, type control-C. If you’ve got a continually repeating serial output, you may prefer to use the less command instead of cat. less /dev/cu.usbmodemXXXX will also print out the serial output, but it will stop after each screenful. Type the spacebar to page through multiple screens, or use the arrow keys to read up and down. Type q to exit.
Using the Command Line for Duplex (two-way) Communication
Another useful POSIX command line tool is the screen program. This allows you to both read from and write to a serial port. Type screen followed by the name of your serial port to open the interactive serial monitor called screen. Yours might look like this:
screen /dev/cu.usbmodem-1421
On Windows and Linux, remember to use sudo:
sudo screen /dev/ttyS6
The screen program will take your terminal over. You will be able to type messages to be sent out the serial port in addition to receiving them in the port. To end the screen program, type control-A control-D. This will quit the program.
NOTE: only one program can control a serial port at a time. When you’re not using a given program, remember to close the serial port. You won’t be able to re-program your Arduino module if you don’t, because the serial terminal program will have control of the serial port.
CoolTerm is a more fully-featured GUI serial terminal program. It’s free, it’s available for OSX, Windows and Linux, and includes some features you don’t get from the Serial Monitor, like being able to open multiple ports in multiple windows, being able to view your data in ASCII (Figure 10) or hexadecimal (Figure 9) values, and more.
Serial Studio is a fully-featured serial terminal program that allows you to configure dashboards to display data via JSON, send data over a network via MQTT or UDP, and many more features. It’s more than a beginner needs, but a useful advanced user’s tool.
The Serial Monitor, CoolTerm, Serial Studio and the screen program on the command line are all examples of a serial terminal program.
Figure 9. The CoolTerm serial terminal application showing the hexadecimal view.
Figure 10. The CoolTerm serial terminal application showing the ASCII view.
Initializing Communication
What is asynchronous serial communication, anyway? Serial means that the two computers communicating are doing so one bit at a time, by sending pulses of data back and forth. Asynchronous means that the two computers that are communicating are each keeping track of time independently. As you know from the Asynchronous Serial Communications: the Basics page, there are three things the two computers need to agree upon:
Electrical: what is the voltage of the pulses?
Data rate: How often is a bit of data sent?
Logic: Does low voltage mean the bit is a 0 or a 1?
Electrical and logic agreements are set for you when you use an Arduino. You set the data rate in your code. In your Arduino sketches so far, you’ve been setting the data rate to 9600 bits per second with this line:
Serial.begin(9600);
Whatever program you’re communicating to (whether it’s the Serial Monitor, CoolTerm, Serial Studio, the command line or another programming environment) has to set the same data rate. You can change both, as long as you change them to the same rate.
There are three connections between the two computers:
a transmit line from sender to receiver
a receive line from receiver to sender
a common ground line
The transmit (sometimes called TX) and the receive (sometimes called RX) are relative: my transmit is connected to your receive, and vice versa. On the Arduino Uno and Nano 33 IoT, digital pins 0 and 1 are used for receive and transmit. They are attached to the USB-to-serial chip on the board. When you plug the Arduino into the computer, it shows up as a USB COM device, meaning a serial communications device. When you ask for a list of serial ports, whether in the Arduino Serial Monitor, CoolTerm, or any program, the Arduino will show up as a new port.
ASCII vs. Binary: What are you sending?
In order to communicate clearly between two devices, you need to understand how the devices are encoding the data which they’re communicating. There are two main approaches most computers use. They will either send the data directly, as a series of bits (this is called raw binary data), or they will encode the information as a series of alphanumeric characters (this is called ASCII-encoded data). This section explains the difference between ASCII and raw binary data.
To begin with, just send the value from one sensor, the first analog sensor (the first axis of the accelerometer in the photos) and divide the output to give a maximum value of 1023:
1
2
3
4
5
6
7
8
9
voidsetup() {
// start serial port at 9600 bps:
Serial.begin(9600);
}
voidloop() {
intanalogValue =analogRead(A0);
Serial.println(analogValue);
}
When you open the serial monitor, you should see a number between 0 and 1023 scrolling down the window. That’s because Serial.println()formats the value it prints as an ASCII-encoded decimal number, with a linefeed at a carriage return at the end. To send the value 1023, for example, println() sents six bytes: the characters 1, 0, 2, and 3, and a carriage return byte and a newline byte. Meanwhile, the serial monitor, receiving the data, assumes it should show you the ASCII character corresponding to each byte it receives.
The output from analogRead() can’t fit in a single byte, because the microcontroller’s analog-to-digital converter (ADC) reads the input with a resolution of 10 bits, or 210. To get the output into a single byte, map the output to a range from 0-255 like so:
Try it now, and your output should range from 0 to 255.
Try changing the Serial.println() to a Serial.write(). Now you get a range of garbage characters (Figure 11). What’s going on? The Serial.write() command doesn’t format the bytes as ASCII characters. It sends out the binary value of the sensor reading. Each sensor reading can range from 0 to 1023; in other words, it has a 10-bit range, since 210 = 1024 possible values. Since that’s more than the eight bits that can fit in a byte, you can either divide the value by 4 in the code above or use the map() function to get a range from 0 to 255, or 28 bits. For more background on this, see the notes on variables.
Figure 11. The Arduino IDE with the serial monitor open
So, for example, if the sensor reading’s value is 234, then the Serial.write()command sends the binary value 11101010. If the reading is 255, then Serial.write() sends 11111111. If it’s 157, then the command sends 10011101. For more decimal-to-binary conversions, open your computer’s calculator and choose the Programmer view (press apple-3 on a mac, and Alt-3 on Windows). Sometimes you’ll see byte values in hexadecimal as well; for example, both CoolTerm and Serial Studio have hexadecimal modes. You can use the calculator to do these conversions too.
The garbage characters are characters corresponding to the ASCII values the Monitor is receiving. When the Serial Monitor receives a byte, it and assumes it should show you the ASCII character corresponding to that byte’s value.
For example, imagine that analogValue = 32:
Serial.println(analogValue) results in “32” with a linefeed and carriage return
Serial.write(analogValue) results in ” “, the space character, which has the ASCII value 32.
How many bytes does Serial.println(analogValue) send when analogValue = 32?
Serial.println(analogValue) actually sends FOUR bytes! It sent a byte to represent the 3, a byte to represent the 2, a byte to tell the Monitor to move the cursor down a line (newline), and a byte to move the cursor all the way to the left (carriage return). The raw binary values of those four bytes are 51 (ASCII for “3”), 50 (ASCII for “2”), 10 (ASCII for “newline”), and 13 (ASCII for “carriage return”). Check the ASCII table and you’ll see for yourself.
Serial.write(mappedValue); // Print the raw binary value
Serial.print('\t'); // print a tab
// print ASCII-encoded values:
Serial.print(mappedValue, BIN); // print ASCII-encoded binary value
Serial.print('\t'); // print a tab
Serial.print(mappedValue); // print decimal value
Serial.print('\t'); // print a tab
Serial.print(mappedValue, HEX); // print hexadecimal value
Serial.print('\t'); // print a tab
Serial.print(mappedValue, OCT); // print octal value
Serial.println(); // print linefeed and carriage return
}
You should get output like this:
â 11100010 226 E2 342
á 11100001 225 E1 341
á 11100001 225 E1 341
á 11100001 225 E1 341
à 11100000 224 E0 340
à 11100000 224 E0 340
ß 11011111 223 DF 337
ß 11011111 223 DF 337
ß 11011111 223 DF 337
This sketch is printing the raw binary value, then the ASCII-encoded binary value, then the ASCII-encoded decimal, hexadecimal, and octal values. You may never need all of these different formats, but you’ll likely need at least the decimal and the raw binary versions at some point.
What’s this \t, \r and \n Stuff, Anyway?
The ASCII table contains several characters that are “invisible”, like tab, newline, carriage return, and so forth. These characters tell the receiving program how to format the visible characters on the screen; newline tells the receiver to move down a line; carriage return tells it to move to the left edge of the screen, and so forth. In most programming languages, these characters are denoted with an escape string starting with a backslash: \. For example, newline is \n. Carriage return is \r. Tab is \t. When you see an escape string in a code sample, replace it with the appropriate ASCII value in your mind.
Send the values for all three sensors
In the first example above, using Serial.write(), you sent one byte representing one sensor’s value, over and over. When you’re sending multiple sensor values, it gets a little more complicated. You need to a way to know which value represents which sensor. For example, imagine if you sent the value of the potentiometers like so:
1
2
3
4
5
6
7
8
9
voidloop() {
intsensor1Value =analogRead(A0);
Serial.print(sensor1Value);
Serial.print(",");
intsensor2Value =analogRead(A1);
Serial.print(sensor2Value);
Serial.print(",");
}
You’ll get a string like this:
452,345,416,234,534,417,325,452,231
How can you tell which value corresponds to which sensor? You don’t know which sensor is which. You could assume that if you start listening when the microcontroller starts sending that the first reading corresponds to the first sensor, but you can’t know that for sure. There are two ways to get your sensor values in order. You can use punctuation or you can use a call-and-response or handshaking method. Use whichever makes the most sense to you. They’re explained below.
Formatting Multiple Serial Data: Punctuation
One way to send the data such that it can be interpreted clearly is to punctuate each set of data uniquely. Just as a sentence ends with a period, you can end your data with a carriage return and a newline. Change the code above as shown below so that a carriage return and newline are printed at the end of each string of values.
1
2
3
4
5
6
7
8
9
voidloop() {
intsensor1Value =analogRead(A0);
Serial.print(sensor1Value);
Serial.print(",");
intsensor2Value =analogRead(A1);
Serial.println(sensor2Value);
}
From this loop, you’d get output like this:
452,345
234,534
325,452
This is much better. Whenever you get a newline, you know that the next value is the first sensor.
Now write a program that reads the two analog sensors on your board and the one digital switch, and prints them out in this format:
Start by setting up a constant for the switch pin’s number. Then in the setup, initialize serial communications at 9600bps, and declare the switch pin as an input.
1
2
3
4
5
6
7
8
9
constintswitchPin =2; // digital input
voidsetup() {
// configure the serial connection:
Serial.begin(9600);
// configure the digital input:
pinMode(switchPin, INPUT);
}
In the main loop, use a local variable called sensorValue to read each input. You can re-use the variable after each read because you don’t need the sensors’ values once you print them. Read the two analog inputs first, and print them with a comma after each one. Then read the digital input, and print it with a carriage return and linefeed at the end.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
voidloop() {
// read the sensor:
intsensorValue =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(switchPin);
// print the results:
Serial.println(sensorValue);
}
Once you’ve got a data format, all you have to do is to write a program that reads that format. You’ll see how do to that in this lab:
Punctuation helps keep your data in order, but because asynchronous serial communication is asynchronous, 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
8
voidsetup() {
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
23
voidloop() {
if(Serial.available()) {
// read the incoming byte:
intinByte =Serial.read();
// read the sensor:
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(switchPin);
// 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:
1
2
3
4
5
6
7
8
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
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. For example, JavaScript sends data as ASCII strings almost by default, so it makes sense to use ASCII when writing in JavaScript. 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 and 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. For example, if you’re using P5.js, you may notice that using println() in the draw() loop will cause your sketch to slow down. 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.
Bonus Tip: writing Serial Data to a File
POSIX environments treat every input to the computer as a file stream, so when you’re using the cat command like you saw above, you’re telling the operating system to concatenate the serial input as if it’s a file. You can so some useful things as a result of this, like sending the serial output directly to a file.
Let’s say you want to save a few minutes of serial readings into a file. First, write a simple serial program that continually sends serial out, like you did earlier in this lab. Then, on the command line, type:
cat /dev/cu.usbmodem14131 > datalog.csv
You won’t see anything, unlike when you did it before, because now the cat program is redirecting to a file called datalog.csv, not to the command line. Type control-C to stop it, then open the file. You can do this from the Finder as you might usually, or you can just type
open datalog.csv
Since you made it a .csv file (for comma separated values), the operating system tries to open it with your spreadsheet program. This can be a quick way to get data into a structured format from your serial devices. For more on using the command line, see Karl Ward’s Introduction to Unix and the command line.
Further Work
The following labs will help you get better at serial communication:
In this lab you’ll learn how to send data from p5.js to a microcontroller using asynchronous serial communication.
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.serialport library for P5.js, it communicates with a webSocket server in the P5.js IDE to give you access to serial devices attached to your computer. This lab shows you how to use P5 to control a microcontroller using asynchronous serial communication.
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.
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.
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:
Figure 5. An Arduino Uno on the left connected to a solderless breadboard, right.
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.
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:
Figure 7. Schematic view of an Arduino connected to an LED.
Figure 8. Breadboard view of an Arduino connected to an LED.
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.
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
voidsetup() {
Serial.begin(9600); // initialize serial communications
}
voidloop() {
if(Serial.available() > 0) { // if there's serial data available
intinByte =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
}
}
The P5.js serialport library
To communicate with your microcontroller serially, you’re going to use the P5.js serialport library and the p5.serialcontrol app. The P5.js serialport library can’t access your serial ports directly when a sketch is running in a browser because the browser doesn’t have direct access to the serial port. But it can communicate with another program on your computer that can exchange data with the serialport. p5.serialcontrol is the app that connects your sketch, running in a browser, with the serial ports on your computer as shown in Figure 11.
Figure 11. Diagram of the connection from the serial port to p5.js through p5.serialcontrol
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. 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.
Install the P5.serialcontrol App
Download the latest version of the P5.serialcontrol application and save it in your Applications folder. When you run it, it will check serial ports on your machine. You don’t need to do anything with the app, just have it open. However, remember this most important fact:
Only one port at a time can access a serial port.
That means that when you want to reprogram your Arduino from the Arduino IDE, you need to quit p5.serialcontrol to do so. Then, reopen p5.serialcontrol 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 p5.serialcontrol.
You’ll need to know the name of your serial port to get started. If you’re not sure how to get this, see the Serial Input to P5.js lab for how to get a list of ports.
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 Serial Input to P5.js lab, so that you can see that the microcontroller is getting the same values you’re sending.
Program P5.js For Serial Communication
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. In the head of the document, look for this line:
The setup of your sketch will initialize the P5.serialport 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
varserial; // variable to hold an instance of the serialport library
varportName = '/dev/cu.usbmodem1421'; // fill in your serial port name here
varinData; // for incoming serial data
varoutByte = 0; // for outgoing data
functionsetup() {
createCanvas(400, 300); // make the canvas
serial = newp5.SerialPort(); // make a new instance of the serialport library
serial.on('data', serialEvent); // callback for when new data arrives
serial.on('error', serialError); // callback for errors
serial.on('list', printList); // set a callback function for the serialport list event
serial.list(); // list the serial ports
serial.open(portName); // open a serial port
}
You’re only using the ‘data’ and ‘error’ and ‘list’ callbacks this time, but you can add the other serial callbacks if you want them. You can also add a serialport select menu as you did in the Serial Input to P5.js lab if you wish.
Program the serialEvent() function and serialError() function similarly to those in the previous lab. They read incoming data (serialEvent()) and report any errors (serialError()), as follows:
1
2
3
4
5
6
7
8
9
10
functionserialEvent() {
// read a byte from the serial port:
varinByte = serial.read();
// store it in a global variable:
inData = inByte;
}
functionserialError(err) {
println('Something went wrong with the serial port. '+ err);
}
Program the draw() function to display the value of any incoming serial bytes. Here it is:
1
2
3
4
5
6
7
functiondraw() {
// black background, white text:
background(0);
fill(255);
// display the incoming serial data as a string:
text("incoming value: "+ inData, 30, 50);
}
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:
1
2
3
4
5
6
functionmouseDragged() {
// map the mouseY to a range from 0 to 255:
outByte = int(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:
1
2
3
4
5
6
functionkeyPressed() {
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
}
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.
Sending ASCII-Encoded Serial Data
If you want to send ASCII-encoded serial data from P5.js, all you have to do is to serial.write() your string. Sending strings is the P5.serialport’s default behavior. 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
constintledPin =5; // the pin that the LED is attached to
intincomingByte; // a variable to read incoming serial data into
voidsetup() {
Serial.begin(9600); // initialize serial communication
pinMode(ledPin, OUTPUT); // initialize the LED pin as an output
}
voidloop() {
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 change the keyPressed() function to read H or L instead of 0 through 9. Here’s your new mousePressed() function:
1
2
3
4
5
functionkeyPressed() {
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?
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
voidsetup() {
Serial.begin(9600); // initialize serial communications
Serial.setTimeout(10); // set the timeout for parseInt
}
voidloop() {
if(Serial.available() > 0) { // if there's serial data available
intinByte =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 With a Newline Character
Now that your microcontroller is expecting a string, program P5.js to send one. This means changing the mouseDragged() function. You still need to convert it to an integer using the int() function (you could also use round()), but then you need to convert it back to a String and add a delimiter. A quick way to do this is by adding the delimiter in the serial.write() command like so:
1
serial.write(outByte + '\n');
When the command encounters the two different elements, the number and the string (‘\n’), it will convert the number into a string in in order to concatenate the two. In addition, the newline on the end will is useful on the Arduino side. Since it’s a non-numeric character, the Serial.parseInt() function will see it and parse the string, not waiting for the timeout.
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.
In this tutorial you’ll learn how to send data using asynchronous serial between an Arduino and p5.js in both directions.
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 Serial 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. You’ll use the data from the sensors to create a pointing-and-selecting device (i.e. a mouse).
Figures 1-5 below are the parts you’ll need for this exercise. Click on any image for a larger view.
Figure 1. Microcontroller. Shown here is an Arduino Nano 33 IoT
Figure 2. Jumper wires. You can also use pre-cut solid-core jumper wires.
Figure 3. A solderless breadboard
Figure 4. A pushbutton
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:
Figure 6. A joystick, which consists of two potentiometers and a pushbutton
Figure 7. Rotary encoders, which include a built-in pushbutton
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.
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.
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.
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
constintbuttonPin =2; // digital input
voidsetup() {
// configure the serial connection:
Serial.begin(9600);
// configure the digital input:
pinMode(buttonPin, INPUT);
}
voidloop() {
// read the first analog sensor:
intsensorValue =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:
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:
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.
Receive the data in P5.js
Now write a P5.js sketch that reads the data as formatted by the Arduino program above. Download the latest version of the P5.serialcontrol application if you haven’t already and save it in your Applications folder. When you run it, it will check serial ports on your machine. You don’t need to do anything with the app, just have it open.
You’ll need to know the name of your serial port to get started. If you’re not sure how to get this, see the Serial Input to P5.js lab for how to get a list of ports.
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 Serial Input to P5.js lab, so that you can see that the microcontroller is getting the same values you’re sending.
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. In the head of the document, look for this line:
The setup of your sketch will initialize the P5.serialport library and define your callback functions for serial events. , as you did in other sketches
Then in the setup(), create a canvas, make an instance of the serialport library, and declare your callback functions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var serial; // variable to hold an instance of the serialport library
function setup() {
createCanvas(800, 600); // make canvas
smooth(); // antialias drawing lines
serial =new p5.SerialPort(); // make a new instance of the serialport library
serial.on('list', printList); // set a callback function for the serialport list event
serial.on('connected', serverConnected); // callback for connecting to the server
serial.on('open', portOpen); // callback for the port opening
serial.on('data', serialEvent); // callback for when new data arrives
serial.on('error', serialError); // callback for errors
serial.on('close', portClose); // callback for the port closing
var portSelector; // a select menu for the port list
Then change the printList function like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// get the list of ports:
function printList(portList) {
// make a select menu and position it:
portSelector =createSelect();
portSelector.position(10,10);
// portList is an array of serial port names
for(var i =0; i < portList.length; i++) {
// Display the list the console:
// console.log(i + " " + portList[i]);
// add item to the select menu:
portSelector.option(portList[i]);
}
// set a handler for when a port is selected from the menu:
portSelector.changed(mySelectEvent);
}
When the select menu’s value has changed, you can assume a serial port has been selected, so write a handler to open it like so:
1
2
3
4
5
6
7
8
9
function mySelectEvent() {
let item =portSelector.value();
// if there's a port open, close it:
if(serial.serialport !=null) {
serial.close();
}
// open the new port:
serial.open(item);
}
From now on, when you run this sketch, you’ll need to select the serial port to open the port.
The rest of the serial event handlers are all the same as you saw in the P5.js Serial Input Lab, except for the serialEvent(). Here are all but the serialEvent():
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
functionserverConnected() {
console.log('connected to server.');
}
functionportOpen() {
console.log('the serial port opened.')
}
functionserialError(err) {
console.log('Something went wrong with the serial port. '+ err);
}
functionportClose() {
console.log('The serial port closed.');
}
Program 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
functionserialEvent() {
// read a string from the serial port
// until you get carriage return and newline:
varinString = serial.readStringUntil('\r\n');
//check to see that there's actually a string there:
if(inString.length > 0 ) {
varsensors = split(inString, ','); // split the string on the commas
if(sensors.length > 2) { // if there are three elements
locH = map(sensors[0], 0, 1023, 0, width); // element 0 is the locH
locV = map(sensors[1], 0, 1023, 0, height); // element 1 is the locV
circleColor = 255 - (sensors[2] * 255); // element 2 is the button
}
}
}
Note the mappings of sensor[0] and sensor[1]. You should use the input mappings for your accelerometer 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
varlocH = 0;
varlocV = 0; // location of the circle
varcircleColor = 255; // color of the circle
Finally, here is the draw function:
1
2
3
4
5
functiondraw() {
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 tilt the accelerometer. 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
voidsetup() {
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
voidloop() {
if(Serial.available() > 0) {
// read the incoming byte:
intinByte =Serial.read();
// read the sensor:
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
functionserialEvent() {
// read a string from the serial port
// until you get carriage return and newline:
varinString = serial.readStringUntil('\r\n');
//check to see that there's actually a string there:
if(inString.length > 0) {
if(inString !== 'hello') { // if you get hello, ignore it
var sensors = split(inString, ','); // split the string on the commas
if (sensors.length > 2) { // if there are three elements
locH = map(sensors[0], 0, 1023, 0, width); // element 0 is the locH
locV = map(sensors[1], 0, 1023, 0, height); // element 1 is the locV
circleColor = 255 - (sensors[2] * 255); // element 2 is the button
}
}
serial.write('x'); // send a byte requesting more serial data
}
}
You also need to add a line to the openPort() function like so:
1
2
3
4
5
functionportOpen() {
console.log('the serial port opened.')
// send a byte to prompt the microcontroller to send:
serial.write('x');
}
The reason for this is that if your 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. 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.
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.
n 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.
Overview
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.
Serial communication to a web page in a browser isn’t something you see every day. Web browsers don’t usually have access to a computer’s serial ports. In order to get your browser-based applications to communicate with a microcontroller serially, you need a program that can both serve HTML/JavaScript pages, and communicate with the serial port. When you’re making projects with P5.js, you can achieve this by using the P5.serialport library and the P5.serialcontrol app by Shawn Van Every (updated by Jiwon Shin). When you use the p5.serialport library, it communicates with the p5.serialcontrol app, a WebSocket server that gives you access to serial devices attached to your computer. This lab shows you how to do that.
Figures 1-4 below show the parts you’ll need for this exercise. Click on any image for a larger view.
Figure 1. Microcontroller. Shown here is an Arduino Nano 33 IoT
Figure 2. Jumper wires. You can also use pre-cut solid-core jumper wires.
Figure 3. A solderless breadboard
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.
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.
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.
Figure 7. Schematic view of a potentiometer connected to analog in 0 of the Arduino
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.
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
voidsetup() {
Serial.begin(9600); // initialize serial communications
To communicate with your microcontroller serially, you’re going to use the P5.js serialport library and the p5.serialcontrol app. The P5.js serialport library can’t access your serial ports directly when a sketch is running in a browser because the browser doesn’t have direct access to the serial port. But it can communicate with another program on your computer that can exchange data with the serialport. p5.serialcontrol is the app that connects your sketch, running in a browser, with the serial ports on your computer as shown in Figure 10.
Figure 10. Diagram of the connection from the serial port to p5.js through p5.serialcontrol
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. 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.
Install the p5.Serialcontrol App
Download the latest version of the P5.serialcontrol application and save it in your Applications folder. When you run it, it will check serial ports on your machine. You don’t need to do anything with the app, just have it open. However, remember this most important fact:
Only one port at a time can access a serial port.
That means that when you want to reprogram your Arduino from the Arduino IDE, you need to quit p5.serialcontrol to do so. Then, reopen p5.serialcontrol 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 p5.serialcontrol.
Program P5.js to List the Available Serial Ports
Now you’re ready to 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. In the head of the document, look for this line:
To start off, your programming environment needs to know what serial ports are available in the operating system. Open the sketch.js file and change it to the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
letserial; // variable to hold an instance of the serialport library
functionsetup() {
serial = newp5.SerialPort(); // make a new instance of the serialport library
serial.on('list', printList); // set a callback function for the serialport list event
serial.list(); // list the serial ports
}
// get the list of ports:
functionprintList(portList) {
// portList is an array of serial port names
for(vari = 0; i < portList.length; i++) {
// Display the list the console:
console.log(i + portList[i]);
}
}
When you run this p5.js sketch in a browser, you’ll get a list of the available serial ports in the console. This list will look just like the list of serial ports you see in the Arduino Tools menu. Find the name of your port in the list. Later, you’ll assign that name to a global variable called portName.
Now you’re ready to listen for some incoming serial data.
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 serialport library uses events and callback functions as well. It can listen for the following serialport events:
list – the program asks for a list of ports.
connected – when the sketch connects to a webSocket-to-serial server
open – a serial port is opened
close – a serial port is closed
data – new data arrives in a serial port
error – something goes wrong.
You’re already using a callback for the ‘list’ event in the code above. You set a callback for the ‘list’ event, then you called it with serial.list(). Generally, you should set your callbacks before you use them like this.
To use the rest of the serialport library’s events, you need to set callback functions for them as well. Add a new global variable called portName and initialize it with the name of your serial port that you got from the listPorts() function before. Then change your setup() function to include callbacks for open, close, and error like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
letserial; // variable to hold an instance of the serialport library
letportName = '/dev/cu.usbmodem1421'; // fill in your serial port name here
functionsetup() {
serial = newp5.SerialPort(); // make a new instance of the serialport library
serial.on('list', printList); // set a callback function for the serialport list event
serial.on('connected', serverConnected); // callback for connecting to the server
serial.on('open', portOpen); // callback for the port opening
serial.on('data', serialEvent); // callback for when new data arrives
serial.on('error', serialError); // callback for errors
serial.on('close', portClose); // callback for the port closing
serial.list(); // list the serial ports
serial.open(portName); // open a serial port
}
Notice the final line of the setup(). It’s going to generate an ‘open’ event, which will be handled by a function called portOpen().
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.js, 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, do it like this:
1
2
letoptions = { baudrate: 9600}; // change the data rate to whatever you wish
serial.open(portName, options);
Now add new functions to respond to the callbacks you just declared. These come after your setup() function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
functionserverConnected() {
console.log('connected to server.');
}
functionportOpen() {
console.log('the serial port opened.')
}
functionserialEvent() {
}
functionserialError(err) {
console.log('Something went wrong with the serial port. '+ err);
}
functionportClose() {
console.log('The serial port closed.');
}
The function that matters the most, though, is serialEvent(), the one that responds to new data. 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:
1
2
3
letserial; // variable to hold an instance of the serialport library
letportName = '/dev/cu.usbmodem1421'; // fill in your serial port name here
letinData; // for incoming serial data
Then modify the serialEvent() function like so:
1
2
3
functionserialEvent() {
inData = Number(serial.read());
}
Next, make the draw() function to print the sensor value to the screen. Start by adding a createCanvas() call to the top of your setup() like so:
1
2
functionsetup() {
createCanvas(400, 300);
Then here’s your draw() function:
1
2
3
4
5
functiondraw() {
background(0);
fill(255);
text("sensor value: "+ inData, 30, 50);
}
Figure 13. 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 13.
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 in P5.js lab.
Adding A Serial Port Select Menu
If you don’t want to have to remember the serial port name every time you run the sketch, you can add a drop-down menu to select the port. Add a global variable at the top of your sketch called portSelector like so:
1
2
// HTML Select option object:
letportSelector;
Then replace the printList() function with the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
// make a serial port selector object:
functionprintList(portList) {
// create a select object:
portSelector = createSelect();
portSelector.position(10, 10);
// portList is an array of serial port names
for(vari = 0; i < portList.length; i++) {
// add this port name to the select object:
portSelector.option(portList[i]);
}
// set an event listener for when the port is changed:
portSelector.changed(mySelectEvent);
}
Then add an extra function that will get called when the port list is changed. This function will get the name of the port you select, close any port that’s open, and open the port you asked for:
1
2
3
4
5
6
7
8
9
functionmySelectEvent() {
letitem = portSelector.value();
// if there's a port open, close it:
if(serial.serialport != null) {
serial.close();
}
// open the new port:
serial.open(item);
}
If you choose this approach, you can delete the global portName variable at the top of your sketch, and the line in your setup() that says:
1
serial.open(portName); // open a serial port
Instead of opening the serial port once at the beginning of your code, you’re now opening and closing the port every time you select from this menu.
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
letxPos = 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
functionsetup() {
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
functiongraphData(newData) {
// map the range of the input to the window height:
varyPos = 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
functiondraw() {
graphData(inData);
}
When you run the sketch now, you should get a graph, as shown in Figure 14.
Figure 14. Screenshot of the serial graph p5.js sketch. The sensor’s values are graphed on the screen
If you’d like to see a fancier graphing sketch, check out this sketch, which adds chart.js to make a better graph. Chart.js is a great tool for graphing data in JavaScript, and it integrates well with p5.js.
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
voidsetup() {
Serial.begin(9600); // initialize serial communications
}
voidloop() {
intpotentiometer =analogRead(A0); // read the input pin
intmappedPot =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 15.
Figure 15. 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
functionserialEvent() {
// 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 now 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
functionserialEvent() {
// read a string from the serial port:
varinString = serial.readLine();
// check to see that there's actually a string there:
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’);
Optional: Accessing a Serial Sketch From Another Computer
You know that p5.js can run in any browser, but what happens to a sketch using p5.serialport.js when it’s running on someone else’s computer, or on your phone or tablet? What serial port does it connect to? That depends on what you do when you initialize it.
When you call new p5.SerialPort() with no parameter between the parentheses, the library attempts to connect to p5.serialcontrol app on the computer that’s running the sketch. If you’re running the sketch on your laptop’s browser, then the library connects to the your laptop’s ports through p5.serialcontrol. But imagine you run the sketch on your phone, but you want the sketch to connect to an Arduino connected to a serial port on your laptop. To do this, the your laptop has to be the web host for your sketch, as well as the computer running p5.serialcontrol. In addition, your laptop and the device running the sketch have to be on the same local network.
note: this will not work if your sketch is in the p5.js web editor. You’ll need to download the sketch and edit it on your laptop to make it work.
Launch the p5.serialcontrol app. It will display the IP address of the computer on which it’s running. Copy it, and modify the new p5.SerialPort() line at the beginning of your setup() function, adding the IP address like so:
1
serial = newp5.SerialPort('10.17.34.128'); // fill in your own IP address in place of the one shown here
Save the sketch, then open a command line interface on your computer (the Terminal app in MacOS, for example). Change directories to the directory where your sketch lives (for example, cd ~/Documents/p5_sketches/mySerialSketch) and run a simple web server like so:
$ python -m SimpleHTTPServer 8080
Now open a browser, either on your computer or your phone or tablet, and enter the following address:
http://your.ip.address:8080
To close this server, type control-C. You can modify the sketch as much as you want, and reload it in the browser without having to re-start the server.
The sketch should run, and operate just as you saw earlier. This approach is handy if you want to use a tablet or phone as a multimedia device to control sounds or videos, controlled by physical sensors on a microcontroller.
Note: the IP address of your computer will change as you move from one network to another (for example, from school to home). If you want to get the IP address dynamically, you can use this: window.location.hostname. This will always return the address of the host computer that served the webpage. So, for example, changing the line above to read as follows will automatically adjust the hostname each time.
1
2
// use the hostname of the computer that served this page:
serial = newp5.SerialPort(window.location.hostname);
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.
Data to Send
A single value
within 0-255
(< 2^8 = 1 byte)
Larger numbers & characters in Ascii Table,
Multiple values
Send as:
Binary
Ascii
Arduino ->
Serial.write()
Serial.println()
-> p5.js
serial.read()
serial.readLine()
=readStringUntil('\r\n')
Table 1. Serial Communication: Arduino to p5.js
Notes about sending Ascii data:
Using Serial.println() on Arduino and serial.readLine() on p5.js is one of many different ways of sending Ascii data from Arduino to p5.js with serial communication.
If you want to use the value as a numeric value 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 Serial Output from P5.js lab.
In this lab you’ll learn some methods for determining when a sensor’s reading changes significantly.
Introduction
Microcontrollers can sense what’s going on in the physical world using digital and analog sensors, but a single sensor reading doesn’t tell you much. In order to tell when something significant happens, you need to know when that reading changes. For example, when a digital input changes from LOW to HIGH or the reverse, you can tell that a person closed or opened a switch. When a force-sensing resistor reaches a peak reading, you know that something has hit the sensor. In this lab, you’ll learn how to program your microcontroller to look for three common changes in sensor readings that give you information about events in the physical world: state change detection on digital sensors, and threshold crossing and peak detection on analog sensors. You’ll use these three techniques all the time when you’re designing to read users’ actions.
What You’ll Need to Know
To get the most out of this lab, you should be familiar with the following concepts. You can check how to do so in the links below:
Arduino Nano 33 IoTFlexible jumper wires. These wires are quick for breadboard prototyping, but can get messy when you have lots of them on a board.A solderless breadboard with two rows of holes along each side. The . board is turned sideways so that the side rows are on top and bottom in this view. There are no components mounted on the board. PushbuttonsForce Sensing Resistor (FSR)10-kilohm resistors. These ones are 5-band resistorsFigures 1-6. The parts you’ll need for this exercise. Click on any image for a larger view.
Understanding How Your Sensor Changes
Before you start trying to detect specific sensor change events, you should know what your sensor’s changes look like over time. You might want to start by viewing the change on an oscilloscope, or by using the Serial Plotter in the Arduino IDE Tools menu (command-shift-L), or a graphing program like the one shown in the WebSerial input to p5.js Lab or Serial Output From Arduino to Processing lab to understand how your sensors change. Figure 7 shows a typical sensor change graph.
Figure 7. Graphing a sensor in Processing
Sensor changes are described in terms of the change in the sensor’s property, often a voltage output, over time. The most important cases to consider for sensor change are the rising and falling edges of a digital or binary sensor, and the rising and falling edges and the peak of an analog sensor. The graphs in Figures 8 and 9 of sensor voltage over time illustrate these conditions:
Figure 8. Digital sensors change from high voltage to low and vice versa. The change from low voltage to high is called the rising edge, and the change from high voltage to low is called the falling edge
Figure 9. The three general states of an analog sensor are when it’s rising (current state > previous state), when it’s falling (current state < previous state), and when it’s at a peak.
Prepare the breadboard
Connect power and ground on the breadboard to power and ground from the microcontroller. On the Arduino module, use the 5V or 3.3V (depending on your model) and any of the ground connections, as shown in Figures 10 and 11.
Figure 10. Breadboard view of an Arduino Uno on the left connected to a solderless breadboard, right.
Figure 10 shows 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 11. Breadboard view of Arduino Nano mounted on a breadboard.
Figure 11 shows an Arduino Nano mounted on a solderless breadboard. 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.
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.
Connect a pushbutton to digital input 2 on the Arduino. Figures 12 and 13 show the schematic and breadboard views of this for an Arduino Uno, and Figure 14 shows the breadboard view for an Arduino 33 IoT.
Figure 12. Schematic view of an Arduino connected to a pushbutton.
Figure 13. Breadboard view of an Arduino connected to a pushbutton.
Figure 14. Breadboard view of an Arduino Nano connected to a pushbutton
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. The pushbutton is mounted across the middle divide of the solderless breadboard. A 10-kilohm resistor connects from the same row as pushbutton’s bottom left pin to the ground bus on the breadboard. There is a wire connecting to digital pin 2 from the same row that connects the resistor and the pushbutton. The top left pin of the pushbutton is connected to +3.3V.
Program the Microcontroller to Read the Pushbutton’s State Change
In the Digital Lab you learned how to read a pushbutton using the digitalRead() command. To tell when a pushbutton is pushed, you need to determine when the button’s state changes from off to on. With the button wired as you have it here, the button’s state will change from 0 to 1. In order to know that, you need to know not only what the current state of the button is, but you also need to remember the state of the button the previous time you read it. This is called state change detection. To do this, set up a global variable to store the button’s previous state. Initialize the button in your program’s setup() function using the pinMode() command. Then, in the loop() function, write a block of code that reads the button and compares its state to the previous state variable. To do this, you need to read the button, check the current button state against the last state, then save the current state of the button in a variable for the next time through the loop like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
intlastButtonState =LOW; // state of the button last time you checked
voidsetup() {
// make pin 2 an input:
pinMode(2, INPUT);
}
voidloop() {
// read the pushbutton:
intbuttonState =digitalRead(2);
// check if the current button state is different than the last state:
if(buttonState !=lastButtonState) {
// do stuff if it is different here
}
// save button state for next comparison:
lastButtonState =buttonState;
}
If buttonState is not equal to lastButtonState, then the button has changed. Then you want to check if the current state is HIGH. If it is, then you know the button has changed from LOW to HIGH. That means your user pressed it. Print out a message to that effect.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
intlastButtonState =LOW; // state of the button last time you checked
voidsetup() {
// initialize serial communication:
Serial.begin(9600);
// make pin 2 an input:
pinMode(2, INPUT);
}
voidloop() {
// read the pushbutton:
intbuttonState =digitalRead(2);
// if it's changed and it's high, toggle the mouse state:
if(buttonState !=lastButtonState) {
if(buttonState ==HIGH) {
Serial.println("Button was just pressed.");
}
}
// save button state for next comparison:
lastButtonState =buttonState;
}
Your code should only print out a message when the button changes state. For every button press, you should get one line of code. You can use this technique any time you need to tell when a digital input changes state.
Count Button Presses
One of the many things you can do with state change detection is to count the number of button presses. Each time the button changes from off to on, you know it’s been pressed once. By adding another global variable and incrementing it when you detect the button press, you can count the number of button presses. Add a global variable at the top of your program like so:
1
2
intlastButtonState =LOW; // state of the button last time you checked
intbuttonPresses =0; // count of button presses
Then in the if statement that detects the button press, add one to the button press:
1
2
3
4
5
6
if(buttonState ==HIGH) {
buttonPresses++;
Serial.print("Button has been pressed ");
Serial.print(buttonPresses);
Serial.println(" times.");
}
The key to detecting state change is the use of a variable to save the current state for comparison the next time through the loop. This is a pattern you’ll see below as well:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
intlastSensorState =LOW; // sensor's previous state
// other globals and the setup go here
voidloop() {
// read the sensor:
intsensorState =digitalRead(2);
// if it's changed:
if(sensorState !=lastSensorState) {
// take action or run a more detailed check
}
// save sensor state for next comparison:
lastSensorState =sensorState;
}
Long Press, Short Press
Sometimes you want to take a different action on a short button press than you do on a long button press. To do this, you need to know now only when the button changes, but also how long it stays in a pressed state after it changes. Here’s how you might do that.
Start with some global variables for the button pin number, and the length of a long press or a short press, in milliseconds. You also need a variable to track how long the button has been pressed, and as in the code above, you need a variable to track the last button state. Add another variable called pressTime, which will keep track of the last time the button went from LOW to HIGH:
1
2
3
4
5
6
7
8
9
10
11
// the input pin:
intbuttonPin =2;
// the length of the presses in ms:
intlongPress =750;
intshortPress =250;
// variable for how long the user actually presses:
longpressTime =0;
// previous state of the button:
intlastButtonState =LOW;
In the setup(), set the button pin mode and initialize serial as you did before:
1
2
3
4
5
voidsetup() {
// initialize serial and I/O pin:
Serial.begin(9600);
pinMode(buttonPin, INPUT);
}
In the loop, look for the button to change state, and when it does, note the press time in the pressTime variable. When the button is released (goes from HIGH to LOW), calculate how ling it was pressed, and print it:
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
voidloop() {
// read the button:
intbuttonState =digitalRead(buttonPin);
// if the button has changed:
if(buttonState !=lastButtonState) {
// if the button is pressed, start a timer:
if(buttonState ==HIGH) {
pressTime =millis();
}
// if it's released, stop the timer:
if(buttonState ==LOW) {
longholdTime =millis() -pressTime;
// take action for long press, short press, or tap:
if(holdTime > longPress) {
Serial.println("long press");
} elseif(holdTime > shortPress) {
Serial.println("short press");
} else{
Serial.println("Tap");
}
}
}
// save button state for next time:
lastButtonState =buttonState;
}
You can see from this that you’ve actually got three states now, long press (> 750ms), short press (250-750ms), and tap (>250ms). With this, you can make one button do three things.
Analog Sensor Threshold Detection
When you’re using analog sensors, binary state change detection like you saw above is not usually effective, because your sensors can have multiple states. Remember, an analog sensor on an Arduino can have up to 1024 possible states. The simplest form of analog state change detection is to look for the sensor to rise above a given threshold in order to take action. However, if you want the action be triggered only once when your sensor passes the threshold, you need to keep track of both its current state and previous state.
Change the Breadboard
To build this example, you’ll need an analog sensor attached to your microcontroller, as shown in the Analog Input lab. Figures 15-17 show how to connect it.
Figure 15. Schematic of Arduino connected to an FSR on pin 2
Figure 16. Breadboard view of Arduino connected to an FSR on pin 2. The FSR is connected to two rows in the left center section of the breadboard. One of its pins is wired to voltage. The other is connected to ground through a 10-kilohm resistor. The row connecting the two resistors is wired to analog input 0.
Figure 17. Breadboard view of Arduino Nano connected to an FSR on pin 2. The FSR is connected to two rows in the left center section of the breadboard, below the Nano. One of its pins is wired to voltage. The other is connected to ground through a 10-kilohm resistor. The row connecting the two resistors is wired to analog input 0.
Program the Microcontroller to Read a Sensor Threshold Crossing
This example is very similar to the one above:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
intlastSensorState =LOW; // sensor's previous state
intthreshold =512; // an arbitrary threshold value
voidsetup() {
Serial.begin(9600);
}
voidloop() {
// read the sensor:
intsensorState =analogRead(A0);
// if it's above the threshold:
if(sensorState >=threshold) {
// check that the previous value was below the threshold:
if(lastSensorState < threshold) {
// the sensor just crossed the threshold
Serial.println("Sensor crossed the threshold");
}
}
// save button state for next comparison:
lastSensorState =sensorState;
}
This program will give you an alert only when the sensor value crosses the threshold when it’s rising. You won’t get any reading when it crosses the threshold when it’s falling, and you’ll only get one message when it crosses the threshold. It is possible to sense a threshold crossing when the sensor is falling, by reversing the greater than and less than signs in the example above. The threshold you set depends on your application. For example, if you’re using a light sensor to detect when it’s dark enough to turn on artificial lighting, you’d use the example above, and turn on the light when the threshold crossing happens. But you might also need to check for the falling threshold crossing to turn off the light.
Detecting a Peak
There are times when you need to know when an analog sensor reaches its highest value in a given time period. This is called a peak. To detect a peak, you first set an initial peak value at zero. Pick a threshold below which you don’t care about peak values. Any time the sensor value rises above the peak value, you set the peak value equal to the sensor value. When the sensor value starts to fall, the peak will remain with the highest value:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
intpeakValue =0;
intthreshold =50; //set your own value based on your sensors
voidsetup() {
Serial.begin(9600);
}
voidloop() {
//read sensor on pin A0:
intsensorValue =analogRead(A0);
// check if it's higher than the current peak:
if(sensorValue > peakValue) {
peakValue =sensorValue;
}
}
You only really know you have a peak when you’ve passed it, however. When the current sensor value is less than the last reading you saved as the peak value, you know that last value was a peak. When the sensor value falls past below threshold after you have a peak, but your peak value is above the threshold, then you know you’ve got a significant peak value. after you use that peak value, you need to reset the variable to 0 to detect other peaks :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
intpeakValue =0;
intthreshold =50; //set your own value based on your sensors
voidsetup() {
Serial.begin(9600);
}
voidloop() {
//read sensor on pin A0:
intsensorValue =analogRead(A0);
// check if it's higher than the current peak:
if(sensorValue > peakValue) {
peakValue =sensorValue;
}
if(sensorValue <=threshold) {
if(peakValue > threshold) {
// you have a peak value:
Serial.println(peakValue);
// reset the peak variable:
peakValue =0;
}
}
}
Dealing with Noise
Quite often, you get noise from sensor readings that can interfere with peak readings. Instead of a simple curve, you get a jagged rising edge filled with many local peaks, as shown in Figure 18:
Figure 18. Graph of local peaks
You can smooth out the noise and ignore some of these local peaks by adding in a noise variable and checking to see if the sensor’s change is different than the previous reading and the noise combined, 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
intpeakValue =0;
intthreshold =50; //set your own value based on your sensors
intnoise =5; //set a noise value based on your particular sensor
voidsetup() {
Serial.begin(9600);
}
voidloop() {
//read sensor on pin A0:
intsensorValue =analogRead(A0);
// check if it's higher than the current peak:
if(sensorValue > peakValue) {
peakValue =sensorValue;
}
if(sensorValue <=threshold -noise ) {
if(peakValue > threshold +noise) {
// you have a peak value:
Serial.println(peakValue);
// reset the peak value:
peakValue =0;
}
}
}
Most sensor change cases can be described using a combination of state change detection, threshold crossing, and peak detection. When you start to write sensor change detection routines, make sure you understand these three basic techniques, and make sure you have a good idea what your sensor’s readings look like over time. With that combination, you should be able to detect most simple sensor change events.
In this lab, you’ll send asynchronous serial data from your personal computer to an Arduino microcontroller in order to control a digital output of the microcontroller. Once you’ve done that, you’ll also learn how to interpret ASCII-encoded numeric strings on the Arduino.
Introduction
In this lab, you’ll send asynchronous serial data from your personal computer to an Arduino microcontroller in order to control a digital output of the microcontroller. Once you’ve done that, you’ll also learn how to interpret ASCII-encoded numeric strings on the Arduino.
Figure 1-3 are basically what you need for this lab.
Figure 1: Arduino Nano 33 IoT
Figure 2: 22AWG hookup wire
Figure 3: 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.
Prepare the breadboard
Connect power and ground on the breadboard to power and ground from the microcontroller. On the Arduino module, use the 5V and any of the ground connections(Figure 4):
Figure 4: An Arduino Uno on the left connected to a solderless breadboard, right.
Figure 5. Breadboard view of Arduino Nano on a breadboard.
As shown in Figure5, 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.
Connect an LED and resistor to pin 11 of the Arduino through a 220-ohm resistor. If you prefer an audio output, you can use a speaker instead. Appropriate code changes will be mentioned below (Figure6-7):
Figure 6: Schematic view of an Arduino connected to an LED.
Figure 7: Breadboard view of an Arduino connected to an LED.
Figure 8. Breadboard view of an LED connected to digital pin 5 of an Arduino Nano.
Figure 8: 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.
Program the Microcontroller to Read Serial Input
Related Video: Serial.available() To program the Arduino to read serial input, you use the Serial.available() command. The .available() command returns the number of bytes that are available in the Arduino’s serial buffer that you haven’t read yet. When there are bytes available, you can read them using Serial.read().
In the setup() function of your program, initialize serial communications using Serial.begin(). Set the LED’s pin to be an output using pinMode() as well. Then in the setup, check how many bytes are available in the serial buffer using Serial.available() like so:
1
2
3
4
5
6
7
8
9
10
voidsetup() {
Serial.begin(9600); // initialize serial communications
pinMode(11, OUTPUT); // set digital pin 11 to be an output, to control the LED
}
voidloop() {
if(Serial.available() > 0) {
}
}
Interpret the Incoming Serial Bytes
Related Video: reading the bytes in Arduino Inside the if statement that checks Serial.available(), you’ll interpret the bytes as they come in. First, read the incoming bytes using Serial.read(). The serial buffer is a First-in, First-out buffer, or a FIFO buffer, meaning that the first byte that the computer sends is the first byte that the Arduino can read:
Here’s how to read the incoming bytes and interpret them:
1
2
3
4
5
6
7
8
9
10
11
voidloop() {
if(Serial.available() > 0) {
byteinput =Serial.read(); // read first available byte into a variable
if(input =='H') { // if the variable equals H, or ASCII 72
digitalWrite(11, HIGH); // turn on the LED
}
if(input =='L') { // if the variable equals L, or ASCII 76
digitalWrite(11, LOW); // turn off the LED
}
}
}
This sketch now reads the first available byte into the variable input, then evaluates the variable. If input is equal to 72, which is the ASCII letter H, it turns on the LED. If input equals 76, or ASCII L, it turns the LED off.
Note: What Do the Single Quotes Mean?
In the C programming language (and by extension, in Arduino, since Arduino based on C), you can put a single ASCII character in single quotes and the compiler will interpret it as its numeric value. This can be handy when you know you want to compare a byte to an ASCII character, but can’t remember the numeric value of the ASCII character.
Once you’ve uploaded this to the board, open the serial monitor. If you’re using the Arduino Serial Monitor to read and write serial data, make sure the line ending tab is set to “no line ending” like so(Figure 9):
Figure 9: Screenshot of the Serial Monitor line ending option
Type H or L in the text input bar at the top, then hit enter. You should see the LED turn on when you send H, and turn off when you send L. You’ll notice that if you send lower case h or l, nothing happens. That’s because you didn’t check for those values. In ASCII, uppercase letters and lowercase letters each get different values. Uppercase H is 72, for example, but lowercase h is 104.
The serial monitor isn’t the only program that can send bytes to your microcontroller. Any program that can communicate over asynchronous serial communication can be used to send data. So if you’re using Processing, or Max/MSP, or node.js, you can control this simple Arduino program serially.
Change the Brightness of the LED Bytes Serially
The microcontroller reads all incoming bytes as values from 0 to 255. In the example above, you saw how to interpret those values as ASCII characters. But you can use the byte values any way you wish. Change the loop of your program as shown below:
1
2
3
4
5
6
7
8
voidloop() {
// put your main code here, to run repeatedly:
if(Serial.available() > 0) {
byteinput =Serial.read();
// use the value of the incoming byte to control the LED's brightness:
analogWrite(11, input);
}
}
Upload this new sketch and open the serial monitor. When you send characters now, what’s happening? The LED’s brightness might be jumping around, seemingly randomly. Lower case letters toward the end of the alphabet will make the LED slightly brighter, and uppercase ones toward the beginning will make it dimmer. The lower the value, the lower the brightness of the LED. a space, which is ASCII 32, will make the LED very dim, while a tilde (~), which is ASCII value 126, will make it brighter.
But what if you want to send an ASCII-encoded numeric string? Why doesn’t the LED turn on to full brightness when you type “255”? Even though you interpret the characters as one number, the Arduino interprets them as three bytes, with the values 50 (“2” = ASCII 50), 53 (“5” = ASCII 53), and 53. How do you get the Arduino to convert these strings as numbers?
You can use the Serial.parseInt() function to interpret ASCII numeric strings. This function will read all incoming bytes looking for a numeric character, and when it finds one, it will keep looking until it finds the next non-numeric character. Then it will interpret all the numeric characters it found as one number. Change your sketch’s loop as follows:
1
2
3
4
5
6
7
8
voidloop() {
// put your main code here, to run repeatedly:
if(Serial.available() > 0) {
intinput =Serial.parseInt();
// use the value of the incoming byte to control the LED's brightness:
analogWrite(11, input);
}
}
Then send in a numeric string, like 255 or 10. You should see the LED get much brighter with 255, and much dimmer with 10. If you send 0, the LED should turn off. Instead of interpreting your data byte-by-byte, .parseInt() is looking for strings of numbers and interpreting them. You can even give it multiple strings separated by non-numeric characters. Try the following strings:
10,127,255 0 255 0 12-250-3
You can separate your numbers however you wish. You could even look for multiple different numbers with multiple variables, like this:
1
2
3
4
5
6
7
8
voidloop() {
// put your main code here, to run repeatedly:
if(Serial.available() > 0) {
intred =Serial.parseInt();
intgreen =Serial.parseInt();
intblue =Serial.parseInt();
}
}
With the code above, if you sent three comma-separated values, you’d be able to set the three variables red, green, and blue independently.
Serial.setTimeout()
You may notice that .parseInt() is slow to respond. It has a timeout that defaults to one second, waiting for incoming data. You can speed it up by using Serial.setTimeout() to set the timeout in milliseconds. In your setup, right after Serial.begin(), try a Serial.setTimeout(10) to set the timeout to 10 milliseconds. This is generally good for most programs that might be sending ASCII strings to the microcontroller.
Serial Control from Node.js
If you’re familiar with node.js and the node-serialport library, perhaps because you’ve already tried the Serial to node.js lab, upload the following Arduino sketch:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
voidsetup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.setTimeout(10);
pinMode(11, OUTPUT);
}
voidloop() {
// put your main code here, to run repeatedly:
if(Serial.available() > 0) {
charinput =Serial.parseInt();
// use the value of the incoming byte to control the LED's brightness:
analogWrite(11, input);
}
}
Now try the following node.js script (you’ll need to install node-serialport using npm as you did in the Serial to node.js lab). Save this as serialOutput.js:
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
// serial port initialization:
varSerialPort = require('serialport'); // include the serialport library
varportName = process.argv[2]; // get the port name from the command line
varmyPort = newSerialPort(portName, 9600);// open the port
// these are the definitions for the serial events:
myPort.on('open', openPort); // called when the serial port opens
functionopenPort() {
varbrightness = 0; // the brightness to send for the LED
// since you only send data when the port is open, this function
// is local to the openPort() function:
functionsendData() {
// convert the value to an ASCII string before sending it:
myPort.write(brightness.toString());
console.log('Sending '+ brightness + ' out the serial port');
// increment brightness by 10 points. Rollover if < 255:
if(brightness < 255) {
brightness+= 10;
} else{
brightness = 0;
}
}
// set an interval to update the brightness 2 times per second:
setInterval(sendData, 500);
}
Make sure the serial monitor in Arduino is closed, then run this by typing the following on the command line:
$ node serialOutput.js portname
Replace portname with the name of your serialport. When this runs, you should see the LED getting ten percent brighter every half a second, then go out when it reaches the brightest.
In this lab, you’ll see synchronous serial communication in action using the Inter-integrated Circuit (I2C) protocol. You’ll communicate with an infrared temperature sensor chip from a microcontroller in order to read the temperature of an object in front of the sensor.
Introduction
In this lab, you’ll see synchronous serial communication in action using the Inter-integrated Circuit (I2C) protocol. You’ll communicate with an infrared temperature sensor chip from a microcontroller in order to read the temperature of an object in front of the sensor.
Figure 1-3 are the parts that you need for this lab.
Figure 1. 22AWG solid core hookup wires.
Figure 2. Arduino Nano 33 IoT
Figure 3. A TMP007 Temperature sensor module.
Figure 4. A short solderless breadboard.
Connect the temperature sensor
The temperature sensor used in this lab, a Texas InstrumentsTMP007, is an integrated circuit (IC) that can read the temperature of an object placed in front of it. Connect the sensor’s power and ground connections and the connections for clock and serial data as shown in Figure 5-7. For the Arduino UNO board and Nano boards, the I2C pins are fixed A4(SDA) and A5(SCL):
Figure 4. Schematic view of an Arduino attached to a TMP007 temperature sensor.
Figure 5. Schematic view of an Arduino attached to a TMP007 temperature sensor.
Figure 6. An Arduino Nano attached to a TMP007 temperature sensor. The TMP007 temperature sensor has 7 pins, and when the sensor is positioned with the pins on the left hand side of the board the pins are labeled VCC, Ground, SDA, SCL, Alert, AD1, and AD0. The sensor’s VCC and ground pins (pins 1 and 2) are connected to the Arduino’s 3.3V (pin 2) and GND (pin 14) pins, respectively. The sensor’s SDA pin (pin 3) is connected to the Arduino’s A4 input (pin 8) and the sensor’s SCL pin (pin 4) is connected to the Arduino’s A5 input (pin 9).
The circuit is now complete, and you’re ready to write a program to control it. One of the advantages of the I2C synchronous serial protocol (as opposed to the SPI protocol) is that you only ever need two wires for communication to one or multiple devices.
How the Temperature Sensor Works
I2C devices exchange bits of data whenever the shared clock signal changes. Controller and peripheral devices both send bits of data when the clock changes from low to high (called the rising edge of the clock). Unlike with SPI, they cannot send data at the same time.
The TMP007 has a series of memory registers that control its function. You can write to or read from these registers using I2C communication from your microcontroller. Some of these registers are writable by the controller so that you can configure the sensor. For example, you can set its I2C address, set the sensitivity of the sensor, and so forth. Some registers are configuration registers, and by writing to them, you configure the chip. For example, you can set lower and upper limits of temperature sensitivity. Other memory registers are read-only. For example, when the sensor has read the temperature of an object, it will store the result in a register that you can read from the controller. The details of the chip’s registers can be found in the TMP007 datasheet, in the “Register Maps” section, page 26.
I2C devices exchange data in 7-bit chunks, using an eighth bit to signal if you’re reading or writing by the controller or for acknowledgement of data received. To get the temperature from the TMP007, your controller device sends the sensor’s address (a 7-bit number) followed by a single bit indicating whether you want to read data or write data (1 for read, 0 for write). Then you send the memory register that you want to read from or write to. For example, as shown in Figure 7, the object temperature is stored in memory register 01 of the TMP007. To get the temperature, you send:
Figure 7. I2C data
To use I2C communication on an Arduino microcontroller, you use the Wire library, which is built into the Arduino IDE. You can find Arduino-compatible libraries for many devices that use the Wire library, but never expose it directly in their APIs. Adafruit’s TMP007 library is typical of this style of library. The library’s readObjTempC() command sends a write command to start a temperature reading of the object in front of the sensor, then sends a read command to read the appropriate temperature register, then combines the results using a formula explained in the datasheet on page 25, then returns the result to you as degrees celsius. Similarly, the readDieTempC() sends a write command to read the chip temperature, then a read command to read the appropriate temperature register, then does the math and gives you the result.
Install the External Libraries
The TMP007 library relies on the Adafruit Sensor library in addition to the Wire library, so you’ll need both in order to make this work. You can use the library manager to find these libraries or download the TMP007 library here and the Sensor library here. Make sure you’re using Arduino version 1.5.5 or later.
Once you’ve downloaded the libraries, change the name of the resulting .zip file to remove the words -master or _Library-master from the end of the file name. Keep the .zip extension though. Open the Arduino IDE (version 1.6.8 or later) and choose the Sketch menu, then choose Import Library… and finally click the Add Library… option. A dialog box will pop up asking you to find the library you want to add. Navigate to the .zip file for the Sensor library and choose it. The library will be added and you’ll see the words “Library added to your libraries. Check the ‘Import Library’ menu”.
Program the Microcontroller
At the beginning of your code, include the appropriate libraries. In the setup(), initialize the sensor with begin(). If the sensor responds, then begin() will return true, and if not, it will return false. This is how to check that the sensor is properly wired to your microcontroller:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include"Wire.h"
#include"Adafruit_TMP007.h"
Adafruit_TMP007 tmp007; // instance of the sensor library
voidsetup() {
Serial.begin(9600);
booleansensorInitialized =tmp007.begin(); // initialize the sensor
while(!sensorInitialized) {
// Do nothing until sensor responds
Serial.println("Sensor is not responding");
}
}
The TMP007 can only read every four seconds. In the main loop, set up an if statement to check when the millis() passes another four seconds using the modulo operator:
1
2
3
4
voidloop() {
if(millis() %4000< 2) { // if 4 seconds have passed
}
}
Inside that if statement, read the object temperature and the chip temperature and print them both out:
1
2
3
4
5
6
7
8
9
10
11
12
13
voidloop() {
if(millis() %4000< 2) { // if 4 seconds have passed
floatobjectTemp =tmp007.readObjTempC(); // read object temperature
floatchipTemp =tmp007.readDieTempC(); // read chip temperature
// print the results:
Serial.print("Chip temperature: ");
Serial.print(chipTemp);
Serial.print(" deg. C. \t Object temperature: ");
Serial.print(objectTemp);
Serial.println(" deg. C");
}
}
As you can see, you’re never actually calling commands from the Wire library directly, but the commands in the TMP007 library are relying on the Wire library. This is a common way to use the Wire library to handle I2C communication.
Conclusion
I2C is a common protocol among many ICs, and it’s handy because you can combine many devices on the same bus. You need to make sure the device addresses are unique. Each device will have its own way to change the address. For the TMP007, see Table 2 in the data sheet; you have to set the address pins (AD1 and AD0 on the breakout board appropriately to change the address.
In this lab, you’ll see synchronous serial communication in action using the Serial Peripheral Interface (SPI) protocol. You’ll communicate with a digital potentiometer chip from a microcontroller.
Introduction
In this lab, you’ll see synchronous serial communication in action using the Serial Peripheral Interface (SPI) protocol. You’ll communicate with a digital potentiometer chip from a microcontroller. You’ll use the digital pot to control the loudness of a speaker playing a tone from the microcontroller.
From Figure 1-5 are the parts that you need for this lab.
Figure 1. 22AWG solid core hookup
Figure 2. Arduino Nano 33 IoT
Figure 3. Digital Potentiometer
Figure 4. An 8 ohm speaker
Figure 5. 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.
Controlling the Loudness of a Speaker
If you did the tone lab on this site, you know that it’s not possible to vary the loudness of a tone generated from a microcontroller. In order to change the loudness, you’d need to change the voltage of the tone pin. If you put a potentiometer in series with the speaker as shown below, you can modify the tone’s loudness, as is shown in Figure 6.
Figure 6. Electrical diagram of speaker. The speaker’s negative pin is connected to ground and the positive pin is connected to a 10k potentiometer
This circuit requires that you modify the loudness manually, by turning the pot. But with a digital potentiometer, you can modify the loudness from your program.
Connect the digital potentiometer
The digital potentiometer used in this lab, an Analog Devices AD5206, is an integrated circuit (IC) that can perform one specific function: it has six potentiometers that you can control, as is shown in Figure 7. Each of its pins has a specific function, as shown below. It’s in a Dual Inline Package, or DIP. DIP package ICs typically have their pins enumerated in a U-shape, starting with pin 1 on the top left, and the highest number pin on the top right.
Figure 7. AD5206 Digital Potentiometer. The pins on the left side of the chip are pins for potentiometer 6, followed by pins for power and SPI connections, followed by pins for potentiometer 5. The potentiometer pins are labeled A, W, and B. The power and SPI connection pins are labeled Ground, CS, Vdd, SDI, CLK, and Vss. The pins on the right side of the chip are for potentiometers 4, 2, 1, and 3. Each of the potentiometer pins are labeled A, W, and B.
The potentiometers in this chip are labeled A1, B1, W1 through A6, B6, W6. The A and B pins are the fixed end pins of the potentiometer, and if you measure resistance across them with a multimeter, you’ll measure 10 kilohms. The W pins are the wipers, and the resistance is programmable via the SPI connection. You can use any of these potentiometers in a circuit just like you would a regular potentiometer.
First, connect the digital potentiometer’s power and ground connections, and the connections for clock, chip select, and serial data in, as shown in Figure 8-10:
Figure 8. Schematic of an Arduino attached to a AD5206 Potentiometer. The Arduino’s ground is attached the the potentiometer’s A5, Vss, and Ground pins, numbered 12, 9, and 4, respectively. The Arduino’s D10, D11, and D13 pins are attached to the potentiometer’s CS, SDI, and CLK pins, which are numbered 5, 7, and 8, respectively. The potentiometer’s Vdd pin, number 6, is connected to 5 volts. If using the Arduino Nano the potentiometer’s Vdd pin, number 6, should connect to 3.3 volts.
Figure 9. Schematic of an Arduino attached to a AD5206 Potentiometer. The Arduino’s ground is attached the the potentiometer’s A5, Vss, and Ground pins, numbered 12, 9, and 4, respectively. The Arduino’s D10, D11, and D13 pins are attached to the potentiometer’s CS, SDI, and CLK pins, which are numbered 5, 7, and 8, respectively. The potentiometer’s Vdd pin, number 6, is connected to 5 volts.
Figure 10. Schematic of an Arduino attached to a AD5206 Potentiometer.
Figure 10. Schematic of an Arduino attached to a AD5206 Potentiometer. The Arduino’s ground is attached the the potentiometer’s A5, Vss, and Ground pins, numbered 12, 9, and 4, respectively. The Arduino’s D10, D11, and D13 pins are attached to the potentiometer’s CS, SDI, and CLK pins, which are numbered 5, 7, and 8, respectively. The potentiometer’s Vdd pin, number 6, is connected to 3.3 volts.
Next, add a speaker to the wiper of the fifth channel of the digital pot. Include a 100-ohm resistor in series with the speaker. Then connect the A5 pin to digital pin 9 of the Arduino, which you’ll use to generate a tone. You can use any channel of the digital pot if you want, but the code below uses the fifth channel.
Figure 11. Schematic of an Arduino attached to a AD5206 Potentiometer and a speaker. The Arduino’s ground is attached the the potentiometer’s A5, Vss, and Ground pins, numbered 12, 9, and 4, respectively. The Arduino’s D10, D11, and D13 pins are attached to the potentiometer’s CS, SDI, and CLK pins, which are numbered 5, 7, and 8, respectively. The potentiometer’s Vdd pin, number 6, is connected to 5 volts. If using the Arduino Nano, the potentiometer’s Vdd pin, number 6, should connect to 3.3 volts. The Arduino’s D9 pin is connected to the negative terminal of a speaker. The speaker’s positive terminal is connected to a 100 Ohm resistor, which is connected to the potentiometer’s W5 pin, number 11.
Figure 12. Schematic of an Arduino attached to a AD5206 Potentiometer and a speaker. The Arduino’s ground is attached the the potentiometer’s A5, Vss, and Ground pins, numbered 12, 9, and 4, respectively. The Arduino’s D10, D11, and D13 pins are attached to the potentiometer’s CS, SDI, and CLK pins, which are numbered 5, 7, and 8, respectively. The potentiometer’s Vdd pin, number 6, is connected to 5 volts. The Arduino’s D9 pin is connected to the negative terminal of a speaker. The speaker’s positive terminal is connected to a 100 Ohm resistor, which is connected to the potentiometer’s W5 pin, number 11.
Figure 13. Figure Schematic of an Arduino attached to a AD5206 Potentiometer and a speaker.
Figure 13. Schematic of an Arduino attached to a AD5206 Potentiometer and a speaker. The Arduino’s ground is attached the the potentiometer’s A5, Vss, and Ground pins, numbered 12, 9, and 4, respectively. The Arduino’s D10, D11, and D13 pins are attached to the potentiometer’s CS, SDI, and CLK pins, which are numbered 5, 7, and 8, respectively. The potentiometer’s Vdd pin, number 6, is connected to 3.3 volts. The Arduino’s D9 pin is connected to the negative terminal of a speaker. The speaker’s positive terminal is connected to a 100 Ohm resistor, which is connected to the potentiometer’s W5 pin, number 11.
Program the Microcontroller
The AD5206 has a simple command protocol, detailed in the “Operation” section of the data sheet. You send two bytes: the channel number you wish to control, and the level for the channel. Setting a channel to 0 makes the resistance between the wiper and the B pin 0 ohms, and setting it to 255 makes the resistance between the wiper and B 10 kilohms. There’s one slightly confusing issue: the channels are addressed as numbers 0 through 5 in code, yet numbered 1 through 6 on the pin diagram. Just remember that the first channel is channel 0, the second channel is channel 1, and so forth (just like array elements in most programming languages).
You can find Arduino-compatible libraries for many SPI devices that use the SPI library, but never expose it directly in the API. Instead, these libraries will include device-specific commands that use the SPI library to transfer data. Because the AD5206’s protocol is so simple, however, you don’t need a device-specific library, you can just use the SPI library. It’s a good illustration of what’s going on inside of some of the more complex SPI libraries.
At the beginning of your code, include the SPI library and set up a pin number for the chip select pin. The other SPI pins are set by the microcontroller you’re using (see the Arduino SPI reference page for the pin numbers). Then in the setup function, call SPI.begin() to initialize communications:
1
2
3
4
5
6
7
8
9
10
// include the SPI library:
#include"SPI.h"
constintCSPin =10; // chip select pin number
voidsetup() {
// initialize SPI:
SPI.begin();
// set the mode of CSPin
pinMode(CSPin, OUTPUT);
}
In your main loop, first make a tone on pin 9. Then make two for() loops to fade the loudness up and down. The actual work of controlling the digital potentiometer will be handled by a function you’ll write called digitalPotWrite():
Finally, write the digitalPotWrite() function to control the digital potentiometer via SPI. Because SPI data can go both directions at the same time, i.e. from controller to peripheral and from peripheral to controller, there is a single command, SPI.transfer(), to transfer data instead of the read() and write() commands you’re used to from asynchronous serial communication. In order to put the digital pot in listening mode, you take its chip select pin low, then when you’re finished communicating with it, you take the pin high again:
1
2
3
4
5
6
7
8
9
voiddigitalPotWrite(intaddress, intvalue) {
// take the SS pin low to select the chip:
digitalWrite(CSPin, LOW);
// send in the address and value via SPI:
SPI.transfer(address);
SPI.transfer(value);
// take the SS pin high to de-select the chip:
digitalWrite(CSPin, HIGH);
}
Once you upload this code, you’re done! You should hear the tone (middle A, 440Hz) fading in and out. You may have noticed that the for() loops fade from 100 to 255. The digital pot is changing the resistance across the wiper on the fifth potentiometer (aka channel 4) from approximately 3921 ohms (100/255 * 10k) to 10 kilohms. These are the levels that were determined from experiment to be the edges of audibility. But if your hearing is better, you may try adjusting the lower limit to see if you can hear it at a lower level.
Conclusion
This is a very simple use of SPI. Data only goes from controller peripheral in this example, and only two bytes are transferred. However, it gives you an indication of how the process works. Each SPI-based device will have its own command protocol, and data will be transferred from controller to peripheral (and vice versa) using the SPI transfer command. To open communications with a given SPI device, you take its chip select pin low, and to close communications, you take the chip select pin low again. This same procedure will work on all SPI devices once you know the command protocol. Keep in mind that most device-specific libraries will handle the SPI communication for you without you having to see it, just like the digitalPotWrite() command does in this example.
In this lab you’ll connect a microcontroller to a web browser using the node.js programming environment, HTML, and JavaScript.
Introduction
You can write programs that handle serial communication in many different languages. This page introduces how to do it using node.js. Node is a JavaScript environment that allows user to write web server programs. Below, you’ll use it to connect a microcontroller to a web browser using the node.js programming environment, HTML, and JavaScript.
The current version of this tutorial works with version 6.x.x of the node-serialport library.
This node.js introductory video will help in understanding this lab. The code in the video is different than this lab, but the basic concepts are similar. This lab simplifies the process a bit.
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.
To get started, download the node.js installer and install it on your computer. Then open your command line terminal. On OSX, open the Terminal app, which can be found in the Applications/Utilities directory. On Windows, go to the start menu and type cmd then press enter to open a window to the command line.
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 $ or %.
When you’ve installed node.js, type this command at the command prompt to get the version of node that you’re running:
$ node -v
If you installed it correctly, you’ll get a version number like 12.18.0. The node installer should also install the node package manager (npm). You can check that in the same way:
$ npm -v
Once node and npm are in place, you’re ready to create a new project.
There’s a library for node.js that allows you to communicate over your computer’s serial ports called serialport. If your computer’s connected to the internet, you can download install it automatically using npm. Create a new directory for your project:
$ mkdir nodeSerialExample
Then change directories to that directory:
$ cd nodeSerialExample
Now make a new text file in that directory with the name index.js.
This will be your main program file. Add the following text to the file:
1
console.log("Hello, and welcome to node.");
Save the file, then run it by typing the following on the command line:
$ node index.js
Your program should print out:
Hello, and welcome to node.
The program will finish and return to the command line when it’s done. Seeing that script running is indication that node.js is fully working on your machine.
You can also pass information into your node program using the process arguments on the command line. Change your program like so:
1
2
varname = process.argv[2];
console.log("Hello, and welcome to node,"+ name);
Run this as you did before, but add your name after the name of your program when you invoke it, like so:
$ node index.js Tom
You’ll get the following:
Hello, and welcome to node, Tom
The command line arguments are passed to your program as an array. The name was the third word you typed, or array element 2 (counting “node” as element 0 and “index.js” as element 1). This is a useful technique, and you’ll see it later to pass the program your serial port’s name.
The Node Serialport Library
You’ll also need the node serialport library, which you can install from the npm registry like so:
$ npm install serialport
This command will make a new subdirectory called node_modules, and in that directory it will install all the necessary assets for the serialport library. You’ll see a lot of text go by, and hopefully no errors. If you get errors, consult npmjs.org and the github wiki for serialport. Now you’re ready to use the serialport library.
The first thing you’ll want is a list of the serial ports. Replace the text of your program file with the following:
If you’re new to JavaScript, this syntax may be confusing. Node.js examples tend to use anonymous functions frequently. JavaScript can pass functions as variables (and vice versa). This is also using the JavaScript ES6 arrow function notation. That’s what’s going on here.
Stoyan Stefanov’s JavaScript Patterns is useful for understanding the various patterns of JavaScript coding.
When you run this script, you’ll get a list of your serial ports like so:
If you’ve got an Arduino plugged in via USB, you should see the name of your board’s port there as well. In the example above, which was run on OSX, the Arduino’s port is /dev/cu.usbmodem1411.
The process of using the serialport library will be the same every time:
initialize the serialport library
open the serial port
set up the callback functions and let them do the rest
Which are all explained below.
Opening the Serial Port
To open a serial port in node, you include the library at the beginning of your script, and make a local instance of the library in a variable. Make a new script or replace index.js with the following:
1
2
3
letserialport = require('serialport');// include the library
// get port name from the command line:
letportName = process.argv[2];
Then you open the port using new() like so:
1
letmyPort = newSerialPort(portName, 9600);
Note the serial parameters, which are passed to the new() function after the port name, as a list. The only one used here is the baud rate, set to 9600 bits per second.
If you want to read serial data as ASCII-encoded text, line by line, you also need to create a parser to tell the serial library how to interpret data when it comes in. It should read all the incoming data as a line of text, and generate a new data event when it sees a newline (“\n”). The parser is doing the same thing as Processing’s Serial.bufferUntil() function does. You do it like so:
1
2
3
letReadline = SerialPort.parsers.Readline; // make instance of Readline parser
letparser = newReadline(); // make a new parser to read ASCII lines
myPort.pipe(parser); // pipe the serial stream to the parser
You can find the full program so far at this link.
The Program Won’t Stop!
When you run this program now, it won’t automatically stop and return to the command line. To stop it, you’ll need to type control-C in the terminal window to stop it. The new instance of Serialport created a software object that listens for events from the serial port. Any node.js script that creates an event listener like this will run until you explicitly stop it. Both the serialport library and the http library, which you’ll use below, generate event listeners and will need to be explicitly stopped using control-C.
Serialport Library Events
The serialport library, like most node.js libraries, is event-based. This means that when the program is running, the operating system and the user’s actions will generate events and the program will provide functions to deal with those events called callback functions.
The main events that the serial library will deal with are when a serial port opens, when it closes, when new data arrives, and when there’s an error. The data event in particular performs the same function as Processing’s serialEvent() function. Once you’ve made an instance of the serialport library using the new() function as shown above, you define what functions will get called when each event occurs by using serialport.on() like so:
1
2
3
4
myPort.on('open', showPortOpen);
parser.on('data', readSerialData);
myPort.on('close', showPortClose);
myPort.on('error', showError);
The functions that are called by the event are the callback functions. In the example above, when the serial port is opened, the showPortOpen function will get called. When new data arrives, the sendSerialData function will get called, and so forth. If the event generates any parameters (for example a new data event will have the data as a parameter), those parameters will get passed to the callback function.
In the example above, you’re listening for the open, close, and error events using functions from the serial port object (e.g. myPort.on('open', showPortOpen);), but you;’re listening for the data event using a function from the parser object (parser.on('data',readSerialData);). You can listen with the serial port object too (e.g.myPort.on('data',readSerialData);), but the port object listener function generates a data event once every byte, while the parser object lets you generate a data event once every newline instead.
Write the callback functions for these events like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
functionshowPortOpen() {
console.log('port open. Data rate: '+ myPort.baudRate);
}
functionreadSerialData(data) {
console.log(data);
}
functionshowPortClose() {
console.log('port closed.');
}
functionshowError(error) {
console.log('Serial port error: '+ error);
}
Now you’ve got enough of a program to see some results. Upload a simple serial output sketch to your Arduino such as the AnalogReadSerial example or the sketch shown in the Analog Input Lab, you’ll be able to see its output from this script. Save the script. Then invoke it as follows, replacing portname with the name of your serial port: $ node index.js portname
For example, on OSX, if you haven an Arduino attached to the serial port called /dev/cu.usbmodem1411, then you’d type:
$ node index.js /dev/cu.usbmodem1411
When the port opens, you’ll see the message from the showPortOpen() function, then the output from the Arduino. Here’s the output from the node script:
port open. Data rate: 9600
266
276
261
To send serial output from node.js to the Arduino, use the serialport write() function like so:
myPort.write("Hello");
That’s all it takes to read and write serial data from node.js to a microcontroller. Node.js is designed for writing web server applications, however, so in the following steps you’ll see how to connect a serial port to your web browser using more of node.js.
Connecting from the Browser to the Node Program
In order to connect your node.js program to a web page, your program needs to listen for messages from the web browser, and the web pages need to connect to the program. To do this, you’ll use a connection called a webSocket. WebSockets are connections between web clients and servers that function a bit like serial ports. Both serial connections and webSocket connections are data streams, in which the first byte sent into the stream on one end is the first byte read out on the other end. Data streams are common programming structures and you’ll see them used in lots of places. They connect programs to files on your computer, or client programs to server programs, or desktop programs to serial or network ports. The diagram below(Figure 1) shows how the browser connects to your node.js program and how the node.js program connects to the serial port.
Figure 1. Diagram of the node.js serial workflow. The webpage on the left communicates with a node.js script running on a computer, shown in a box in the middle of the diagram. The node.js script communicates with an Arduino, shown on the right of the diagram, through a serial port.
There’s a node.js library your script will need to listen for webSocket connections that you should install using the node package manager like so:
$ npm install ws
Once it’s successfully installed, include it with your previous script by adding the following at the beginning of the script, right after you included the serialport library:
1
letWebSocketServer = require('ws').Server;
Following that, you need to use new() to make a new instance of the webSocket servver, and then configure a few parameters, and finally start the server:
1
2
3
const SERVER_PORT = 8081; // port number for the webSocket server
letwss = newWebSocketServer({port: SERVER_PORT}); // the webSocket server
letconnections = newArray; // list of connections to the server
The server will operate on port 8081, so when you write a client-side JavaScript program, you’ll connect to that port number. Your browser will be a client of the node.js script, and the script will be running as a server. Just as there are serialport event listener functions, there will be webSocket event listener functions too. You’ll need to listen for a webSocket connection event, and once connected, you’ll need to listen for incoming messages, and for the webSocket to close.
There can be multiple webSocket clients at any one time, so the server maintains an array to keep track of all the clients. That array is called connections, and every time a new client connects, the client is added to the array using the .push() function. When a client closes, it’s removed from the array using the .slice() function.
Here are the webSocket event listeners:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
wss.on('connection', handleConnection);
functionhandleConnection(client) {
console.log("New Connection"); // you have a new client
connections.push(client); // add this client to the connections array
client.on('message', sendToSerial); // when a client sends a message,
client.on('close', function() { // when a client closes its connection
console.log("connection closed"); // print it out
letposition = connections.indexOf(client); // get the client's position in the array
connections.splice(position, 1); // and delete it from the array
});
}
You’ll also need to modify the serialport data event listener to send data to the webSocket, and vice versa. Here’s a function to send webSocket data to the serial port. Put this after the serial event listeners above:
1
2
3
4
functionsendToSerial(data) {
console.log("sending to serial: "+ data);
myPort.write(data);
}
To parallel that, here’s a function to send serial data to the webSocket clients. Put this after the webSocket event listeners:
1
2
3
4
5
6
// This function broadcasts messages to all webSocket clients
functionbroadcast(data) {
for(myConnection inconnections) { // iterate over the array of connections
connections[myConnection].send(data); // send the data to each connection
}
}
Finally, you need to add the highlighted lines below to the readSerialData() function. This will send the latest data to all available webSocket clients:
1
2
3
4
5
6
7
8
functionreadSerialData(data) {
console.log(data);
// if there are webSocket connections, send the serial data
// to all of them:
if(connections.length > 0) {
broadcast(data);
}
}
Now you’ve got a complete script for connecting serial data to a webSocket server, and serving that to a client through a browser. Next you need a web page with its own embedded JavaScript to connect to his script.
Using the Data in HTML
The real value in connecting the serial port to a server is to generate dynamic HTML from the sensor data. You can do this by making an HTML page that includes some JavaScript to request data from the server, and serving that HTML page from a directory called public in your project directory. First, create the directory and change directory into it: $ mkdir public $ cd publicThen create a new document, index.html, in this directory. Don’t enter any elements, just the bare skeleton of a page:
1
2
3
4
5
6
7
8
9
10
<!DOCTYPEhtml>
<html>
<head>
<metacharset='utf-8'>
<title>Hello</title>
</head>
<body>
</body>
</html>
Including P5.js
If you’re used to Processing, then P5.js is a really good way to get started with JavaScript in the browser. It gives you the same structure as Processing, but in JavaScript. To use it, you’ll need to include P5.js using script tags in the head of your HTML.
First, you need to include p5.js in the document head. You can either download P5.js and its libraries directly, or you can include them from p5.js’s content delivery site, as shown in the HTML below.
Create a file called sketch.js in the same directory as your HTML file. This is where you’ll write your JavaScript, using the p5.js library.
p5.js uses setup() and draw() methods, just like Processing, and similar to Arduino. You’re going to use it to create an HTML text div element in the document, and when you receive serial data, you’ll use it to set the text and the position of the text element. Start with the setup() and draw() and global variables for the text element and a webSocket connection like so (from here on out, the rest of the HTML will be omitted for brevity. Everything you see below will be done in the sketch.js file. Here’s the final HTML:
Start the sketch.js file by making webSocket that will listen on port 8081. Then add the p5.js setup() and draw() functions:
1
2
3
4
5
6
7
8
lettext; // variable for the text div you'll create
letsocket = newWebSocket("ws://localhost:8081");
functionsetup() {
}
functiondraw() {
}
In the setup() function, add listeners for the webSocket, and create the text div and position it. You’ll write the listener functions a bit later:
1
2
3
4
5
6
7
8
9
10
11
12
functionsetup() {
// The socket connection needs two event listeners:
socket.onopen = openSocket;
socket.onmessage = showData;
// make a new div and position it at 10, 10:
text = createDiv("Sensor reading:");
text.position(10,10);
}
functiondraw() {
}
Next, write the openSocket() listener and showData functions which are the callback functions for the webSocket’s event listeners:
1
2
3
4
5
6
7
8
9
10
11
12
13
functionopenSocket() {
text.html("Socket open");
socket.send("Hello server");
}
functionshowData(result) {
// result is a JSON string. Parse it:
letinput = JSON.parse(result.data);
// when the server returns, show the result in the div:
text.html("Sensor reading:"+ input);
xPos = int(input); // convert result to an integer
text.position(xPos, 10); // position the text
}
This last function changes the text inside the div. It also moves the div’s horizontal position. Whenever new data arrives from the server, this function will be called automatically, so there’s no need for a draw() function. Save this file in the public directory, then restart the server and open the file in your browser. You should see the text moving across the screen left to right, depending on the sensor, as in the video below. When the sensor value is high, its text representation will be to the right in the browser. When it’s low, it will be to the right in the browser:
Once you’ve got a server program serving data from a serial device to a browser, you have potential to make all kinds dynamic interfaces that combine HTML and physical interfaces. Notice that the server program doesn’t actually parse the serial data; it just treats it as a string, and passes that string on to the client. The client does any parsing work; in this case, converting the numeric string to an integer. This means you can keep the server very simple, so you only need to make sure the two endpoints (the microcontroller and the web client) are speaking the same protocol. JavaScript has many functions for manipulating strings, particularly comma-separated values. So consider sending your data from Arduino as comma-separated values.
Note: Check your data types
When p5.js returns the result of a request, it returns the string as an array with one element. If you’re planning on manipulating that string with functions like parseInt(), split() and other string handling functions, make sure to get the string out of the array first. For example, if you’ve sent over the string:
1
"234, 124, 134"
and you want to split it, here’s how you’d do it:
1
2
3
4
5
6
7
8
9
functionshowData(result) {
varresultString = JSON.parse(result.data);
text.html("Sensor reading:"+ resultString);
// split it:
varnumbers = split(resultString, ",");
// use the numbers:
text.position(int(numbers[0]), int(numbers[1]));
text.style("font-size", int(numbers[2]) + "%");
}
Adding Handshaking (aka Call-and-Response)
Because the wsServer.js script passes through messages through without parsing, you can add handshaking to this application by modifying only the Arduino program and the P5.js script. When you add handshaking the Arduino will only send new data when it receives a byte of data in the serial port. It allows you to control the flow of data better.
To implement handshaking, make the following change in the Arduino sketch. Wrap the contents of the loop() in the Arduino sketch in an if statement like so:
1
2
3
4
5
6
7
8
9
10
voidloop() {
if(Serial.available()) {
charinput =Serial.read();
// read the input on analog pin 0:
intsensorValue =analogRead(A0);
// print out the value you read:
Serial.println(sensorValue);
delay(1); // delay in between reads for stability
}
}
Then add the following line to the end of the showData() function in your p5.js sketch:
1
2
3
4
5
6
7
8
9
functionshowData(result) {
// result is a JSON string. Parse it:
letinput = JSON.parse(result.data);
// when the server returns, show the result in the div:
text.html("Sensor reading:"+ input);
xPos = int(input); // convert result to an integer
text.position(xPos, 10); // position the text
socket.send('a'); // send a byte to get the Arduino to send new data
}
You won’t need to change the wsServer.js script at all. Just restart it after you upload to the Arduino, and reload the page in the browser. When the client connects to the server, it will send the “Hello” message, which will be sent from the server to the Arduino, and that will trigger the Arduino to start sending data.