{"id":3588,"date":"2015-08-30T14:18:46","date_gmt":"2015-08-30T18:18:46","guid":{"rendered":"https:\/\/itp.nyu.edu\/physcomp\/?page_id=3588"},"modified":"2022-11-06T18:11:08","modified_gmt":"2022-11-06T23:11:08","slug":"lab-serial-control-of-an-arduino","status":"publish","type":"page","link":"https:\/\/itp.nyu.edu\/physcomp\/labs\/labs-serial-communication\/lab-serial-control-of-an-arduino\/","title":{"rendered":"Lab: Serial Input to an Arduino from Node.js"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Introduction\"><\/span>Introduction<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In this lab, you&#8217;ll&nbsp;send asynchronous serial data from your personal computer to an Arduino microcontroller in order to control a digital output of the microcontroller. Once you&#8217;ve done that, you&#8217;ll also learn how to interpret ASCII-encoded numeric strings on the Arduino.<\/p>\n\n\n\n<p>These videos will help to understand this lab:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Video: <a rel=\"noopener\" href=\"https:\/\/vimeo.com\/380355568\">Introduction to Serial Communication<\/a><\/li><li>Video:&nbsp;<a rel=\"noopener\" href=\"https:\/\/vimeo.com\/380355716\">Serial Under the Hood: Interpreting Serial Data<\/a><\/li><li>Video: <a rel=\"noopener\" href=\"https:\/\/vimeo.com\/380356227\">Reading Serial Input in Arduino<\/a><\/li><\/ul>\n\n\n\n<p>The current version of this lab works with version 6.x.x of the node-serialport library.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"What_Youll_Need_to_Know\"><\/span>What You\u2019ll Need to Know<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>To get the most out of this Lab, you should be familiar with the basics of programming an Arduino microcontroller. If you\u2019re not, review the <a rel=\"noopener\" href=\"https:\/\/itp.nyu.edu\/physcomp\/labs\/digital-input-and-output-with-an-arduino\/\">Digital Input and Output Lab<\/a>, the <a href=\"https:\/\/itp.nyu.edu\/physcomp\/labs\/labs-serial-communication\/serial-output-from-an-arduino\/\">Serial Output from an Arduino Lab<\/a>, and perhaps the <a rel=\"noopener\" href=\"http:\/\/arduino.cc\/en\/Guide\/HomePage\">Getting Started with Arduino guide<\/a>.<\/p>\n\n\n\n<p>The video <a href=\"https:\/\/vimeo.com\/380356227\">Video: Serial 3 &#8211; DIY Protocol<\/a>&nbsp;covers the same material as this lab.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Things_Youll_Need\"><\/span>Things You\u2019ll Need<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Figure 1-3 are basically what you need for this lab.<\/p>\n\n\n\n<div class=\"wp-block-image size-thumbnail wp-image-5921\"><figure class=\"alignleft\"><img loading=\"lazy\" decoding=\"async\" width=\"150\" height=\"150\" src=\"https:\/\/itp.nyu.edu\/physcomp\/wp-content\/uploads\/pcomp-kit-f2019-arduino-nano-33-iot-150x150.jpg\" alt=\"Photo of an Arduino Nano 33 IoT module. The USB connector is at the top of the image, and the physical pins are numbered in a U-shape from top left to bottom left, then from bottom right to top right.\" class=\"wp-image-5921\"\/><figcaption>Figure 1: Arduino Nano 33 IoT<\/figcaption><\/figure><\/div>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"alignleft\"><a href=\"https:\/\/itp.nyu.edu\/physcomp\/wp-content\/uploads\/hookup_wire1.jpg\"><img loading=\"lazy\" decoding=\"async\" width=\"150\" height=\"150\" src=\"https:\/\/itp.nyu.edu\/physcomp\/wp-content\/uploads\/hookup_wire1-150x150.jpg\" alt=\"Three short pieces of hookup wire: one is clad in red insulation, one in blue, and one in black. All three have exposed ends approximately 5mm long.\" class=\"wp-image-968\"\/><\/a><figcaption>Figure 2: 22AWG hookup wire<\/figcaption><\/figure><\/div>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"alignleft\"><a href=\"https:\/\/itp.nyu.edu\/physcomp\/wp-content\/uploads\/leds1.jpg\"><img loading=\"lazy\" decoding=\"async\" width=\"150\" height=\"150\" src=\"https:\/\/itp.nyu.edu\/physcomp\/wp-content\/uploads\/leds1-150x150.jpg\" alt=\"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.\" class=\"wp-image-787\"\/><\/a><figcaption>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.<\/figcaption><\/figure><\/div>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Prepare_the_breadboard\"><\/span>Prepare the breadboard<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>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):<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><a href=\"https:\/\/itp.nyu.edu\/physcomp\/wp-content\/uploads\/LabTemplate_bb.png\"><img loading=\"lazy\" decoding=\"async\" width=\"300\" height=\"195\" src=\"https:\/\/itp.nyu.edu\/physcomp\/wp-content\/uploads\/LabTemplate_bb-300x195.png\" alt=\"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.\" class=\"wp-image-2159\" srcset=\"https:\/\/itp.nyu.edu\/physcomp\/wp-content\/uploads\/LabTemplate_bb-300x195.png 300w, https:\/\/itp.nyu.edu\/physcomp\/wp-content\/uploads\/LabTemplate_bb.png 559w\" sizes=\"(max-width: 300px) 85vw, 300px\" \/><\/a><figcaption>Figure 4: An Arduino Uno on the left connected to a solderless breadboard, right.<\/figcaption><\/figure><\/div>\n\n\n\n<div class=\"wp-block-image wp-image-5903\"><figure class=\"aligncenter is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/itp.nyu.edu\/physcomp\/wp-content\/uploads\/LabTemplateNanoShort_bb.png\" alt=\"Arduino Nano on a breadboard.\" class=\"wp-image-5903\" width=\"228\" height=\"359\"\/><figcaption>Figure 5. Breadboard view of Arduino Nano on a breadboard.<\/figcaption><\/figure><\/div>\n\n\n\n<p>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.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Add_the_LED\"><\/span>Add the LED<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p><a rel=\"noopener\" href=\"https:\/\/vimeo.com\/380356227#t=0m0s\">Related Video: DIY Serial protocol<\/a><\/p>\n\n\n\n<p>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):<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><a href=\"https:\/\/itp.nyu.edu\/physcomp\/wp-content\/uploads\/LabSerialIn_schem.png\"><img loading=\"lazy\" decoding=\"async\" width=\"237\" height=\"300\" src=\"https:\/\/itp.nyu.edu\/physcomp\/wp-content\/uploads\/LabSerialIn_schem-237x300.png\" alt=\"Schematic view of an Arduino connected to an LED. Digital pin 5 is connected to a 22-ohm resistor. The other side of the resistor is connected to the anode (long leg) of an LED. The cathode of the LED is connected to ground.\" class=\"wp-image-3592\" srcset=\"https:\/\/itp.nyu.edu\/physcomp\/wp-content\/uploads\/LabSerialIn_schem-237x300.png 237w, https:\/\/itp.nyu.edu\/physcomp\/wp-content\/uploads\/LabSerialIn_schem.png 479w\" sizes=\"(max-width: 237px) 85vw, 237px\" \/><\/a><figcaption>Figure 6: Schematic view of an Arduino connected to an LED.<\/figcaption><\/figure><\/div>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><a href=\"https:\/\/itp.nyu.edu\/physcomp\/wp-content\/uploads\/LabSerialIn_bb.png\"><img loading=\"lazy\" decoding=\"async\" width=\"300\" height=\"204\" src=\"https:\/\/itp.nyu.edu\/physcomp\/wp-content\/uploads\/LabSerialIn_bb-300x204.png\" alt=\"Breadboard view of an Arduino connected to an LED. The +5 volts and ground pins of the Arduino are connected by red and black wires, respectively, to the left side rows of the breadboard. +5 volts is connected to the left outer side row (the voltage bus) and ground is connected to the left inner side row (the ground bus). The side rows on the left are connected to the side rows on the right using red and black wires, respectively, creating a voltage bus and a ground bus on both sides of the board. A blue wire connects Digital to a 22-ohm resistor that straddles the center divide of the breadboard in row 17. The other side of the resistor is connected to the anode (long leg) of an LED. The LED is mounted in rowsd 16 and 17 of the right side of the center section of the board. a black wire connects the cathode's row, row 16, to the ground bus on the right side of the board.\" class=\"wp-image-3591\" srcset=\"https:\/\/itp.nyu.edu\/physcomp\/wp-content\/uploads\/LabSerialIn_bb-300x204.png 300w, https:\/\/itp.nyu.edu\/physcomp\/wp-content\/uploads\/LabSerialIn_bb.png 645w\" sizes=\"(max-width: 300px) 85vw, 300px\" \/><\/a><figcaption>Figure 7: Breadboard view of an Arduino connected to an LED.<\/figcaption><\/figure><\/div>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<div class=\"wp-block-image wp-image-6033\"><figure class=\"aligncenter is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/itp.nyu.edu\/physcomp\/wp-content\/uploads\/LabDigitalOutNano_bb.png\" alt=\"Breadboard view of an LED connected to digital pin 5 of an Arduino Nano.\" class=\"wp-image-6033\" width=\"243\" height=\"358\"\/><figcaption>Figure 8. Breadboard view of an LED connected to digital pin 5 of an Arduino Nano.<\/figcaption><\/figure><\/div>\n\n\n\n<p>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&#8217;s voltage pin (physical pin 2) connects to the board&#8217;s voltage bus, and the Nano&#8217;s ground pin (physical pin 14) connects to the board&#8217;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&#8217;s anode to a wire connecting to digital pin 5. The LED&#8217;s cathode is connected to the ground bus.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Program_the_Microcontroller_to_Read_Serial_Input\"><\/span>Program the Microcontroller to Read Serial Input<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p><a rel=\"noopener\" href=\"https:\/\/vimeo.com\/380356227#t=1m23s\">Related Video: Serial.available()<\/a><br>To program the Arduino to read serial input, you use the <code>Serial.available()<\/code> command. The <code>.available()<\/code> command returns the number of bytes that are available in the Arduino&#8217;s serial buffer that you haven&#8217;t read yet. When there are bytes available, you can read them using <code>Serial.read()<\/code>.<\/p>\n\n\n\n<p>In the <code>setup()<\/code> function of your program, initialize serial communications using <code>Serial.begin()<\/code>. Set the LED&#8217;s pin to be an output using <code>pinMode()<\/code> as well. Then in the setup, check how many bytes are available in the serial buffer using <code>Serial.available()<\/code> like so:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: arduino; title: ; notranslate\" title=\"\">\nvoid setup() {\n  Serial.begin(9600);   \/\/ initialize serial communications\n  pinMode(11, OUTPUT);  \/\/ set digital pin 11 to be an output, to control the LED\n}\n\nvoid loop() {\n  if (Serial.available() &gt; 0) {\n\n  }\n}\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Interpret_the_Incoming_Serial_Bytes\"><\/span>Interpret the Incoming Serial Bytes<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p><a rel=\"noopener\" href=\"https:\/\/vimeo.com\/380356227#t=2m10s\">Related Video: reading the bytes in Arduino<\/a><br>Inside the if statement that checks <code>Serial.available()<\/code>, you&#8217;ll interpret the bytes as they come in. First, read the incoming bytes using <code>Serial.read()<\/code>. The serial buffer is a <strong>First-in, First-out buffer<\/strong>, or a <strong>FIFO buffer<\/strong>, meaning that the first byte that the computer sends is the first byte that the Arduino can read:<\/p>\n\n\n\n<p>Here&#8217;s how to read the incoming bytes and interpret them:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: arduino; title: ; notranslate\" title=\"\">\nvoid loop() {\n  if (Serial.available() &gt; 0) {\n    byte input = Serial.read();  \/\/ read first available byte into a variable\n    if (input == &#039;H&#039;) {          \/\/ if the variable equals H, or ASCII 72\n      digitalWrite(11, HIGH);     \/\/ turn on the LED\n    }\n    if (input == &#039;L&#039;) {          \/\/ if the variable equals L, or ASCII 76\n      digitalWrite(11, LOW);      \/\/ turn off the LED\n    }\n  }\n}\n<\/pre><\/div>\n\n\n<p>This sketch now reads the first available byte &nbsp;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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Note_What_Do_the_Single_Quotes_Mean\"><\/span>Note: What Do the Single Quotes Mean?<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>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&nbsp;a byte to an ASCII character, but can&#8217;t remember the numeric value of the ASCII character.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Send_Bytes_to_the_Microcontroller\"><\/span>Send Bytes to the Microcontroller<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p><a rel=\"noopener\" href=\"https:\/\/vimeo.com\/380356227#t=3m34s\">Related Video: uploading the sketch to the Arduino<\/a><\/p>\n\n\n\n<p>Once you&#8217;ve uploaded this to the board, open the serial monitor. If you&#8217;re using the Arduino Serial Monitor to read and write serial data, make sure the line ending tab is set to &#8220;no line ending&#8221; like so(Figure 9):<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><a href=\"https:\/\/itp.nyu.edu\/physcomp\/wp-content\/uploads\/line-ending-tab.png\"><img loading=\"lazy\" decoding=\"async\" width=\"342\" height=\"122\" src=\"https:\/\/itp.nyu.edu\/physcomp\/wp-content\/uploads\/line-ending-tab.png\" alt=\"Screenshot of the Arduino IDE Serial Monitor line ending option. The &quot;no line ending&quot; option is chosen.\" class=\"wp-image-3597\" srcset=\"https:\/\/itp.nyu.edu\/physcomp\/wp-content\/uploads\/line-ending-tab.png 342w, https:\/\/itp.nyu.edu\/physcomp\/wp-content\/uploads\/line-ending-tab-300x107.png 300w\" sizes=\"(max-width: 342px) 85vw, 342px\" \/><\/a><figcaption>Figure 9: Screenshot of the Serial Monitor line ending option<\/figcaption><\/figure><\/div>\n\n\n\n<p>If you prefer to <a href=\"https:\/\/itp.nyu.edu\/physcomp\/lab-intro-to-serial-communications\/#Connecting_via_the_Command_Line\">use a command line interface for serial communication<\/a>, you can do that using the screen command.<\/p>\n\n\n\n<p>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&#8217;ll notice that if you send lower case h or l, nothing happens. That&#8217;s because you didn&#8217;t check for those values.&nbsp;In ASCII, uppercase letters and lowercase letters each get different values. Uppercase H is 72, for example, but lowercase h is 104.<\/p>\n\n\n\n<p>The serial monitor isn&#8217;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&#8217;re using Processing, or Max\/MSP, or node.js, you can control this simple Arduino program serially.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Change_the_Brightness_of_the_LED_Bytes_Serially\"><\/span>Change the Brightness of the LED Bytes Serially<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>The microcontroller reads&nbsp;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&nbsp;the byte values any way you wish. Change the loop of your program as shown below:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: arduino; title: ; notranslate\" title=\"\">\nvoid loop() {\n  \/\/ put your main code here, to run repeatedly:\n  if (Serial.available() &gt; 0) {\n    byte input = Serial.read();\n    \/\/ use the value of the incoming byte to control the LED&#039;s brightness:\n    analogWrite(11, input);\n  }\n}\n<\/pre><\/div>\n\n\n<p>Upload this new sketch and open the serial monitor. When you send characters now, what&#8217;s happening? The LED&#8217;s brightness might be jumping around, seemingly randomly. &nbsp;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.<\/p>\n\n\n\n<p><a rel=\"noopener\" href=\"https:\/\/vimeo.com\/380356227#t=4m15s\">Related Video: reading a byte from the computer in Arduino<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Advanced_Serial_Input_Parsing_Numeric_Strings\"><\/span>Advanced Serial Input: Parsing Numeric Strings<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>But what if you want to send an ASCII-encoded numeric string? &nbsp;Why doesn&#8217;t the LED turn on to full brightness when you type &#8220;255&#8221;? &nbsp;Even though you interpret the characters as one number, the Arduino interprets them as three bytes, with the values 50 (&#8220;2&#8221; = ASCII 50), 53 (&#8220;5&#8221; = ASCII 53), and 53. How do you get the Arduino to convert these strings as numbers?<\/p>\n\n\n\n<p>You can use the <code>Serial.parseInt()<\/code> 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&#8217;s loop as follows:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: arduino; title: ; notranslate\" title=\"\">\nvoid loop() {\n  \/\/ put your main code here, to run repeatedly:\n  if (Serial.available() &gt; 0) {\n    int input = Serial.parseInt();\n    \/\/ use the value of the incoming byte to control the LED&#039;s brightness:\n    analogWrite(11, input);\n  }\n}\n<\/pre><\/div>\n\n\n<p>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, <code>.parseInt()<\/code> 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:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">10,127,255 0 255 0 12-250-3<\/pre>\n\n\n\n<p>You can separate your numbers however you wish. You could even look for multiple&nbsp;different numbers with multiple variables, like this:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: arduino; title: ; notranslate\" title=\"\">\nvoid loop() {\n  \/\/ put your main code here, to run repeatedly:\n  if (Serial.available() &gt; 0) {\n    int red = Serial.parseInt();\n    int green = Serial.parseInt();\n    int blue = Serial.parseInt();\n  }\n}\n<\/pre><\/div>\n\n\n<p>With the code above, if you sent three comma-separated values, you&#8217;d be able to set the three variables red, green, and blue independently.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"SerialsetTimeout\"><\/span>Serial.setTimeout()<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>You may notice that <code>.parseInt()<\/code> 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 <code>Serial.begin()<\/code>, try a <code>Serial.setTimeout(10)<\/code> to set the timeout to 10 milliseconds. This is generally good for most programs that might be sending ASCII strings to the microcontroller.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Serial_Control_from_Nodejs\"><\/span>Serial Control from Node.js<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>If you&#8217;re familiar with node.js and the node-serialport library, perhaps because you&#8217;ve already tried the <a href=\"https:\/\/itp.nyu.edu\/physcomp\/labs\/labs-serial-communication\/lab-serial-communication-with-node-js\/\">Serial to&nbsp;node.js lab<\/a>, upload&nbsp;the following Arduino sketch:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: arduino; title: ; notranslate\" title=\"\">\nvoid setup() {\n  \/\/ put your setup code here, to run once:\n  Serial.begin(9600);\n  Serial.setTimeout(10);\n  pinMode(11, OUTPUT);\n}\n\nvoid loop() {\n  \/\/ put your main code here, to run repeatedly:\n  if (Serial.available() &gt; 0) {\n    char input = Serial.parseInt();\n    \/\/ use the value of the incoming byte to control the LED&#039;s brightness:\n    analogWrite(11, input);\n  }\n}\n<\/pre><\/div>\n\n\n<p>Now try the following node.js script (you&#8217;ll need to install node-serialport using npm as you did in the <a href=\"https:\/\/itp.nyu.edu\/physcomp\/labs\/labs-serial-communication\/lab-serial-communication-with-node-js\/\">Serial to node.js lab<\/a>). Save this as <code>serialOutput.js<\/code>:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\n\/\/ serial port initialization:\nvar SerialPort = require(&#039;serialport&#039;); \/\/ include the serialport library\nvar portName = process.argv&#x5B;2]; \/\/ get the port name from the command line\nvar myPort = new SerialPort(portName, 9600);\/\/ open the port\n\n\/\/ these are the definitions for the serial events:\nmyPort.on(&#039;open&#039;, openPort); \/\/ called when the serial port opens\n\nfunction openPort() {\n  var brightness = 0; \/\/ the brightness to send for the LED\n  console.log(&#039;port open&#039;);\n  console.log(&#039;baud rate: &#039; + myPort.options.baudRate);\n\n  \/\/ since you only send data when the port is open, this function\n  \/\/ is local to the openPort() function:\n  function sendData() {\n    \/\/ convert the value to an ASCII string before sending it:\n    myPort.write(brightness.toString());\n    console.log(&#039;Sending &#039; + brightness + &#039; out the serial port&#039;);\n    \/\/ increment brightness by 10 points. Rollover if &lt; 255:\n    if (brightness &lt; 255) {\n      brightness+= 10;\n    } else {\n      brightness = 0;\n  }\n}\n\n\/\/ set an interval to update the brightness 2 times per second:\nsetInterval(sendData, 500);\n}\n<\/pre><\/div>\n\n\n<p>Make sure the serial monitor in Arduino is closed, then&nbsp;run this by typing the following on the command line:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">$ node&nbsp;serialOutput.js portname<\/pre>\n\n\n\n<p>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.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this lab, you\u2019ll send asynchronous serial data from your personal computer to an Arduino microcontroller in order to control a digital output of the microcontroller. Once you\u2019ve done that, you\u2019ll also learn how to interpret ASCII-encoded numeric strings on the Arduino.<\/p>\n","protected":false},"author":2,"featured_media":0,"parent":1979,"menu_order":230,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"categories":[11,15,16,9],"tags":[],"class_list":["post-3588","page","type-page","status-publish","hentry","category-code","category-lab","category-node-js","category-serial-communication"],"_links":{"self":[{"href":"https:\/\/itp.nyu.edu\/physcomp\/wp-json\/wp\/v2\/pages\/3588"}],"collection":[{"href":"https:\/\/itp.nyu.edu\/physcomp\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/itp.nyu.edu\/physcomp\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/itp.nyu.edu\/physcomp\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/itp.nyu.edu\/physcomp\/wp-json\/wp\/v2\/comments?post=3588"}],"version-history":[{"count":43,"href":"https:\/\/itp.nyu.edu\/physcomp\/wp-json\/wp\/v2\/pages\/3588\/revisions"}],"predecessor-version":[{"id":10728,"href":"https:\/\/itp.nyu.edu\/physcomp\/wp-json\/wp\/v2\/pages\/3588\/revisions\/10728"}],"up":[{"embeddable":true,"href":"https:\/\/itp.nyu.edu\/physcomp\/wp-json\/wp\/v2\/pages\/1979"}],"wp:attachment":[{"href":"https:\/\/itp.nyu.edu\/physcomp\/wp-json\/wp\/v2\/media?parent=3588"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/itp.nyu.edu\/physcomp\/wp-json\/wp\/v2\/categories?post=3588"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/itp.nyu.edu\/physcomp\/wp-json\/wp\/v2\/tags?post=3588"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}