2

I want to be able to make a (continuous motion) servo motor rotate a lens/filter/polariser and have it be fed an intensity value in real time and then stop once it reaches a minimum, then doing it again and again.

I have got it to stop when the intensity is at a minimum but I can't seem to take it to the next step. I need it to wait (or delay) by a small time, check the intensity as to whether it truly is below the threshold or not. If it isn't then I want it to rotate slowly back until it is at a minimum, wait and then repeat but in the opposite direction.

#include<Servo.h>

Servo myServo;

const int resistPin = A0;
const int servPin = 9;
int intenState = analogRead(resistPin);

void setup() {
    Serial.begin(9600);
    pinMode(servPin, OUTPUT);
    pinMode(resistPin, INPUT);
    myServo.attach(9);
}

void loop(){

    if(analogRead(A0) > 500){
        myServo.write(120);
    }else if(analogRead(A0) <= 500){
        myServo.write(94);
    }
}

This is the code I currently have to stop the servo, but, due to the need for accuracy and the slight delay there is between reading the intensity of the light and then transmitting a command to the servo motor, I need it to be able to re-check the value and then readjust accordingly until it is as accurate as possible. (Obviously I understand the intensity value will change based on random noise/fluctuations and this is why the minimum intensity will be <= than a straight up ==).

1 Answers1

1

Ok, I understand. In Arduino you can use the Delay command to make it wait. And take an average of say 5 values before making a move. Reference: https://www.arduino.cc/en/Reference/Delay Example : delay(1000) //1 second delay

#include<Servo.h>

Servo myServo;

const int resistPin = A0;
const int servPin = 9;
int intenState = analogRead(resistPin);
int xa=0;

void setup()
{
    Serial.begin(9600);
    pinMode(servPin, OUTPUT);
    pinMode(resistPin, INPUT);
    myServo.attach(9);
}

void loop()
{
  for (int i=0;i<5;i++)
  {
     xa+=analogRead(A0);
     delay(1000);
  }

  xa=xa/3;  //averaging the 3 collected values at 1 seconde delay each.
  //now its time to compare.

  if(xa > 500)
  {
        myServo.write(120);
  }

  else if(xa <= 500)
  {
        myServo.write(94);
  }

}