Hi, for the past few days I've been trying to create a small project with my arduino. I want to use a servo controlled by a LDR (those resistance that change value by the amount of light). I want the servo to be at 150 degrees when there's no light or just a little light and then switch to 120 degrees when there's plenty of light.
I've based my setup on the servo controlled by a potentiometer in the tutorial section. The code of the example is the following:
// Controlling a servo position using a potentiometer (variable resistor)
// by Michal Rinott <http://people.interaction-ivrea.it/m.rinott>
#include <Servo.h>
Servo myservo; // create servo object to control a servo
int potpin = 0; // analog pin used to connect the potentiometer
int val; // variable to read the value from the analog pin
void setup()
{
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop()
{
val = analogRead(potpin); // reads the value of the potentiometer (value between 0 and 1023)
val = map(val, 0, 1023, 0, 179); // scale it to use it with the servo (value between 0 and 180)
myservo.write(val); // sets the servo position according to the scaled value
delay(15); // waits for the servo to get there
}
I've taken a few example on many sites and I've produced a buggy code that doesn't do what I want:
#include <SoftwareServo.h>
SoftwareServo myservo; // create servo object to control a servo
int potPin = 0; // analog pin used to connect the LDR
int ledPin = 13; //Blinking led
int limit = 800; //Threshold limit if the LDR output a value between 0 and 1023
void setup()
{
myservo.attach(2); // attaches the servo on pin 2 to the servo object
pinMode(ledPin, OUTPUT);
pinMode(potPin, INPUT);
}
void loop()
{
int val = analogRead(potPin); // read the value of the LDR and store it into val
if (val < limit) {
myservo.write(150); //write 150 degrees to the servo if val is smaller than 800
} else if (val >= limit) {
digitalWrite(ledPin, HIGH);
delay(1000);
digitalWrite(ledPin, LOW);
delay(1000);
digitalWrite(ledPin, HIGH);
delay(1000);
digitalWrite(ledPin, LOW);
delay(1000);
myservo.write(120); //If val is bigger than 800 blink led 2 times and switch servo to 120 degrees
}
delay(3000); // waits 3 seconds before restarting
SoftwareServo::refresh(); //Don't know why it's here but I was told it had to be
}
When I upload it the servo start from 0 degrees and increment of about 20 degrees its rotation every 3 seconds...
What am I doing wrong...