Sunday, December 20, 2009

last saturday[12XII] exercises

this time no schemes! just explanation what and where. you schould be able to find all the necessary info int the net. check fritzing examples as well.
only thing you need to do is to load a servo library in the beginning of all four codes below
you go to sketch/import library/servo.

piezo triggers servo movement 004

//servo attached to pin 2 + piezo on analog pin 0 [needs amplifier, check here]
//load servo library!

Servo myServo;
const int threshold=200;//how hard do you need to knock?
int piezoRead;

void setup(){
myServo.attach(2);
}

void loop(){

piezoRead=analogRead(0);

if (piezoRead>threshold){//if the signal from piezo is strong enough, then...

for (int i=0; i<180;i+=1){ //turn the servo
myServo.write(i);
delay(10);
}

myServo.write(0);//and go back
delay(500);

}
}

servo and photocell 003

//hook up a servo to pin2 and a photocell[stabilize it with resistor] to analog pin 0
//load servo library!

Servo myServo;
int photoCellValue;
int mappedValue;

void setup(){
myServo.attach(2);
}

void loop(){

photoCellValue=analogRead(0);//reads value from the photocell
mappedValue=map(photoCellValue,0,1024,1,180);//check in the help, very usefull

myServo.write(mappedValue);
delay(5);

}

different speeds servo 002

//similar as below, only little change introduced in the loop
//load servo library!

Servo myServo;

void setup(){
myServo.attach(2);
}

void loop(){

for (int i=0; i<180;i+=1){ //repeats commands inbetween braces 180 times
myServo.write(i);//angle is a variable now
delay(10);
}

myServo.write(0);//go back
delay(500);
}

simple servo control codes [last saturday] 001

//for this code you'll need a servo conected to PIN2

//remember to load a library for servo control!

Servo myServo;//creates servo object to play with

void setup(){
myServo.attach(2);//defines where the servo is attached
}

void loop(){//repeats that:

myServo.write(0);//turns the servo to its 0 positioon
delay(500);//waits 500 ms
myServo.write(180);//turns the servo 180 degrees
delay(500);//waits again
}