Tutorial: Drawing using a sensor

Getting a sensor to create an image in Processing:

In Arduino write this code (for a sensor on pin 0):

int sensorPin = 0;
void setup() 
{
Serial.begin(9600);
pinMode(sensorPin, INPUT); //my sensor will send data in to the Arduino
}
void loop()
{
int volt = analogRead(sensorPin); //read the data
//Serial.println(num); //find out what the number range is

int num = map(volt, 0, 75, 0, 800);
//remap the numbers so they result in ones you can use


Serial.write(num); //write the sensor data so Processing can capture it
delay(100);
}

In Processing:

import processing.serial.*;
Serial myPort; // Create object from Serial class
String val; // used for data received from the serial port
float Pos = 0; //used in drawing
void setup() {
String portName = Serial.list()[2];
//change the 0 to a 1 or 2 etc. to match your port

myPort = new Serial(this, portName, 9600);
  size(800, 600); //create a window to draw in
background(0); //set the background color (black)
}
void serialEvent (Serial myPort) {
//a new function that looks for Serial events
int sensorData = myPort.read(); // get the sensor data
//println(sensorData); // print it so we can see it
Pos = sensorData; //use the sensor data to draw a line (later)
}
void draw() {
line(0, Pos, 800, Pos); //draw a line x1, y1, x2, y2
stroke(random(255), 0, Pos); //change the color of the stroke randomly
line(Pos, 0, Pos*3, 600);
stroke(Pos, 0, Pos);
}

 Diagram:Photoresistor.png

Resources

Processing Info on Line() Links to an external site.

The attributes that work with Line are:

strokeWeight() Links to an external site.
strokeJoin() Links to an external site.
strokeCap() Links to an external site.
beginShape() Links to an external site.