Select COM port in sketch through drop down list using controlP5 and serial library

edited June 2017 in Share Your Work

So i made this simple sketch where you can easily select the serial port in a drop down meny. I used the Serial and controlp5 library. Hope you like it, Enjoy!

import processing.serial.*;
import controlP5.*;

ControlP5 cp5;
DropdownList d1;

Serial myPort;

String portName;
int serialListIndex;

void setup() {
  size(700, 400 );
  cp5 = new ControlP5(this);

  PFont pfont = createFont("Arial",10,true); //Create a font
  ControlFont font = new ControlFont(pfont,20); //font, font-size

  d1 = cp5.addDropdownList("myList-d1")
          .setPosition(100, 100)
          .setSize(100, 200)
          .setColorActive(color(255, 128))

      d1.getCaptionLabel().set("PORT"); //set PORT before anything is selected

      portName = Serial.list()[0]; //0 as default
      myPort = new Serial(this, portName, 9600);

void draw() {

  if(d1.isMouseOver()) {
   d1.clear(); //Delete all the items
   for (int i=0;i<Serial.list().length;i++) {
     d1.addItem(Serial.list()[i], i); //add the items in the list
  if ( myPort.available() > 0) {  //read incoming data from serial port
    println(myPort.readStringUntil('\n')); //read until new input

void controlEvent(ControlEvent theEvent) { //when something in the list is selected
    myPort.clear(); //delete the port
    myPort.stop(); //stop the port
    if (theEvent.isController() && d1.isMouseOver()) {
    portName = Serial.list()[int(theEvent.getController().getValue())]; //port name is set to the selected port in the dropDownMeny
    myPort = new Serial(this, portName, 9600); //Create a new connection
    println("Serial index set to: " + theEvent.getController().getValue());


Sign In or Register to comment.