API Docs for:
Show:

p5.SerialPort Class

Module: p5.serialport
Parent Module: p5.serialport

Base class for a serial port. Creates an instance of the serial library and prints "hostname":"serverPort" in the console.

Constructor

p5.SerialPort

(
  • [hostname]
  • [serverPort]
)

Parameters:

  • [hostname] String optional

    Name of the host. Defaults to 'localhost'.

  • [serverPort] Number optional

    Port number. Defaults to 8081.

Example:

var portName = '/dev/cu.usbmodem1411'; //enter your portName
    
function setup() {
     createCanvas(400, 300);
     serial = new p5.SerialPort()
     serial.open(portName);
}

Methods

available

() Number

Returns the number of bytes available.

Returns:

Number:

The length of the serial buffer array, in terms of number of bytes in the buffer.

Example:

    function draw() {
        // black background, white text:
        background(0);
        fill(255);
        // display the incoming serial data as a string:
        var displayString = "inByte: " + inByte + "\t Byte count: " + byteCount;
        displayString += "  available: " + serial.available();
        text(displayString, 30, 60);
        }

clear

()

Clears the underlying serial buffer.

Example:

close

(
  • name
)

Tell server to close the serial port. This functions the same way as serial.on('close', portClose).

Parameters:

  • name String

    of callback

Example:

    var inData;
    
    function setup() {
      serial.open(portOpen);
      serial.close(portClose); 
    }

function portOpen() {
      println('The serial port is open.');
    }  
     
    function portClose() {
      println('The serial port closed.');
    }  

emit

() private

Returns:

Example:

isConnected

() Boolean

Tells you whether p5 is connected to the serial port.

Returns:

Boolean:

true or false

Example:

    var serial; // variable to hold an instance of the serialport library
    var portName = '/dev/cu.usbmodem1411';
    
    function setup() {
        createCanvas(400, 300);
        serial = new p5.SerialPort();
        serial.open(portName);
        println(serial.isConnected());
    }

last

() Number

Returns the last byte of data from the buffer.

Returns:

Number:

Example:

lastChar

()

Returns the last byte of data from the buffer as a char.

Example:

list

() Array

Lists serial ports available to the server. Synchronously returns cached list, asynchronously returns updated list via callback. Must be called within the p5 setup() function. Doesn't work with the p5 editor's "Run in Browser" mode.

Returns:

Array:

array of available serial ports

Example:

    function setup() {
    createCanvas(windowWidth, windowHeight);
    serial = new p5.SerialPort();
    serial.list();
    serial.open("/dev/cu.usbmodem1411");
    }

For full example: Link

    function printList(portList) {
      // portList is an array of serial port names
      for (var i = 0; i < portList.length; i++) {
        // Display the list the console:
        println(i + " " + portList[i]);
      }
    }

open

(
  • serialPort
  • [serialOptions]
  • [serialCallback]
)

Opens the serial port to enable data flow. Use the {[serialOptions]} parameter to set the baudrate if it's different from the p5 default, 9600.

Parameters:

  • serialPort String

    Name of the serial port, something like '/dev/cu.usbmodem1411'

  • [serialOptions] Object optional

    Object with optional options as {key: value} pairs. Options include 'baudrate'.

  • [serialCallback] Function optional

    Callback function when open completes

Example:

    // Change this to the name of your arduino's serial port
    serial.open("/dev/cu.usbmodem1411");
    // All of the following are valid:
    serial.open(portName);
    serial.open(portName, {}, onOpen);
    serial.open(portName, {baudrate: 9600}, onOpen)
    
    function onOpen() {
      print('opened the serial port!');
    }

read

() Number

Returns a number between 0 and 255 for the next byte that's waiting in the buffer. Returns -1 if there is no byte, although this should be avoided by first checking available() to see if data is available.

Returns:

Number:

Value of the byte waiting in the buffer. Returns -1 if there is no byte.

Example:

    function serialEvent() {
    inByte = int(serial.read());
        byteCount++;
    }
    function serialEvent() {
        // read a byte from the serial port:
        var inByte = serial.read();
        // store it in a global variable:
        inData = inByte;
    }

readBytes

() Number

Returns a number between 0 and 255 for the next byte that's waiting in the buffer, and then clears the buffer of data. Returns -1 if there is no byte, although this should be avoided by first checking available() to see if data is available.

Returns:

Number:

Value of the byte waiting in the buffer. Returns -1 if there is no byte.

Example:

    var inData;
    
    function setup() {
      // callback for when new data arrives
      serial.on('data', serialEvent); 
      
    function serialEvent() {
      // read bytes from the serial port:
      inData = serial.readBytes();
    }

readBytesUntil

(
  • UNKNOWN
)
Number

Returns all of the data available, up to and including a particular character. If the character isn't in the buffer, 'null' is returned. The version without the byteBuffer parameter returns a byte array of all data up to and including the interesting byte. This is not efficient, but is easy to use.

The version with the byteBuffer parameter is more efficient in terms of time and memory. It grabs the data in the buffer and puts it into the byte array passed in and returns an integer value for the number of bytes read. If the byte buffer is not large enough, -1 is returned and an error is printed to the message area. If nothing is in the buffer, 0 is returned.

Parameters:

  • UNKNOWN byteBuffer

Returns:

Number:

[Number of bytes read]

Example:

    // All of the following are valid:
    charToFind.charCodeAt();
    charToFind.charCodeAt(0);
    charToFind.charCodeAt(0, );

readChar

() String

Returns the next byte in the buffer as a char.

Returns:

String:

Value of the Unicode-code unit character byte waiting in the buffer, converted from bytes. Returns -1 or 0xffff if there is no byte.

Example:

    var inData;
    
    function setup() {
      // callback for when new data arrives
      serial.on('data', serialEvent); 
      
    function serialEvent() {
      // read a char from the serial port:
      inData = serial.readChar();
    }

readLine

() String

Returns all of the data available as an ASCII-encoded string until a line break is encountered.

Returns:

String:

ASCII-encoded string

Example:

You can use this with the included Arduino example called AnalogReadSerial. Works with P5 editor as the socket/serial server, version 0.5.5 or later. Written 2 Oct 2015 by Tom Igoe. For full example: Link

    function gotData() {
      var currentString = serial.readLine();  // read the incoming data
          trim(currentString);                    // trim off trailing whitespace
        
          if (!currentString) return; {            // if the incoming string is empty, do no more 
            console.log(currentString);
            }
            
          if (!isNaN(currentString)) {  // make sure the string is a number (i.e. NOT Not a Number (NaN))
            textXpos = currentString;   // save the currentString to use for the text position in draw()
            }
        }

readString

()

Returns all the data from the buffer as a String. This method assumes the incoming characters are ASCII. If you want to transfer Unicode data: first, convert the String to a byte stream in the representation of your choice (i.e. UTF8 or two-byte Unicode data). Then, send it as a byte array.

Returns:

Example:

readStringUntil

(
  • stringToFind
)
String

Returns all of the data available as an ASCII-encoded string.

Parameters:

  • stringToFind String

    String to read until.

Returns:

String:

ASCII-encoded string until and not including the stringToFind.

Example:

For full example: Link

     var serial1 = new p5.SerialPort();
     var serial2 = new p5.SerialPort();
     var input1 = '';
     var input2 = '';
    
     function serialEvent(){
            data = serial1.readStringUntil('\r\n');
            if (data.length > 0){
            input1 = data;
            }
     }
     
     function serial2Event() {
            var data = serial2.readStringUntil('\r\n');
            if (data.length > 0){
            input2 = data;
            }
     }

stop

()

Stops data communication on this port. Use to shut the connection when you're finished with the Serial.

Example:

write

(
  • Data
)

Sends a byte to a webSocket server which sends the same byte out through a serial port.

Parameters:

  • Data String, Number, Array

    Writes bytes, chars, ints, bytes[], and strings to the serial port.

Example:

You can use this with the included Arduino example called PhysicalPixel. Works with P5 editor as the socket/serial server, version 0.5.5 or later. Written 2 Oct 2015 by Tom Igoe. For full example: Link

    function mouseReleased() {
          serial.write(outMessage);
          if (outMessage === 'H') {
            outMessage = 'L';
          } else {
            outMessage = 'H';
          }
    }

For full example: Link

    function mouseDragged() {
      // 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);
    }