Comments: Connecting Arduino to Processing

Pages

Comments 24 comments

  • I have done displaying the string from arduino to pc but it is showing “null” and then “hello world” displays any method to stop displaying “null” and stop the code when it reaches end of file.

  • Using an arduino Mega and processing 3.3 Sending Data from the arduino to processing I dont have an issue.

    Using a exact copy of the code for sending data from Processing to Arduino and issues arrise. The Pin 13 Light turns on and never turns off, even when I switch to a different pin in the sketch Pin 13 doesn’t turn off until I use the serial monitor in the Arduino IDE or reset the arduino

  •     import processing.serial.*;
         //import the Serial library
         Serial myPort;  //the Serial port object
         String val;
        // since we're doing serial handshaking, 
        // we need to check if we've heard from the microcontroller
        boolean firstContact = false;
    
        void setup() {
          size(200, 200); //make our canvas 200 x 200 pixels big
          //  initialize your serial port and set the baud rate to 9600
          myPort = new Serial(this, Serial.list()[4], 9600);
          myPort.bufferUntil('\n'); 
        }
        void draw() {
          //we can leave the draw method empty, 
          //because all our programming happens in the serialEvent (see below)
        }
    
        void serialEvent( Serial myPort) {
        //put the incoming data into a String - 
        //the '\n' is our end delimiter indicating the end of a complete packet
        val = myPort.readStringUntil('\n');
        //make sure our data isn't empty before continuing
        if (val != null) {
          //trim whitespace and formatting characters (like carriage return)
          val = trim(val);
          println(val);
    
          //look for our 'A' string to start the handshake
          //if it's there, clear the buffer, and send a request for data
          if (firstContact == false) {
            if (val.equals("A")) {
              myPort.clear();
              firstContact = true;
              myPort.write("A");
              println("contact");
            }
          }
          else { //if we've already established contact, keep getting and parsing data
            println(val);
    
            if (mousePressed == true) 
            {                           //if we clicked in the window
              myPort.write('1');        //send a 1
              println("1");
            }
    
            // when you've parsed the data you have, ask for more:
            myPort.write("A");
            }
          }
        }
    

    I pasted the code, as in the tutorial with Processing3.2.2 with Arduino Genuino 101.

    It gave me on Processing the following ErrorArrayIndexOutOfBoundsExeption 4 and underline this part of the code

        myPort = new Serial(this, Serial.list()[4], 9600);
    

    I am a newbie, and i am learning how to code. Thank you for helping me improve

    • make it [0]

    • Hi, I am new to electronics too. I got this project to work. Your error was the same one I had - the serial port # has to be corrected to match the port # used by your operating system. In my case the port was #1. So my line looked like this:

      myPort = new Serial(this, Serial.list()[1], 9600);

      You can figure out the port # for your computer by trial and error. Simply edit the line by changing the port number to 1, run the sketch and if you get the error message, change it to 2 and run the sketch again. Repeat until you have no error message.

  • Here’s an interesting thing I noted - Please try this and let me know if you get the same results:

    Initially the Processing example (the first serial test) was printing a LOT of Hello, world!’s. I thought it looked like way faster than 100 ms, so I changed the Arduino code to loop every 1000 ms instead. Same thing coming out of the Processing script! A quick look at the Processing sketch showed me why: The ‘println’ is outside the ‘if’ statement that checks for serial data, so it prints every loop instead of waiting for new data. So I moved it into the ‘if’ block and everything was pretty!

    I know.. I’m getting to the fun part. After the ‘if’ block mode to the Processor sketch, add a counter variable to the Arduino sketch, and print it and increment it in the loop, then slow the delay to 1000 ms. Like this:

    int counter = 0;

    void setup() { // put your setup code here, to run once: //initialize serial communications at a 9600 baud rate Serial.begin(9600); }

    void loop() { // put your main code here, to run repeatedly: //send ‘Hello, world!’ over the serial port Serial.println(“Hello, world!”); Serial.println(counter); //wait 1000 milliseconds so we don’t drive ourselves crazy delay(1000); counter++; }

    Now for the odd portion: Upload the new Arduino sketch and run the Processor sketch. Stop the Processor sketch. If you start it again, what do you think you’ll see?

    First hypothesis: The serial buffer is pretty big, so it’ll just wait until Processing grabs the next bits, and the numbers will start where they left off.

    Nope!

    Second: The numbers just keep going and the Windows serial routine just drops them, so you’ll get some numbers starting a good bit higher than when you stopped.

    Sorry Charlie!

    What you’ll see, almost every time, is that the numbers start from zero again!!! Why? The Arduino didn’t stop. The TX light is still blinking every second. The count should just keep going, one way or the other, right?? So what in the digital world is going on!?!??!?!??!

    I say almost every time, because occasionally the first number you get is the next from when you stopped, obviously still in the buffer. Then it starts at zero. It HAS to be the Arduino, somehow sensing the restart and resetting the sketch - but how? There is no mechanism for that that I’m aware of, and I certainly didn’t put any serial status code in the script.

    Can anyone exlpain???

  • Would this also work for raspberry Pi 2 Model B?

  • Arduino code:


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

    void loop() { Serial.println(“hello world”); delay(100); }


    processing code:


    import processing.serial.*;

    Serial myPort; // Create object from Serial class String val; // Data received from the serial port void setup() {// I know that the first port in the serial list on my mac // is Serial.list()[0]. // On Windows machines, this generally opens COM1. // Open whatever port is the one you’re using. String portName = Serial.list()[0]; //change the 0 to a 1 or 2 etc. to match your port myPort = new Serial(this, portName, 9600); } void draw() { if ( myPort.available() > 0) { // If data is available, val = myPort.readStringUntil(‘\n’); // read it and store it in val } println(val); //print it out in the console }


    it’s work when i press run button on p5

    but the p5’s console is pop up null,null,null,

    how can i fix it to pop up ‘hello world’

    help me,please…this made me crazy >___<

  • Here is the code I’m using in processing. The problem is at the bottom it says error opening serial port/dev.cu.Bluetooth-modem:Port busy. PLEASE HELP! I’m using this processing sketch with arduino code. Thanks!

    /* This program functions as a data visualizer for the Pulse Sensor Serial input is designed to mate with arduino sketch “A_PulseSensor_xx” This code made by Joel Murphy and Yury Gitman in Brooklyn, Summer 2011.

    interactive features in this version: press ’S' or ’s' to take a picture of the data window. (.tif image) Pulse data window will plot pulse 1:1 (ADC value : pixesls) and auto adjust to fit waveform in screen CC Attribution Share-Alike http://creativecommons.org/licenses/by-sa/3.0/us/ */

    import processing.serial.*; // this is how we talk to arduino PFont font, rateFont, smallFont; // create font instances Serial port; // create and name the serial port

    int heart = 0; // used to time pulsing of heart graphic with your heart beat int pulseRate = 0; // used to hold pulse rate value sent from arduino (beats per minute) int Sensor = 0; // used to hold raw sensor data from arduino int HRV; // time between this current beat and the last beat in mS (used for Heart Rate Variability) int Ypos; // used to print the new Pulse Sensor data point int[] pulseY; // used to hold pulse waveform Y positions int[] rateY; // used to hold bpm waveform Y positions // these variables will hold pulse window specs int PulseWindowMin; int PulseWindowMax;
    int PulseWindowW; int PulseWindowH; int PulseWindowY; int PulseWindowX; int PulseDisplayBaseline = 712; // these variables are used to adjust the pulse window display int PulseOffset = 712; // the max and min will auto adjust if the waveform drifts beyond the screen

    color eggshell = color(255,253,248); // offwhite color for data display windows color R = color(250,0,0); // red color for datapoints and heart graphic int grey = 80; // grey color for numeric data windows

    boolean beat = false; // used to advance heart rate graph boolean newRate = false; // used to update heart rate display

    void setup() { size(800,600); // Stage size frameRate(100); // refresh rate font = loadFont(“Arial-BoldMT-36.vlw”); // font for small text rateFont = loadFont(“Arial-BoldMT-80.vlw”); // font for larger text smallFont = loadFont(“Arial-BoldMT-14.vlw”); // font for smaller text textFont(font); // set up to print small font textAlign(RIGHT); // referemce points rectMode(CENTER);

    // define the size of the pulse window PulseWindowW = 710; // width of pulse window PulseWindowH = 400; // height of pulse window PulseWindowX = width/2+30; // center X coordinate of pulse window PulseWindowY = height-225; // center Y coordinate of pulse window PulseWindowMin = PulseWindowY - PulseWindowH/2; // top Y position of pulse window PulseWindowMax = PulseWindowY + PulseWindowH/2; // bottom Y position of pulse window

    pulseY = new int[PulseWindowW+1]; // array to hold Y coordinate of pulse datapoints rateY = new int[320]; // array to hold y coordinate of heart rate datapoints

    // find and establish contact with the serial port println(Serial.list()); // print a list of available serial ports port = new Serial(this, Serial.list()[0], 115200); // choose the right one in square brackets port.bufferUntil(‘\n’); // arduino will end each ascii string with a ‘\n’ at the end (carriage return) port.clear(); // flush the serial buffer

    // set arbitrary initial data position at top of pulse window Ypos = PulseWindowMin;
    for (int i = 0; i < pulseY.length; i++){
    pulseY[i] = PulseWindowMin;
    }

    // set the BPM visualizer line to 0 for (int i=0; i<rateY.length; i++){ rateY[i] = 162; // 162 is the pixel height for 0 heart rate } }

    void draw(){

    printScreen(); // DRAW THE MAJOR SCREEN COMPONENTS AND TEXT

    // THESE ARE THE PULSE SENSOR WAVEFORM DRAWING ROUTINES // fisrt, move the Y coordintae of previous pulse data points over one pixel to the left for (int i = 0; i < pulseY.length-1; i++){
    pulseY[i] = pulseY[i+1];
    } // new data enters on the right of the screen. sensor value is placed in the last array position pulseY[pulseY.length-1] = Ypos; // Ypos is updated in the serialEvent tab // This for loop renders the Pulse Sensor waveform for (int x = 1; x < pulseY.length-1; x++){ // variable ‘x’ will take the place of pixel x position stroke®; // get ready to make a red line // Here are a few ways to draw the datapoints.
    // line(x+61, pulseY[x]+1, x+61, pulseY[x]-1); // display previous datapoint as vertical line // point(x+61,pulseY[x]); //display previous datapoint as point // ellipse(x+61,pulseY[x],1,1); // display previous datapoint as a small dot line(x+76, pulseY[x], x+75, pulseY[x-1]); //display previous datapoint as a connected line }

    // THESE ARE THE HEART RATE DRAWING ROUTINES if (beat == true){ // only move the heart rate line over once every time the heart beats (beat flag set in serialEvent tab) beat = false; // reset beat flag for (int i=0; i<rateY.length-1; i++){ rateY[i] = rateY[i+1]; // shif the bpm Y coordinates over one pixel to the left } } // update the BPM display Y coordinate when arduino sends a new calculation if (newRate == true){ // when the new rate is sent from arduino float dummy = map(pulseRate,0,200,135,10); // map it to the heart rate window Y rateY[rateY.length-1] = int(dummy); // set the rightmost pixel to the new data point value } // print out the graph of the heart rate stroke(250,0,0); // color of heart rate graph for (int x=0; x < rateY.length-1; x++){ // variable ‘x’ will take the place of pixel x position line(x+76, rateY[x]+2, x+76, rateY[x]-2); // display previous heart rate datapoint as vertical line } } //end of draw loop

    void printScreen(){ // DRAW MAJOR SCREEN ELEMENTS AND TEXT background(0); // black background noStroke();
    fill(grey); // grey rect(40,PulseWindowY,70,PulseWindowH); // draw box around pulse window numbers
    rect(40,90,70,150); // draw box around rate window numbers
    fill(eggshell); // eggshell rect(PulseWindowX,PulseWindowY,PulseWindowW,PulseWindowH); // draw pulse terminal rect(235,90,320,150); // draw bpm terminal text(“0”,65,163); // print ʻ0ʻ at bottom of bpm terminal (min heart rate for zombies) text(“200”,65,35); // print ʻ200ʻ at top of bpm terminal (max heart rate for young runners) text(HRV,65,PulseWindowY); // print the waveform amplitude text(“BPM”,width-215,100); // clarification (BPM = Beats Per Minute = heart rate) text(“Pulse Sensor Visualizer 0.6”,width-35,160); // name of program, version
    textFont(smallFont); text(“mS Time”,72,PulseWindowY + 20); text(“Between”,72,PulseWindowY + 40); // print the high number of visible datapoints (DEPENDS ON AUTO OFFSET) text(“Beats”,72,PulseWindowY + 60); // print the low number of visible datapoints (DITTO)
    textFont(rateFont); // set up to print large text text(pulseRate,width-275,100); // print out the pulse rate textFont(font); // set up to print small text

    // DRAW THE HEART AND MAYBE MAKE IT BEAT fill(250,0,0); stroke(250,0,0); heart–; // the heart variable is used to time how long the heart graphic swells when your heart beats if (heart < 0){heart = 0;} // don’t let the heart variable go into negative numbers if (heart > 0){ // if a beat happened recently, strokeWeight(8); // make the heart big } smooth(); // draw the heart with two bezier curves bezier(width-125,30, width-45,-40, width-25,120, width-125,130); bezier(width-125,30, width-215,-40, width-225,120, width-125,130); strokeWeight(1); // reset the strokeWeight

    } // END OF printScreen FUNCTION

    // original heart design and positioning // bezier(width-150,50, width-70,-20, width-50,140, width-150,150); // bezier(width-150,50, width-230,-20, width-250,140, width-150,150);

  • //Here's my code:
    
    //The error I get is: ArrayIndexOutOfBoundsException:3
    
    //My Arduino is on COM3
    
    // Notes/comments were to myself.  Not meant to be insulting. I am just learning.
    
    
    //Uncomment, (remove the forward slashes) cut and Paste this first section into Arduino:
    //void setup ()
    //{
    //  //initialize serial communication at 9600 baud rate
    //  Serial.begin(9600);
    //}
    //
    //void loop()
    //{
    //  //send "Hello World!" over the serial port
    //  Serial.println ("Hello World");
    // wait 100 milliseconds so we don't drive ourselves crazy
    //  delay (100);
    //}
    //********************************************************************************************
    
    //Cut and Paste from here down into Processing
    
    import processing.serial.*;
    
    Serial myPort;  // Create object from Serial class
    String val;     // Data received from the serial port
    
    void setup() 
    {
     String portName = Serial.list()[3]; //change the 0 to a 1 or 2 etc. to match your port
     myPort = new Serial(this, portName, 9600);
    }
       void draw()
        {
          if ( myPort.available() > 0) 
          {  // If data is available,
          val = myPort.readStringUntil('\n');         // read it and store it in val
          } 
        println(val); //print it out in the console
        }
    
    //***********************************************************************************************
    
    //If you're not sure which port your Arduino is on. Open a new Processing sketch, 
    // uncomment (remove the forward slashes at the start of each line) 
    //cut, paste and run the following into Processing to get a list of ports:
    //
    //import processing.serial.*;
    // void setup() {
    // println(Serial.list());
    //}
    
    • Just Copied and Pasted the exact same code into a fresh Processing sketch and it worked perfectly. Not sure why that would be?

      Thanks heaps for this Excellent Tutorial. It’s a great.

  • Thank you for this tutorial. It is just what i am looking for!

    I get the error message (OS = Mac):

    Error opening serial port /dev/tty.usbmodel1451: Port busy

    when trying to run Processing after starting to run the Arduino sketch on this port.

    It makes sense the port is busy. However, for this to work they must share.

    What am i doing wrong that will not allow sharing of the serial port? (thank you very much.

    • I got this too. I was using the serial monitor in the Arduino software at the same time. After I shut the serial monitor down everything started working.

  • In the first processing sketch, I keep getting a “ArryIndexOutOfBoundsException: 3” error Here is the code I am using:

    import processing.serial.*;
    
    Serial myPort;  // Create object from Serial class
    String val;     // Data received from the serial port
    // I know that the first port in the serial list on my mac
    // is Serial.list()[0].
    // On Windows machines, this generally opens COM1.
    // Open whatever port is the one you're using.
    
    void setup() 
    {
    String portName = Serial.list()[3]; //change the 0 to a 1 or 2 etc. to match your port
    myPort = new Serial(this, portName, 9600);
    }
    void draw()
    {
      if ( myPort.available() > 0) 
      {  // If data is available,
      val = myPort.readStringUntil('\n');         // read it and store it in val
      } 
    println(val); //print it out in the console
    }
    
    • Looks like you are picking the wrong number in the array to pick your serial port – if you’re using a 3 in the line:

      String portName = Serial.list()[3];

      Try replacing that 3 with a 0, 1, or 2 instead.

      • Hi b_e_n,

        Just thought I’d let you know that I was having the exact sam error. then I cut and pasted the code into a new sketch and had no errors. Not sure why this would be but thought you may want to try it.

        All the code required is in my comment above.

  • I can’t get this to work, even had my friend look at it. when i run it, it says, “expecting EOF, found ‘myPort’, and it highlights the following line of code, like it doesn’t like it:

    myPort = new Serial(this, portName, 9600);

    we tried changing the line of code above it to [1], and 2-9 etc in order to try to get this little tutorial to work, but no such luck. I’m using a mac osx system, an arduino uno, processing 2.2.1….totally hopelessly stuck and need help on getting this to work!

    Anyone?! I would be grateful–

    • To clarify b_e_n’s comment just a touch, check the line directly above myPort = ..., not the code you posted above. :)

    • Is the code above properly terminated with a semicolon? Are your parentheses properly matched and nested? This error occurs due to a syntax error in your code, has nothing to do with your serial port.

  • Really great guide, however using the arduino mega I experienced some strange results going from processing to arduino:

    I was using the if / else statement in the void draw in processing with the actual line writing to serial being this: myPort.write(1); (I was using straight bytes rather than chars from another tutorial that ended up working)

    when run the RX light was blinking fast, on almost solid which made sense since it was supposedly transmitting either the 1, or the 0 depending if I was clicking or not.

    However, the Arduino was not receiving any actual bytes and the only time I got a response was in the else statement since it covered not receiving a byte as well.

    What I stumbled across that worked, was using using a method like this:

    void mousePressed() {
            squareVisible = !squareVisible;
            if(squareVisible) port.write(0);
            else              port.write(1);
    }
    

    Any ideas why that would work for me , and the continuous method wouldn’t?

  • hello i am doing a project on face tracking. i have a problem communicating with the arduino via processing. it gives a null pointer exception error on the line arduinoPort.write(‘a’); .do u have any idea why this is happening. if you want i can send you the codes to look at thank you.

  • When you don’t know which number of port to choose, read this: In the processing sketch in the part where you have to change the 0 to a 1 or 2 etc. to match your port. : String portName = Serial.list()[4]; I tried 0, 1 and 2 and always got an error saying"the port is busy". To solve that, I run this code in processing.

    import processing.serial.*;
     void setup() {
     println(Serial.list());
    }
    

    That gives you a list of ports. Make sure the Arduino is connected and check which one is your Arduino using (tools>serial port) Then count in the list processing gave you, which number is that, starting from 0. Mine was 4, so I just replaced 0 for 4 in: String portName = Serial.list()[4];

  • While trying out the given set of code, I had some difficulty with the “myPort.readStringUntil(‘\n’)” line. The processing program keeps telling me badlyd formed character constant for the ‘\n’ part. that line of code is continuously highlighted and refuses to work. An suggestions? void draw() { if ( myPort.available() > 0) { // If data is available, val = myPort.readStringUntil(‘\n’); // read it and store it in val } println(val); //print it out in the console }

    • Try replacing the “myPort.readStringUntil(‘\n’)” line for “myPort.readString()”, so your void draw will look like this: void draw() { if ( myPort.available() > 0) { // If data is available, val = myPort.readString(); // read it and store it in val } println(val); //print it out in the console }


If you've found a bug or have other constructive feedback for our tutorial authors, please send us your feedback!