Saturday, June 25, 2011

Arduino UNO: PhotoCell - sensing light

In this tutorial, we will send the analog readings obtained from a Photo Resistor, also known as a Light Dependent Resistor (LDR), to the computer. We will display the each reading on the monitor using a simple Processing sketch.


Here is what you will need to complete the Arduino side of the project:

Parts Required:

  • PhotoCell (or PhotoResistor)
  • 10K resistor
  • Breadboard
  • Arduino UNO
  • 3-4 wires(to connect it all together)
  • USB cable to upload sketch and for Serial communication with Processing.


Fritzing sketch:



Arduino Sketch


 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

/* ==========================================================
Project : Send Photo resistor values to computer
Author: ScottC
Created: 25th June 2011
Description: This sketch will make the arduino read Photo resistor
             values on analog pin A0. The analog readings will
             be dependent on the amount of light reaching the
             sensor. The Analog readings will be sent to the
             computer via the USB cable using Serial communication.
==============================================================
*/

int photoRPin = 0;
int minLight; //Used to calibrate the readings
int maxLight; //Used to calibrate the readings
int lightLevel;
int adjustedLightLevel;

void setup() {
 Serial.begin(9600);
 
 //Setup the starting light level limits
 lightLevel=analogRead(photoRPin);
 minLight=lightLevel-20;
 maxLight=lightLevel;
}

void loop(){
 //auto-adjust the minimum and maximum limits in real time
 lightLevel=analogRead(photoRPin);
 if(minLight>lightLevel){
 minLight=lightLevel;
 }
 if(maxLight<lightLevel){
 maxLight=lightLevel;
 }
 
 //Adjust the light level to produce a result between 0 and 100.
 adjustedLightLevel = map(lightLevel, minLight, maxLight, 0, 100);
 
 //Send the adjusted Light level result to Serial port (processing)
 Serial.println(adjustedLightLevel);
 
 //slow down the transmission for effective Serial communication.
 delay(50);
}

Arduino Sketch Explanation:

Serial.begin(9600) : starts the serial communication between the Arduino and Processing
lightLevel=analogRead(photoRPin): take a reading from the analog pin 0.
minLight and maxLight: automatically adjust the minimum and maximum range of the sensor
adjustedLightLevel: used to map the reading from the PhotoCell to a value between 0-100.

The adjustment of the light level is not necessary, and could be handled in Processing instead.
The delay(50) at the end of the sketch, is only used to slow down the transmission of the Serial messages to Processing. Depending on what you want to do with the sensor data, you may wish to increase or decrease the amount of delay.



 Processing Sketch

Here is a very basic Processing Sketch that will allow you to receive data from the Serial port attached to the Arduino and display the reading on your computer screen. In my case, the Arduino is connected to COM13. You may need to change this if you decide to follow in my footsteps.

The processing sketch will look for the line feed character ' \n' coming from COM13, which will trigger a serialEvent(). You can get processing to look for another character if you want to: just change the character within the bufferUntil() command. The draw() method is made redundant because the screen updating is handled by the serialEvent() in response to serial data communication with the Arduino UNO.

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

/* ============================================================
Processing Version: 2.2.1
Project: Display Sensor data on computer screen
Author:  ScottC
Created: 25th June 2011
Description: This Processing sketch will allow you to display
             sensor data received from the Arduino via the
             serial COM port (or USB cable).
=============================================================== */
import processing.serial.*;
Serial myPort;
String sensorReading="";
PFont font;


void setup() {
  size(400,200);
  myPort = new Serial(this, "COM13", 9600);
  myPort.bufferUntil('\n');
  font = createFont(PFont.list()[2],32);
  textFont(font);
}

void draw() {
  //The serialEvent controls the display
}  

void serialEvent (Serial myPort){
 sensorReading = myPort.readStringUntil('\n');
  if(sensorReading != null){
    sensorReading=trim(sensorReading);
  }

  writeText("Sensor Reading: " + sensorReading);
}


void writeText(String textToWrite){
  background(255);
  fill(0);
  text(textToWrite, width/20, height/2);
}

This is how the data will be displayed on the computer screen:

If this tutorial helped you, please support me here:





Displaying Serial data from an Arduino UNO on your computer screen - using Processing

Here is a very basic Processing Sketch that will allow you to receive data from the Serial port attached to the Arduino and display the reading on your computer screen. In my case, the Arduino is connected to COM13. You may need to change this if you decide to follow in my footsteps.


You will need to setup an Arduino sketch to send serial data to the computer using a Serial.println(value) command. The processing sketch will look for the line feed character ' \n' coming from COM13, which will trigger a serialEvent(). You can get processing to look for another character if you want to: just change the character within the bufferUntil() command.
The draw() method is made redundant because the screen updating is handled by the serialEvent() in response to serial data communication with the Arduino UNO



Here is the Processing sketch code:

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import processing.serial.*;
Serial myPort;
String sensorReading="";
PFont font;


void setup() {
size(400,200);
myPort = new Serial(this, "COM13", 9600);
myPort.bufferUntil('\n');
font = createFont(PFont.list()[2],32);
textFont(font);
}

void draw() {
//The serialEvent controls the display
}

void serialEvent (Serial myPort){
sensorReading = myPort.readStringUntil('\n');
if(sensorReading != null){
sensorReading=trim(sensorReading);
}

writeText("Sensor Reading: " + sensorReading);
}


void writeText(String textToWrite){
background(255);
fill(0);
text(textToWrite, width/20, height/2);
}
This was formatted using this site.

If you want an Arduino project that goes well with this code, see this post.





Thursday, June 23, 2011

Reading a text or CSV file using the Processing language

In a previous post, I showed you how to export data to a text file. Now I will show you how to import it back into your Processing program. This will come in handy later on.

This is what my data looks like in the text file:

There are many ways to import text from a text file, and there are many ways to store the data within your code after you have imported it. Feel free to make mention of your method in the comments, however, this one definitely works, and is doing what I want it to do.

I have decided to store each line within an ArrayList.
The first column is stored in another ArrayList by splitting the data into bits using splitTokens.
Most of the file reading code was taken from this Java site, and seems to work quite fine with the Processing programming language. I have taken bits and pieces of code from various places, and added my own flavour.

Here is a snippet of the data after import.


You can see that I have separated the two ArrayLists using dots "....."



Processing Code:
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58

/*==========================================================
Project: Read data from Text file into Processing
Author: ScottC
Created: 23rd Jun 2011 (Updated 26th Aug 2014)
Description: Use processing to read a text file and populate an ArrayList.
             The ArrayList is then printed to the debug window.
             
Processing version tested: 2.2.1
References: This was made possible using bits and pieces from these sites
         http://www.kodejava.org/examples/28.html
         http://processing.org/reference/ArrayList.html
         http://processing.org/reference/splitTokens_.html
         
===========================================================  */
import java.io.FileReader;
import java.io.FileNotFoundException;

ArrayList sensorData;
ArrayList columnOne;

void setup(){
  sensorData=new ArrayList();
  columnOne=new ArrayList();
  readData("C:/SensorData/mySensorData.txt");
}

void readData(String myFileName){
  
  File file=new File(myFileName);
  BufferedReader br=null;
  
  try{
    br=new BufferedReader(new FileReader(file));
    String text=null;
    
    while((text=br.readLine())!=null){
      String [] subtext = splitTokens(text,",");
      columnOne.add(int(subtext[0]));
      sensorData.add(text);
    }
  }catch(FileNotFoundException e){
    e.printStackTrace();
  }catch(IOException e){
    e.printStackTrace();
  }finally{
    try {
      if (br != null){
        br.close();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  for (int i=0; i<sensorData.size()-1; i++){
    print(columnOne.get(i) + ".....");
    println(sensorData.get(i));
  }
}

 Processing Code Explained


void setup(): this creates 2 new ArrayLists to hold the data, and then calls the readData function. The readData() function needs the name of the file that you want to analyse, eg. C:/mySensorData.txt


br=new BufferedReader(new FileReader(file));
This just sets up the file that you will be reading, which then allows you to use a "while-loop" to read one line at a time using br.readLine().


String [] subtext = splitTokens(text,",");
This splits each line into bits, using a "," as a separator, and puts it into the subtext array.


columnOne.add(int(subtext[0]));
This shows how you can extract the first number or column from each line.
If you wanted the second number or column, you would use subtext[1] instead.


sensorData.add(text);
This shows how you can extract the ENTIRE line.


  }catch(FileNotFoundException e){
    e.printStackTrace();
  }catch(IOException e){
    e.printStackTrace();

This is just error handling related to file reading.


br.close();
This closes the file.


for (int i=0; i<sensorData.size()-1; i++){
    print(columnOne.get(i) + ".....");
    println(sensorData.get(i));
  }

This just prints the data to your screen so that you can see if the whole process has been successful.




Update : If you want to read values from a text file and then send these values to the Arduino - read this blog entry.









Sunday, June 19, 2011

Colour Sensing - Update Two

This colour sensing project is starting to get bigger than I wanted it to. However, I am learning a lot about the Arduino/Processing as I look for ways to accomplish my tasks. When you see my final code, I will have a bit of explaining to do.

I now have a relatively quick method of detecting MegaBlok colours, and will probably use a PhotoCell to improve read rates under different lighting conditions. Once I have done this, I would like to get the Arduino to do something in response to the colour. But let me get over step one.

Thursday, June 16, 2011

How to append text to a txt file using Processing

Sometimes it would be useful to have a function to save data to a text file.
I plan to save some of my Arduino sensor data to a text file using the Processing language.
Ninety percent of the following code comes from this forum posting. Thank goodness for the internet, and for people like PhiLho and Cedric. I modified their code and ended up with this (to suit my own project):

Processing Sketch

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

/* =====================================================================
     Project : Append data to a text file
      Author : ScottC
     Created : 16 Nov 2011  (Updated 26 Aug 2014)
 Description : Use the Processing language to store data on
               the computer. This code can be used to create a
               new text file or append to an existing file.
               
Processing Version tested : 2.2.1
Reference: http://processing.org/discourse/yabb2/YaBB.pl?num=1251025598/4

=============================================================================== */

import java.io.BufferedWriter;
import java.io.FileWriter;

void setup(){
   String myFileName = "C:/SensorData/mySensorData.txt";
   String mySensorData = "10,20,30,40,50";
   
   //To insert data into a new file
   //saveData(myFileName, mySensorData, false);
   
   //To append data to an existing file
   saveData(myFileName, mySensorData, true);
}

void draw(){
}

/* --------------------------------------------------------------
  SaveData:
  - This code is used to create/append data to a designated file.
  - fileName = the location of the output data file (String)  
  - newData = the data to be stored in the file (String)
  - appendData = true if you want to append
               = false if you want to create a new file
  --------------------------------------------------------------*/
void saveData(String fileName, String newData, boolean appendData){
  BufferedWriter bw = null;
  try {
    FileWriter fw = new FileWriter(fileName, appendData);
    bw = new BufferedWriter(fw);
    bw.write(newData + System.getProperty("line.separator"));
  } catch (IOException e) {
  } finally {
    if (bw != null){
      try {
        bw.close();
      } catch (IOException e) {}
    }
  }
}
 
 

This will append the sensor data of  10,20,30,40,50 to the end of mySensorData.txt file.
If I wanted to create a new text file instead, then I would call saveData in the following way:
saveData(myFileName, mySensorData, false);

If you found this code useful, please support me here:  
 



Sunday, June 12, 2011

Colour Sensing - Update One

I successfully modified the previous sketch to detect the colour of the Mega Blok that was over the sensors. However, it was taking up to 10-20 seconds to reveal the answer.

The problem I am experiencing is mainly due to the effect of ambient light levels. Just when I get all my limits set up, something changes, and I lose the ability to identify one of the Bloks.

I get the feeling that I may have over-complicated the design or the method to detect the Blok colour, and am now trying to simplify and speed up the process.

Once again, I think I may be able to get faster results using a PhotoCell, but I don't want to differentiate by light level alone. I would like to read colour using one or more LEDs as a Sensor.

I think I need to utilise the RGB LED functionality a little bit more. So instead of white light, I might scan with different colours.

Stay tuned.

If you have any ideas, please make suggestions in the comments.

Saturday, June 11, 2011

Colour Sensing - Intro

Now that I have different patterns for the different coloured Mega Bloks, I will try to get processing to "Identify" or tell me which Blok is which. I am essentially trying to make a DIY colour sensor.
I know that if I get the RGB LED to produce different coloured light (rather than just white), I will be able to get more information/patterns from my Red and Yellow LED sensors, however, I think I have enough information from the white light to tell the difference between the Red, the yellow and the green Mega Bloks.

We'll see how we go. Stay tuned.

For more information about what project I referring to - jump to this Blog Posting:
Arduino UNO: LED Sensor Part Two

Arduino UNO: LED Sensor, Part Two




Building on the last project, I am now using a Red and a Yellow LED as a Sensor to detect light coming from an RGB LED.

Putting different coloured Mega Bloks over the LEDs has different effects on the Sensors as the RGB LED gets brighter and brighter.

I used the Processing Language to control the brightness of the RGB LED through a Serial command, and then use the resulting Sensor readings from the Yellow and the Red LEDs to create a chart or plot.

Here are the results of my experiment.

Red Mega Blok




Yellow Mega Blok



Green Mega Blok













When the displayed bars are RED, it indicates that the Red LED is absorbing MORE light than the Yellow LED (and vice versa). Hence this is a "Difference Chart".
The Green Mega Blok absorbs more Red Light than the other blocks, therefore producing a big difference between Red LED sensor readings and Yellow Sensor readings.

Here is the list of components required to perform this experiment
All parts hardware parts except for the wires and the Mega Bloks
can be found in the Sparkfun Inventors Kit.

Here is the Sketch: (created in Fritzing):

































Here is the Arduino Code:

arduino code RedYellow Sensor with RGB LED

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
//Define the pins for the Red LED Sensor
#define Red_LED_Sensor_POS 4
#define Red_LED_Sensor_NEG 5

//Define the pins for the Yellow LED Sensor
#define Yellow_LED_Sensor_POS 7
#define Yellow_LED_Sensor_NEG 8

//Define the pin for the RGB LED torch
#define RGB_LED_RedPin 9
#define RGB_LED_GreenPin 10
#define RGB_LED_BluePin 11
int intensity=0;


//Define the maximum cycles/time allowed for each LED to capture light
long max_darkness=80000;


void setup(){
//Setup the RED LED Sensor
pinMode(Red_LED_Sensor_POS,OUTPUT);
digitalWrite(Red_LED_Sensor_POS,LOW);

//Setup the YELLOW LED Sensor
pinMode(Yellow_LED_Sensor_POS,OUTPUT);
digitalWrite(Yellow_LED_Sensor_POS,LOW);

//No need to setup the RGB LED Pins

//Turn on Serial Protocol
Serial.begin(9600);
}

void loop()
{

byte byteRead;
// check if data has been sent from the computer:
if (Serial.available()) {
// read the most recent byte (which will be from 0 to 255):
byteRead = Serial.read();
// set the brightness of the LED:
analogWrite(RGB_LED_RedPin, byteRead);
analogWrite(RGB_LED_GreenPin, byteRead);
analogWrite(RGB_LED_BluePin, byteRead);

//Read the amount of Yellow light
read_LED('Y', Yellow_LED_Sensor_NEG);

//Read the amount of Red light
read_LED('R', Red_LED_Sensor_NEG);
}
}

void read_LED(char LED_Colour, int LED_Pin){

// Charge the LED by applying voltage in the opposite direction
pinMode(LED_Pin,OUTPUT);
digitalWrite(LED_Pin,HIGH);

//Read the amount of Light coming into the LED sensor
long darkness=0;
int lightLevel=0;
pinMode(LED_Pin,INPUT);
digitalWrite(LED_Pin,LOW);

while((digitalRead(LED_Pin)!=0) && darkness < max_darkness){
darkness++;
}

lightLevel=((max_darkness-darkness)+1)/80;

//Print the LED colour
Serial.println(LED_Colour);
//Print the light level
Serial.println(lightLevel);
}




Here is the Processing Code:

processing code Read Serial Chart and Write Serial

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/* Processing code for this example */

// Graphing sketch

//This sketch was written by ScottC, but was adapted from a sketch
//written by Tom Igoe in 2005

// This example code is in the public domain.

import processing.serial.*;

Serial myPort; // The serial port
int xPos = 1; // horizontal position of the graph
float YellowVal=0; // The variable to hold the Yellow Sensor Reading
float RedVal=0; // The variable to hold the Red Sensor Reading
float Diff=0; // The variable to hold the difference between the readings
int Switcher=0; // Used to control the flow of the program

void setup () {
// set the window size:
size(1020, 750);

// List all the available serial ports
println(Serial.list());
// I use COM13 for my Serial Port - you will need to change this to suit your system
myPort = new Serial(this, "COM13", 9600);
// don't generate a serialEvent() unless you get a newline character:
myPort.bufferUntil('\\n');
// set inital background:
background(0);
//Send a value to the Arduino to start the feedback mechanism
myPort.write(0);
}
void draw () {
// everything happens in the serialEvent()
}

void serialEvent (Serial myPort) {
// get the ASCII string:
String inString = myPort.readStringUntil('\\n');

if (inString != null) {
// trim off any whitespace:
inString = trim(inString);

//The arduino sends 2 sensor readings. The following code
//helps to identify which reading is which.
if(inString.equals("Y")){
Switcher=0;
} else if (inString.equals("R")){
Switcher=1;
} else {

//Convert the String to a float
float inByte = float(inString);
//Map the reading, so that the chart fits within the window.
inByte = map(inByte, 0, 1000, 0, height);

if(Switcher==0){
//Save the reading from the yellow sensor to YellowVal
YellowVal=inByte;
} else {
//Save the reading from the red sensor to RedVal
RedVal=inByte;
//Calculate the difference between the readings
Diff=RedVal-YellowVal;

//If the yellow sensor is greater, plot with a yellow line
//If the red sensor reading is greater, plot a red line.
if(Diff<=0){
stroke(255,255,0);
Diff=abs(Diff);
} else {
stroke(255,0,0);
}
// draw the line:
line(xPos, height, xPos, height - Diff);

// at the edge of the screen, go back to the beginning:
if (xPos > width) {
xPos = 0;
background(0);
//Send a value to the Arduino to change the intensity
//of the RGB LED and take another reading
myPort.write(xPos);
} else {
// increment the horizontal position: Increment by more
// to get less readings and to make it quicker
xPos+=4;
if (xPos>0){
//Send a value to the Arduino to change the intensity
//of the RGB LED and take another reading
myPort.write(xPos/4);
} else {
myPort.write(xPos);
}
}
}
}
}
}

Wednesday, June 8, 2011

Arduino UNO: LED Sensor, Part One

As seen in the previous blog postings, the LED (Light Emitting Diode) was used to DISPLAY the result of various sensors. It was also used to create a variety of Light patterns or sequences.

The LED is commonly used as an OUTPUT device, however, I have since found out: there is another option.

You can use the LED as an INPUT device !!



I have only tried this with a Yellow LED and a Red LED, however, this should work with any colour. Some sites recommend using a clear/transparent/colourless LED for best effect, but it depends on what you are trying to achieve.

The LED responds better to light of the same wavelength that it emits. So a yellow LED responds better to yellow light, and a red LED responds better to Red light.

The following experiment attempts to prove this theory.
A Red and Yellow LED alternate and fade in to maximum brightness using PWM (Analog Output). Meanwhile, a separate LED is used as an INPUT device to receive the light. The value obtained is plotted using a processing sketch.

The chart above used a Yellow LED to measure the light emitted from a Red and then a Yellow LED.
As the Yellow LED gets brighter, the INPUT LED takes less time to discharge, and thus produces a lower result. On the other hand, the Red LED has little effect on the INPUT LED, despite it's brightness.
Ambient light will produce different graph patterns.

Parts Required:
  • Arduino UNO
  • 2 x Yellow LEDs
  • 1 x Red LED
  • 3 x 330 ohm Resistors (choose resistors suitable for your LEDs)
  • 5 wires to connect the circuit
  • Breadboard
  • Processing software
Here is the Sketch:

     Created with Fritzing : http://fritzing.org/


Here is the Arduino Code: which was adapted from this site.
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#define LED_Sensor_NEG 8
#define LED_Sensor_POS 7
#define Yellow_LED 10
#define Red_LED 9

int switcher=0;
int lightLevelY=0;
int lightLevelR=0;

void setup(){
pinMode(LED_Sensor_POS,OUTPUT);
digitalWrite(LED_Sensor_POS,LOW);
pinMode(Yellow_LED,OUTPUT);
pinMode(Red_LED,OUTPUT);

//Turn on Serial Protocol
Serial.begin(9600);
}

void loop()
{

//Alternate the flashing of the Yellow and Red LED
if(switcher==0){
lightLevelR+=4;
if(lightLevelR>255){
lightLevelR=0;
switcher=1;
}
} else {
lightLevelY+=3;
if(lightLevelY>255){
lightLevelY=0;
switcher=0;
}
}
analogWrite(Red_LED,lightLevelR);
analogWrite(Yellow_LED,lightLevelY);


// Charge the LED by applying voltage in the opposite direction
pinMode(LED_Sensor_NEG,OUTPUT);
digitalWrite(LED_Sensor_NEG,HIGH);

// Set pin 8 to read the input and Turn off the internal pull up resistor.
// The greater the amount of light in the room, the smaller the number represented by variable "darkness".
long darkness=0;
int outputVal=0;
pinMode(LED_Sensor_NEG,INPUT);
digitalWrite(LED_Sensor_NEG,LOW);
while((digitalRead(LED_Sensor_NEG)!=0) && darkness<80000){
darkness++;
}

outputVal=darkness/80;
//Print the darkness level in the room.
Serial.println(outputVal);
}

Here is the Processing Code:     Code Source
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/* Processing code for this example */

// Graphing sketch


// This program takes ASCII-encoded strings
// from the serial port at 9600 baud and graphs them. It expects values in the
// range 0 to 1023, followed by a newline, or newline and carriage return
// Created 20 Apr 2005
// Updated 18 Jan 2008
// by Tom Igoe
// This example code is in the public domain.

import processing.serial.*;

Serial myPort; // The serial port
int xPos = 1; // horizontal position of the graph

void setup () {
// set the window size:
size(400, 300);

// List all the available serial ports
println(Serial.list());
// I know that the second port in the serial list on my PC
// is always my Arduino, so I open Serial.list()[1].
// Open whatever port is the one you're using.
myPort = new Serial(this, Serial.list()[1], 9600);
// don't generate a serialEvent() unless you get a newline character:
myPort.bufferUntil('\n');
// set inital background:
background(0);
}
void draw () {
// everything happens in the serialEvent()
}

void serialEvent (Serial myPort) {
// get the ASCII string:
String inString = myPort.readStringUntil('\n');

if (inString != null) {
// trim off any whitespace:
inString = trim(inString);
// convert to a float and map to the screen height:
float inByte = float(inString);
inByte = map(inByte, 0, 1023, 0, height);

// draw the line:
stroke(127,34,255);
line(xPos, height, xPos, height - inByte);

// at the edge of the screen, go back to the beginning:
if (xPos >= width) {
xPos = 0;
background(0);
}
else {
// increment the horizontal position:
xPos++;
}
}
}