OLDPFA:007 – Arduino + Processing

Inspiration

Arduino + Processing

In order to use Arduino together with Processing, we need to send and receive data via the serial port. You can make up your own protocol or use some readymade ones. The one we are going to use is called Firmata.

Firmata

Firmata code comes with the Arduino examples. It handles all the commands to receive or send data between the Arduino board and various other software (Processing, Pure Data etc.)

How to use it:

  1. Upload the StandardFirmata code to your Arduino. (File–>Example–>Firmata–>StandardFirmata)
  2. After you have uploaded the code, you can close the Arduino IDE
  3. In Processing, install the Arduino (Firmata) library using the Contribution Manager (Sketch–>Import Library–>Add Library). Search for Arduino and you should see it appear.)

A Basic Example

How to open the connection and turn on an LED connected to pin 9.

screen-shot-2016-10-20-at-14-23-30

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

Arduino myArduino;

void setup(){
  size(500,500);
  // Print a list all the serial ports available on your computer
  printArray(Arduino.list());
  // Insert the index number of your Arduino serial port
  // inside the Arduino.list[X] to open the connection
  myArduino = new Arduino(this, Arduino.list()[0], 57600);
  myArduino.pinMode(9,Arduino.OUTPUT);
  background(0);
}

void draw(){
  // Turn the LED on
  myArduino.digitalWrite(9,Arduino.HIGH);
}

Reading Sensors

screen-shot-2016-10-20-at-14-23-30

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

Arduino myArduino;
float b = 0;
float lightVal = 0;
float bgColor = 0;

void setup(){
  size(500,500);
  printArray(Arduino.list());
  myArduino = new Arduino(this, Arduino.list()[2], 57600);
  myArduino.pinMode(9,Arduino.OUTPUT);
  background(0);
}

void draw(){
  lightVal = myArduino.analogRead(0);
  bgColor = map(lightVal,200,800,0,255);
 
  b = map(mouseX,0,width,0,255);
  myArduino.analogWrite(9,int(b));
  
  background(bgColor);
  textSize(50);
  text(lightVal,100,100);
  text(int(b),mouseX,mouseY);
}