Arduino and Processing serial interaction

This is more of a reminder for me, when trying to turn Arduino inputs into something that is usable by Processing (a nice language to visualise data quickly, which is also what Arduino IDE is based on). The following Arduino code, reads input from an Light Dependent Resistor and sends the value out via the serial port. In addition to this it also sends outs the following characters “B”, “4″ and “L”.

More after the jump (if you’re really interested).


// Arduino code: Light sensitive LED + processing test

int val; // to grab the value of the LDR

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

void loop()
{
    val = analogRead(2);

    Serial.println(val);

    // This is just to prove to myself that the ascii conversion works
    Serial.print("B");
    Serial.print("4");
    Serial.println("L");

    delay(500); // to avoid overloading serial port
}

On the other side of the serial connection we use Processing to read the values, parsing out ASCII values 10 and 13 which are new line and carriage return (presumedly caused by Arduino’s println) and then displays the ASCII character representation. The main item to note is the typecasting of the int into a char, which is basically the ASCII conversion.


// print out values that the arduino sends via serial

import processing.serial.*; 

Serial port;
int inByte;

void setup()
{
  // Uncomment to list all the available serial ports, use this to work out which port to use
  //println(Serial.list());

  // Open the port that the Arduino board is connected to (in this case #0)
  // Make sure to open the port at the same speed Arduino is using (9600bps)
  port = new Serial(this, Serial.list()[0], 9600);
} 

void draw()
{
  while (port.available() > 0)
  {
    inByte = port.read();
    // 10 = new line and 13 = carriage return
    if (inByte != 13 || inByte != 10)
    {
      print(char(inByte));
    } else {
      println(".");
    }
  }
}

For completeness sake, I’ve also included sample output.


Stable Library
=========================================
Native lib Version = RXTX-2.1-7
Java lib Version   = RXTX-2.1-7
567
B4L
563
B4L
563
B4L
567
B4L
561
B4L
567
B4L
563
B4L
568
B4L
Experimental:  JNI_OnLoad called.


About this entry