Servo Motors
In our example we controlled the servo motro with the potentiometer. You can also try to use the light sensor instead of the pot.
#include <Servo.h> Servo motor; int pos = 0; int potVal = 0; void setup() { // put your setup code here, to run once: motor.attach(10); Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: potVal = analogRead(A0); //potVal will be between 0-1023 //pos should be between 0-180 pos = map(potVal,0,1023,0,180); Serial.println(pos); motor.write(pos); }
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.
Arduino + Processing
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:
- Upload the StandardFirmata code to your Arduino. (File–>Example–>Firmata–>StandardFirmata)
- After you have uploaded the code, you can close the Arduino IDE
- 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.
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
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); }