JeremyBlum.com

v3.1

Tutorial 6 for Arduino: Serial Comm and Processing

| 198 Comments

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.

 

198 Comments

  1. 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
    þC
    c.pinMode(4,’input’);
    %PSC
    c.pinMode(5,’input’);
    þM
    c.pinMode(6,’input’);
    «ADM
    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

  2. I just got a Arduino uno and I tried this tutorial and It recives the right data but also adds -38 to the end every time.

  3. Acording to a ascii table its a 10. Wich is a new line feed but turns to -38 when I -0

  4. Will this tutorial work with processing 2?

  5. Pingback: Tutorial 11 for Arduino: SD Cards and Datalogging | JeremyBlum.com

  6. On Processing 2 the function readStringUntil(char) has not been included yet in the serial library, therefore you must replace the function readStringUntil(‘\n’) with readString().

    I’m using Com6 and the screen resolution is 1366,768, therefore on my Win8 64b the code is:

    import processing.serial.*;
    Serial port;
    float brightness = 0;

    void setup()
    {
    size(1366,768);
    port = new Serial(this, “COM6″, 9600);
    port.bufferUntil(‘\n’);
    }

    void draw()
    {
    background(0,0,brightness);
    }

    void serialEvent (Serial port)
    {
    brightness = float(port.readString());
    }

  7. I am trying to follow a tutorial from mad science (link posted below) but cannot get the Processing 2 to work as it indicates ‘Cannot find anything named ‘Serial’”, I’ve been all over and researched for days. I am trying to get this project done for my Physics class. Can you help/point me in the right direction?

    This is what I have in Processing 2:

    void setup() {
    // initialize the serial communication:
    Serial.begin(9600);
    }

    void loop() {
    // send the value of analog input 0:
    Serial.println(analogRead(A0));
    // wait a bit for the analog-to-digital converter
    // to stabilize after the last reading:
    delay(2);
    }

    http://mad-science.wonderhowto.com/how-to/diy-polygraph-machine-detect-lies-with-tin-foil-wire-and-arduino-0134599/

  8. Pingback: First Arduino Encounter | // drafts

  9. why he Serial.flush(); is not working anymore? How can i clean the buffer?
    Thx.

    • Read the post – I explained this above.

    • Hi here is the answer to Serial.Flush() not working:

      int ledPin = 11;

      void setup()
      {

      Serial.begin(9600);
      pinMode(ledPin,OUTPUT);
      }

      void loop()
      {

      // Make Sure this line is included
      // Have the Ardunio wait to receive input

      while(Serial.available() == 0) {
      delay(500);
      }

      // Read the input

      int val = Serial.read() – ’0′;

      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”);

      }

      // Serial.flush(); ( Failed )

      // Make Sure this line is included

      while(Serial.available() > 0)
      {
      Serial.read();
      }

      }

  10. Serial.flush(); AND while(Serial.available()>0) Serial.read(); doesn’t flush out serial buffer on my Arduino Mega. Any advice?

  11. I struggled with the Serial.flush() alternative as well. I finally figured it out by putting a small delay in the initial while() statement. Without the delay it would never clear out the incoming buffer in the second while loop. Here is my sample code:

    void loop()
    {
    while(Serial.available() == 0) { delay(500); }

    int val = Serial.read() – ’0′;

    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!!”);
    }

    while(Serial.available() > 0) {
    Serial.read();
    }
    }

    • Hello Kyle, your solution worked, it was spotted, all other examples were either confusing or did not work, you just need to put comments explaining the Serial.available statement, the reason for the Delaying to 500 and the Serial.read().

      When I saw this problem on Jeremy Blum YouTube Channel, I knock my head against the wall and refused to go forward until i found a solution, it took almost an hour before I found the message board, it was worth it.

      Thank ***

    • Thank you SO MUCH!

    • Finally, someone with a working solution!

  12. Hey jeremy i bought your book before the break to learn more about the arduino and im happy to say im very pleased with it so far!

  13. hello jeremy, first of all thank you for all of your videos.
    i think you explain them very well, and i enjoy to learn from you.
    good job!!

    i want to ask you some questions and i will be more than happy if you reply to me:

    1. i want the arduino uno board read some data from text file in my computer
    for example: i want the arduino read the date 23.1253 from text file.
    how can i do that?
    which cables i need – usb only or rs232?
    whether need i use ttl converter voltage?

    2. i want to send the data 23.1253 from matlab , to the arduino uno board.
    how can i do that?
    which cables i need?
    whether need i use ttl converter voltage?

    thanks a lot!

  14. Hi Jeremy, I’ve been meddling around with an arduino for a couple of weeks now and I’ve been looking for interesting ways to have it interact with processing. Until now all I had was the same data leaving the arduino entering processing’s console and not really doing much. This tutorial has helped me out so much. Thanks and keep up the good work.

  15. Hi
    when i write the first code when i write numbers it returns me except the number i except , one more number..

    for example when i push 1 it returns me 49 an 13

    What’s wrong?

    Check out my print screen

    http://prntscr.com/30rrfq

    thank’s

  16. change “new line” to “no line ending” right-bottom on the serial monitor

    • reply for this comment

      matt:
      Acording to a ascii table its a 10. Wich is a new line feed but turns to -38 when I -0

  17. Pingback: Arduino新手教程(6)USB串口通信和Processing语言 | 观澜小站

  18. Hye Jeremy Blum,
    I have problem with the connection between arduino and Matlab GUI.
    I need take data from Arduino to sent to Matlab GUI.
    How I need to write the program?
    May you show to me the basic of procedure to do that?
    Really appreciate your helps.
    Thank you.

  19. Hey! i am making a project with kinect + processing + arduino.
    I got some data from kinect onto processing. Now i want to send this data to arduino. Can you kindly help me out ?
    I have no idea about it so a small clue will also be helpfull :)

  20. Hey! i am making a project with kinect + processing + arduino.
    I got some data from kinect onto processing. Now i want to send this data to arduino. Can you kindly help me out ?
    I have no idea about it so a small clue will also be helpfull :)
    or atleast share your own code for help . Thanks

  21. Hi Jeremy!

    Great video!, i am doing something similar getting data from a airflow sensor to processing, but i found that there is a lag of 5 seconds in the data between arduino and processing. That is a big problem, do you know how to avoid it?

    Thanks!

  22. Hey Jeremy, i am trying to have a serial connection with arduino Leonardo for sending data via pc to arduino.
    I use linux and i am using LIbSerial, but as i try to run my program i have no reply from arduino.
    I would be glad if you could help me cause i need it for my university final project.

    Thanks a lot
    Marios

    This is my arduino code:

    const int Relay1=12;
    const int Relay2=11;
    int bytesRead;
    char incoming[11];

    void setup(){
    Serial.begin(9600);
    pinMode(Relay1,OUTPUT);
    pinMode(Relay2,OUTPUT);
    digitalWrite(Relay2,LOW);
    digitalWrite(Relay1,LOW);
    }

    void loop(){
    int matchFlag = 0;
    int end1;

    if(Serial.available()>0){
    bytesRead = Serial.readBytesUntil(‘\n’, incoming, 10);
    incoming[bytesRead] = ”; // Add null terminator…
    if (strcmp(incoming, “lights”) == 0){
    Serial.println(“Lights matched”);
    matchFlag = 1;
    digitalWrite(Relay1, HIGH);
    end1=Serial.write(“end”);
    }
    if (strcmp(incoming, “voltage”) == 0){
    Serial.println(“Voltage matched”);
    matchFlag = 1;
    digitalWrite(Relay2, HIGH);
    end1=Serial.write(“end”);
    }

    if (strcmp(incoming, “end”) == 0){
    Serial.println(“End matched”);
    matchFlag = 1;
    digitalWrite(Relay2,LOW);
    delay(3000);
    digitalWrite(Relay1,LOW);
    end1=Serial.write(“end”);
    }
    if (matchFlag == 0){
    Serial.println(“error”);
    end1=Serial.write(“end”);
    }
    }
    }

    And this is my pc code:

    #include
    #include
    #include
    #include
    #include
    #include
    #include

    using namespace std;
    using namespace LibSerial;

    int main(){

    char end[4] = { 0 };
    int reply;
    int f=0;
    SerialStream arduino;
    arduino.Open(“/dev/ttyS0″);
    arduino.SetBaudRate(SerialStreamBuf::BAUD_9600);
    arduino.SetCharSize(SerialStreamBuf::CHAR_SIZE_8);
    arduino.SetNumOfStopBits(1);
    arduino.SetFlowControl(SerialStreamBuf::FLOW_CONTROL_NONE);
    arduino.SetVTime(1);
    arduino.SetVMin(100);
    if(!arduino.good()){
    f=1;
    arduino.Open(“/dev/ttyS1″);
    arduino.SetBaudRate(SerialStreamBuf::BAUD_9600);
    arduino.SetCharSize(SerialStreamBuf::CHAR_SIZE_8);
    arduino.SetNumOfStopBits(1);
    arduino.SetFlowControl(SerialStreamBuf::FLOW_CONTROL_NONE);
    arduino.SetVTime(1);
    arduino.SetVMin(100);
    }
    if(!arduino.good()){
    cout<<"Arduino not connected \n";

    }
    if(f==0){
    cout<<"Arduino connected in /dev/ttyS0 port \n"<<"with: \n"<<"Baudrate:9600 \n";

    }
    if(f==1){
    cout<<"Arduino connected in /dev/ttyS1 port \n"<<"with: \n"<<"Baudrate:9600 \n";

    }

    arduino<<"lights"<<std::endl;
    cout<<"is here? \n";
    while(strcmp(end,"end")!=0){
    arduino.read(end,4);
    cout<<"is here? \n";
    }
    cout<<"is here? \n";
    arduino.Close();
    return 0;

    }

Leave a Reply

Required fields are marked *.