Description:
I basically change the speed for a bounce ball using the Photocell. If there is no force then the speed is zero, I can increase the speed of the ball by pressing the Photocell. For this project I also add a speaker output coincidence with the speed of the ball. Therefore, when the speed of the ball is high, the speaker frequency is lower as we increase the delay. The LED is just the indicator that the system working properly.
Materials:
Arduino
Photocell
Blue LED
Speaker
Arduino Code:
int potPin = 0;
int val = 0;
int valSpeed = 0;
int speakerPin = 7;
void setup() // run once, when the sketch starts
{
pinMode(speakerPin, OUTPUT);
Serial.begin(9600);
}
void loop() // run over and over again
{
digitalWrite(speakerPin, LOW);
val = analogRead(potPin);
valSpeed = map(val, 1, 1022, 0, 20);
Serial.println(valSpeed);
for( int i=0; i<500; i++ ) { // play it for 50 cycles
digitalWrite(speakerPin, HIGH);
delayMicroseconds(val);
digitalWrite(speakerPin, LOW);
delayMicroseconds(val);
}
}
Processing Code:
import processing.serial.*;
// Change this to the portname your Arduino board
String portname = "COM3"; // or "COM5"
Serial port;
String buf="";
int cr = 13; // ASCII return == 13
int lf = 10; // ASCII linefeed == 10
int size = 60; // Width of the shape
float xpos, ypos; // Starting position of shape
int xspeed = 0; // Speed of the shape
int yspeed = 0; // Speed of the shape
int xdirection = 1; // Left or Right
int ydirection = 1; // Top to Bottom
void setup()
{
size(400, 600);
noStroke();
frameRate(30);
smooth();
// Set the starting position of the shape
xpos = width/2;
ypos = height/2;
port = new Serial(this, portname, 9600);
}
void draw()
{
background(102);
// Update the position of the shape
xpos = xpos + ( xspeed * xdirection );
ypos = ypos + ( yspeed * ydirection );
// Test to see if the shape exceeds the boundaries of the screen
// If it does, reverse its direction by multiplying by -1
if (xpos > width-size || xpos < 0) {
xdirection *= -1;
}
if (ypos > height-size || ypos < 0) {
ydirection *= -1;
}
// Draw the shape
ellipse(xpos+size/2, ypos+size/2, size, size);
}
void serialEvent(Serial p) {
int c = port.read();
if (c != lf && c != cr) {
buf += char(c);
}
if (c == lf) {
int val = int(buf);
println("val="+val);
xspeed = val;
yspeed = val;
buf = "";
}
}