Examples > Communication

To Computer

A simple example of communication from the Arduino board to the computer: the value of an analog input is printed. We call this "serial" communication because the connection appears to both the Arduino and the computer as an old-fashioned serial port, even though it may actually use a USB cable.

You can use the Arduino serial monitor to view the sent data, or it can be read by Processing (see code below), Flash, PD, Max/MSP, etc.


An analog input connected to analog input pin 0.


void setup()

void loop()

Processing Code

// Analog In 
// by <a href="http://itp.jtnimoy.com">Josh Nimoy</a>. 

// Reads a value from the serial port and sets the background color. 

// Created 8 February 2003. 
// Updated 2 April 2005
// Modified 25 March 2007 by David A. Mellis.

import processing.serial.*;

String buff = "";
int val = 0;
int NEWLINE = 10;

Serial port;

void setup()
  size(200, 200);

  // Print a list in case COM1 doesn't work out
  println("Available serial ports:");

  // Uses the first port in this list (number 0).  Change this to
  // select the port corresponding to your Arduino board.  The last
  // parameter (e.g. 9600) is the speed of the communication.  It
  // has to correspond to the value passed to Serial.begin() in your
  // Arduino sketch.
  port = new Serial(this, Serial.list()[0], 9600);  

  // If you know the name of the port used by the Arduino board, you
  // can specify it directly like this.
  //port = new Serial(this, "COM1", 9600);

void draw()
  while (port.available() > 0) {

void serialEvent(int serial) 
  // If the variable "serial" is not equal to the value for 
  // a new line, add the value to the variable "buff". If the 
  // value "serial" is equal to the value for a new line,
  //  save the value of the buffer into the variable "val".
  if(serial != NEWLINE) { 
    buff += char(serial);
  } else {
    // The end of each line is marked by two characters, a carriage
    // return and a newline.  We're here because we've gotten a newline,
    // but we still need to strip off the carriage return.
    buff = buff.substring(0, buff.length()-1);
    // Parse the String into an integer
    val = Integer.parseInt(buff)/4;
    // Clear the value of "buff"
    buff = "";