Go Down

Topic: Problems gradualy triggering a servo with sensor values (Read 136 times) previous topic - next topic

OliverR

Firstable, this is my first topic in this page so hi to everyone and sorry for any mistake I could make.

This is the point: I am trying to control the rotation of a servo elice with the values that a photoresist shows in the computer (for example making it rotate 180 degrees when the photoresist show a 1023 value, and stay still in 0 degrees when the value is 0).

 What I do not know is how to make a relation between the intermediate values of the photoresist and the degrees between 0 and 180 that the elice can rotate. The only thing I think that could work would be to use an if-else declaration for every value, but I fear it would sturate the Arduino memory even using an Arduino Mega, nd it would take to me too much time too so, have you got any idea?

By the way, this is what I have for now:

#include <Servo.h>

Servo myservo;

const int sensorpin=A0;

int sensorvalue=0;
int proximityvalue=0;

 
void setup() {
 Serial.begin(9600);
 myservo.attach(2);
 myservo.writeMicroseconds(600);
}

void loop() {
 proximityvalue=analogRead(sensorpin);
 delay(5);
 
 myservo.write(0);

 if(proximityvalue<200)
 {
  myservo.write(180);
  delay(600);
 }
 else
 {
  myservo.write(0);
  delay(600);
 }
 Serial.println(proximityvalue);
}

Grumpy_Mike

Look up the map function on the Arduino's referance Page.

groundFungus

Since a photo resistor must be part of a voltage divider the range of output values will not be 0-1023.  The actual range depends on how the voltage divider is wired and the resistance values.

johnwasser

Using map() would look something like this:
Code: [Select]
#include <Servo.h>


Servo MyServo;


const byte SensorPin = A0;
const byte ServoPin = 2;


void setup() {
  Serial.begin(9600);
  MyServo.attach(ServoPin);
}


void loop() {
  int proximityValue = analogRead(SensorPin);
  MyServo.writeMicroseconds(map(proximityValue, 0, 1023, 1000, 2000));
  Serial.println(proximityValue);
}



Note that map() does linear interpolation.  For piecewise linear approximating a curve there is a third-party function called multiMap():


https://playground.arduino.cc/Main/MultiMap


Send Bitcoin tips to: 1G2qoGwMRXx8az71DVP1E81jShxtbSh5Hp

wvmarle

Indeed map, or a simple mathematical formula.

LDRs are most commonly used to tell dark from bright - to see if the lid of a box is open, or to see when it's time to open/close a chicken coop door based on daylight levels. They're dirt cheap but not exactly accurate.

If you want any decent accuracy, get a proper light intensity sensor like the TEMT6000 (best for indoor, can't handle sunlight brightness) or TSL2591 (much greater range). Both output absolute lux values.
Quality of answers is related to the quality of questions. Good questions will get good answers. Useless answers are a sign of a poor question.

Go Up