Week 14

Serial Communication

Processing and Arduino can send and recieve messages on the usb connection, this allows us to use them together in on project. Last week we looked at using the arduino to read a digital input pin connected to a switch. The Input Pullup Resistor example monitors pin 2, and sends '0's and '1's on the serial connection to communicate the pin’s state.

This example code shows how to listen for '0's and '1's in processing, and updates a variable called buttonPressed that the program uses to change what is drawn based on wether you switch is open or closed.

// DigitalReadSerial
// Reads 0s and 1s from the serial connection and updates the boolean variabled 'buttonPressed' accordingly.


// include the serial library
import processing.serial.*;

//declare a variable to store our serial port
Serial myPort;    


void setup() {
  size(400, 400);
  println(Serial.list());

  //connect
  String portName = Serial.list()[0];
  myPort = new Serial(this, portName, 9600);
}

void draw() {
  background(0);
  if (buttonPressed) {
    fill(0, 255, 0);
  }
  else {
    fill(255, 0, 0);
  }
  rect(100, 100, 200, 200);
}


// declare a variable to hold the button state sent by the arduino
boolean buttonPressed = false;

// listen to messages from the arduino
void serialEvent(Serial myPort) {
  char in = myPort.readChar();
  if (in == '1') {
    buttonPressed = false;
  }
  else if (in == '0') {
    buttonPressed = true;
  }
  else {
    //unknown message
  }
}

Leave a Reply