BLOG > Tutorial 6 for Arduino: Serial Comm and Processing

This tutorial was featured on the official Arduino blog on 3/9/2011

The next four episodes are all about communicating between the Arduino and other devices.  In this video, we’ll focus on communicating with the computer via a standard serial connection.  We’ll be using a new programming language called “processing” to visualize some information from the Arduino on the computer screen.  If you are new to processing, they have an excellent set of tutorials to help you get started.

The Arduino Contest has been extended! You only have 1 more week to submit your project!

EDIT:
Serial.flush() has changed in Arduino 1.0.  You can use the following instead:
while(Serial.available()>0) Serial.read();

You can download the files associated with this episode here:

GNU GPL License Distributed under the GNU General Public (Open-Source) License.
Please Attribute and Share-Alike.

 

252 comments

  1. Great job on the tutorials. The processing help is awesome for beginners. Showing how to collect data (like temp), display in a graph (on processing), and save to a file would be a really cool tutorial if you are looking for ideas! I would love to see something like that.

  2. hi jerry in the processing window i just get a warning like this
    RXTX Version mismatch
    Jar version = RXTX-2.2pre1
    native lib Version = RXTX-2.2pre2

    1. At Rocky
      Your RXTX error generally relates to trying to run on 64bit Windows 7. You need the Cloudhopper Library, which you need to install in your Java directory. As Processing is just an interface to Java.

      I am still having trouble with getting a reliable connection. But at least the error has gone and it sometimes works.

  3. hi jerry i have a doubt if i m gonna use a joystick it has two axis x and y how will i giv the input via serial communication any ideas pls.. :(

  4. Jeremy,
    I have been stuck on the multiple invalid glitch for a week.
    I’ve tried both combinations “(Serial.flush & while(Serial.available()>0) Serial.read();” and copied and pasted the whole code right from your pde file but I still get repeats.
    I can’t move forward till I understand and correct this problem.
    Could it be that Arduino 1.0 is playing well on my Duemilanove?
    Thanks for your help.
    Jim G.

      1. Yes i have the same problem myself. I’d like to add that for the first part of the tutorial (with serial print val that goes to 48 and after correction to 0) it prints two numbers for me.
        for 0 it prints “48” and just under “10”
        After correction and still for zero: “0” an just under “38”.

        My code is absolutely the same as the tutorial..?

    1. Serial.flush() has changed in Arduino 1.0. You can use the following instead:
      while(Serial.available()>0) Serial.read();

  5. did anyone solved the problem that Jim G. and anorexis had? i have this problem too… and tried both combinations too :-(

    1. I’m stuck myself. I’m a total newbie at this and have not been able to resolve the Serial.flush() issue with Arduino 1.0

        1. I have solved the Flush problem by adding “delay(50)” after “int val = Serial.read()- ‘0’;” and replacing flush with “while(Serial.available()>0) Serial.read();”.

          But I was still very curious about the reason, would you please explain this.

          Many thanks.

  6. For those with the Serial.flush() -> while Serial.read() problem, try adding “Delay(30);” after every digitalwrite, the first while loop, and the Serial.read() loop. That may fix your problem.

  7. Hi, great videos, thanks. Question how did you get the com box you are typing into which displays the results?
    Thanks,
    Steve

  8. hi Jeremy, you was great things. i have a question for you, if i buy this card, can i connect with matlab.
    can we define glabal varriable on this program, and then we can chance other platform this varriable. also matlab is use for guide applications right?

  9. Hi Jez,
    thanks for the tutorials,
    did anyone solve the Serial.flush(); not working?
    Bob.

  10. answer Serial.flush() has changed in Arduino 1.0. You can use the following instead:
    while(Serial.available()>0) Serial.read();

  11. The processing shows me en error on the line –
    port = new Serial(this, “COM3”, 9600);
    the error :
    error inside Serial.()

    And I did everythis right , please help me

  12. could help me with a 3-axis accelerometer + -1.5/6g MMA7361L is that I find no tutorials or information on how to connect, let alone program it arduino please

  13. could help me with a 3-axis accelerometer + -1.5/6g MMA7361L is that I find no tutorials or information on how to connect, let alone program it arduino please

  14. I got the same problem as everybody else. According to the Arduino website, Serial.read reads in the first ‘byte’ of data. So if you input 124, it will first read in 1, then continue with the program. So the 1 should turn on the LED. However, the 2 and 4 don’t get flushed. I think the reason is because the baud rate is much slower than the arduino clock speed. So 2 and 4 are not yet available to be flushed after reading the 1 (so the program loops back to the beginning). If you add a delay(10) before trying to flush the bits, then the Serial communication has enough time to load all of the bytes into the buffer so it can be flushed (btw, I’m assuming there’s a buffer here). In this case 1 will be read, and 2 and 4 will be flushed. However, 124 is supposed to give an invalid input. I found that this can be wored out if you use Serial.parseInt().

  15. I am trying to implement a DAQ using Arduino, so i require higher data transfer speeds. I found out that the Arduino has a maximum baud rate of 115200. Is there any other way to get much higher speeds??

    1. Hi, I have the same problem as you do. Did you find out any good solution for it? It would be really nice if you can post it up here!!!

  16. I have two questions here!!
    1. How does Arduino connect to the processing ? I mean we just write these two programs(one in Arduino, one in Processing), and we run the program in Progressing and it is all done?

    2. You mention in the video that we can use other programming languange to ”link “ to Arduino, right? Then how about Java, if I want to use Java to link to Arduino, how can I do, almost the same with the progressing?

    1. They are talking over serial. So, if you are running both programs, and the arduino is connected to the right serial port, then they will talk.

      You can use java as long as you can find a Java library that allows you to access a serial port.

  17. After enough struggle I managed to sort my flush problem. Notice that after the delay we flush.

    void loop() {
    while(Serial.available() == 0);
    int data = Serial.read()-‘0’;
    int pos = map(data, 0, 7, 0, 180);
    pos = constrain(pos, 0, 180);

    delay(20);
    while(Serial.available()>0) Serial.read();
    Serial.println(data);
    Serial.println(pos);
    S.write(pos);
    }

  18. Hey Jeremy,

    I wanted to input words, have them read and then have them spit back out. Here is my program but when I try to verify it it says “invalid conversion from int to char*”

    char* Input = “” ;

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

    }

    void loop()
    {
    while(Serial.available() == 0) ;
    Input = Serial.read() ;
    Serial.println(Input) ;
    }

    Thanks!

  19. I want to see my graph with line.. not point.. how to do that.. ? my sensor is a accelerometer.. can you help me.. ?

    import processing.serial.*;
    import cc.arduino.*;

    int[] xvals; // Definición de array para almacenar el canal X
    int[] yvals; // Definición de array para almacenar el canal Y
    int[] zvals; // Definición de array para almacenar Z
    int xval; // Valor leído en el canal X
    int yval; // Valor leído en el canal Y
    int zval; // Valor leído en Z
    int arrayindex = 0;

    Arduino arduino;
    int xpin=0; // Designación del PIN para X
    int ypin=1; // Designación del PIN para Y
    int zpin=2; // Designación del PIN para Z
    void setup() // Configuración
    {
    size(500,720); //Tamaño de ventana
    xvals = new int[width];
    yvals = new int[width];
    zvals = new int[width];
    arduino = new Arduino(this,Arduino.list()[1],57600);

    }

    void draw()
    {
    background(0);

    // desplaza la posición del array un lugar a la izquierda
    for(int i=1; i<width; i++)
    {
    xvals[i-1] = xvals[i];
    yvals[i-1] = yvals[i];
    zvals[i-1] = zvals[i];
    }
    // añade el nuevo valor al final del array
    // lee el valor de la entrada (0..1024), divide por 4 (0..255)
    // para mantenerse dentro de límites lienzo de dibujo
    xval = arduino.analogRead(xpin);
    xvals[width-1] = xval/4;
    yval = arduino.analogRead(ypin);
    yvals[width-1] = yval/4;
    zval = arduino.analogRead(zpin);
    zvals[width-1] = zval/4;
    // dibuja el array
    for(int i=1; i<width; i++) {
    stroke(255);
    point(i, 255-xvals[i]); //flip y coordinate so 0 is at bottom
    point(i, 512-yvals[i]); //flip y coordinate so 0 is at bottom
    point(i, 712-zvals[i]); // DUDA!!!!!!
    }
    textAlign(LEFT);
    text("X: "+xval, 200, 30);
    text(5.0*(xvals[width-1]/255.0)+"V",200,60);
    text("Y: "+yval, 200, 256+30);
    text(5.0*(yvals[width-1]/255.0)+"V",200,256+60);
    text("Z: "+zval, 200, 510+30);
    text(5.0*(zvals[width-1]/255.0)+"V",200,510+60);
    }

  20. Hey Jeremy,

    I keep ketting this error message in processing, do you maybe know whats wrong?
    This line is marked: port = new Serial(this, “/dev/tty.usbmodem1a21”, 9600);

    I’m using the code from your tutorial.

    The error message:
    java_home: unrecognized option `–request’
    java.lang.UnsatisfiedLinkError: /Library/Java/Extensions/librxtxSerial.jnilib: no suitable image found. Did find: /Library/Java/Extensions/librxtxSerial.jnilib: no matching architecture in universal wrapper thrown while loading gnu.io.RXTXCommDriver
    Exception in thread “Animation Thread” java.lang.UnsatisfiedLinkError: /Library/Java/Extensions/librxtxSerial.jnilib: no suitable image found. Did find: /Library/Java/Extensions/librxtxSerial.jnilib: no matching architecture in universal wrapper
    at java.lang.ClassLoader$NativeLibrary.load(Native Method)
    at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1827)
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1716)
    at java.lang.Runtime.loadLibrary0(Runtime.java:823)
    at java.lang.System.loadLibrary(System.java:1045)
    at gnu.io.CommPortIdentifier.(CommPortIdentifier.java:83)
    at processing.serial.Serial.(Serial.java:170)
    at processing.serial.Serial.(Serial.java:116)
    at sketch_121025b.setup(sketch_121025b.java:30)
    at processing.core.PApplet.handleDraw(PApplet.java:2103)
    at processing.core.PGraphicsJava2D.requestDraw(PGraphicsJava2D.java:190)
    at processing.core.PApplet.run(PApplet.java:2006)
    at java.lang.Thread.run(Thread.java:680)

    thanks

  21. Hi Jeremy,
    I have an array of values that I am sending from Arduino via serial.
    Problem is I don’t know how to read them in Processing.

    Can you help me out with that please? Here you can see the Arduino code:

    // They’re used here to
    // set pin numbers:
    int buttonPins[] = {
    2,4,7,8,12} ; // the number of the pushbutton pin

    int buttonStates[5]; // variable for reading the pushbutton status
    int i;
    void setup() {
    for (i=0; i<5; i++){
    pinMode(buttonPins[i], INPUT);
    }
    Serial.begin(9600);
    }

    void loop(){
    for (int i=0; i<5; i++){
    // read the state of the pushbutton value:
    buttonStates[i] = digitalRead(buttonPins[i]);

    // check if the pushbutton is pressed.
    // if it is, the buttonState is HIGH:
    if (buttonStates[i] == HIGH) {
    Serial.print("ON");
    Serial.println(buttonPins[i]);
    Serial.print ("VAL");
    Serial.println (buttonStates[i]);
    Serial.write (buttonStates[i]);
    }
    else {
    Serial.print("OFF");
    Serial.println(buttonPins[i]);
    Serial.print ("VAL");
    Serial.println (buttonStates[i]);
    Serial.write (buttonStates[i]);
    }

    }
    delay(15000);
    }

  22. I want to activate a 5×5 matrix led using Arduino and I also open serial to monitoring the output. The output in serial monitor was exactly what I wanted. However, the output shown on the matrix led was a little different. When I keep the serial open, the led flickered a little bit. And there is a very tiny light spot shown which was not my intention. Then when I turned off the serial, it didn’t flickering anymore but that tiny spot became completely lightened.

    I look forward to see your reply.

    Thanks ahead.

  23. many many many ……thanxxxx to my friend for video tutorial 6 about Serial port and prodessing.

    it really works . god bless u.

  24. great job…. im kinda new to this audrino thing.. I and working on building a 737 home cocpit and was wondering how i can get this card to interface with fsuipc or microsoft fsx. example. can it be used liek this….. if i turn on a toggle switch can it write the data to fsx and also light up an led at the same time? thanks

  25. Thanks for doing these video tutorials!

    Your method(s) for relaying the information in my opinion is spot on!
    These really help explain the foundation of arduino process.
    By far the best video tutorials i have seen!

  26. hi…can you help me how to send msg using gsm-gprs shield please forward the program needed….tnx

  27. Hi Jerry, thanks for great videos. May I have your opinions about how to have a localization system for several modular robots with servos controlled by arduino uno???

    1. That depends on where you are using the robots… You could use GPS, overhead localization with cameras and AR tags, sonar localization, dead reckoning…

  28. Great work on the Tutorials there Jeremy, it is great just to sit back and pick up on something I might not of fully understood, Currently I have a project for myself and you might be able to show me the way, I need to send a special character the key via serial TTL I am having a hard time finding out first if it can be done, second how would I send the character, are you able to help as this is the last piece of the puzzle.
    Cheets paul

  29. Another way to solve the issue with a 1 being 49 is is by changing int to char. This also works with letters as well and all characters I think

  30. Hi,
    I am trying matlab to turn the led light in arduino, I was wondering if anyone knew the data type of the serial information sent by the serial monitor to the arduino.

    So far I have the following code in matlab

    clear;
    s=serial(‘com3′);
    fopen(s);
    try
    fwrite(s,’1’, ‘uint8’);
    %a= fscan(s);
    fclose(s);
    catch err
    fclose(s);
    disp(‘dint work’)
    end

    I know that arduino is receiving some signal from matlab , but not able to understand it !!!

    any help , would be appreciated

    thanks

  31. Hi Jeremy
    Thanks For your tutorial. I want to control a robot by serial communication. According to your tutorial I have to use “enter” button for sending each data in serial monitor.But I want to controlled the robot in such away that when I press a button the robot should be in motion & when I release the button it should be stop.
    Is there any solution for this, then please help me.

  32. Thank you for the great tutorial. I would like to somehow make this same thing happen, where the light turns on and off, based on cell within an Excel Spreadsheet. Is that possible?

  33. Hi Jeremy,
    I really love your Arduino tutorials. I just picked up my Arduino, and I am learning a lot through your tutorials. I downloaded the Processing software, and used the code that you posted on this website, but comes up with an error that says serial is only available in 32 bit version. I downloaded 64 bit because I have a 64 bit computer. What should I do?

  34. I have two questions. If I need to input more then one integer from mat lab to the Arduino code is there a way to do that in one line ex. (20,260,10) and if I have to do it line by line how would I code the Arduino to read this info. Also is there a way I can have the Arduino read an email or text?

  35. I am new to all this and have just downloaded the arduino software. Do i need to download anything else or will the code run straight off that.

  36. Thanks a lot for your great tutorials! They really put things in perspective. I don’t suppose you’re planning on, making some new ones on how to interface, through Pure Data..?
    But if you do have any information on where to start, I would love to hear. I’m trying to interact with a rgb led, and have three sliders which each represents the value 0-255 for pwm values sent in bytes. How would I through serial.parseInt designate each value to their ledpin?

  37. Thank you Steven, the solution provided by you worked, but I too am wondering what the 50ms delay does to make this work. Is it that the 9600 baud rate is too slow for the micro controller to receive the complete input from the serial port when multiple chars are input?

    Below is the code that I used in loop function, in case it helps anyone.

    void loop()
    {
    //Wait for input data
    while(Serial.available() == 0);
    int val = Serial.read() – ‘0’;
    delay(50);

    //Check value read from serial port
    if (val == 1)
    {
    Serial.println(“Led is on”);
    digitalWrite(ledPin, HIGH);
    }
    else if(val == 0)
    {
    Serial.println(“Led is off”);
    digitalWrite(ledPin, LOW);
    }
    else
    {
    Serial.println(“Invalid value received!!!”);
    }
    //Read any extra chars from the serial input to avoid multiple invalid value output!!!
    while(Serial.available() > 0) Serial.read();
    }

  38. Hi Jeremy, I’m having a problem in my application with Matlab Gui -Arduino serial communication. I want to receive data from Arduino when a optical encoder sends me a 1 or a 0 and send it to Matlab Gui, but I don’t know where and how to write my code in order to make my Gui check all the time the state of my digital inputs (4).
    And I have another question, is it possible to send from Arduino to Matlab Gui an array mixed of numbers and text? I don’t know how to write the code for that either in Matlab.
    Please help me, right now I’m using a toggle button_callback to write my code of detecting the state of my inputs in it, but it only detects one time at the begining.

    function EXECUTE_Callback(hObject, eventdata, handles)
    % hObject handle to EJECUTA (see GCBO)
    % eventdata reserved – to be defined in a future version of MATLAB
    % handles structure with handles and user data (see GUIDATA)

    % Hint: get(hObject,’Value’) returns toggle state of EJECUTA

    delete(instrfind({‘Port’},{‘COM3’}))
    global c fec psc fem aam
    %%COMUNICATION ARDUINO UNO
    c=arduino(‘COM3′);

    %INPUTS FOR THE ARRAY

    c.pinMode(2,’input’);
    c.pinMode(3,’input’);

    %Sensors
    %FEC
    c.pinMode(4,’input’);
    %PSC
    c.pinMode(5,’input’);
    %FEM
    c.pinMode(6,’input’);
    %ABADM
    c.pinMode(7,’input’);

    %p%Led
    c.pinMode(13,’output’);

    %%check state of sensors
    fec=0;
    psc=0;
    fem=0;
    aam=0;

    fec=c.digitalRead(4); %%sensor1
    psc=c.digitalRead(5); %% sensor2
    fem=c.digitalRead(6); %%sensor3
    aam=c.digitalRead(7); % sensor4

    handles.c=c;

    if fec==1
    c.digitalWrite(13,1); % ledpin13 high
    Popup_6;
    else
    c.digitalWrite(13,0); % ledpin13 low
    end

    if psc==1
    c.digitalWrite(13,1);
    Popup_6;
    else
    c.digitalWrite(13,0);
    end
    if fem==1
    c.digitalWrite(13,1);
    Popup_6;
    else
    c.digitalWrite(13,0);
    end
    if aam==1
    c.digitalWrite(13,1);
    Popup_6;
    else
    c.digitalWrite(13,0);
    end

Leave a Reply to Smashed Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Advertisement