Go Down

Topic: How to move a servo with an analog input (Read 2117 times) previous topic - next topic

wildbill

Here is a simpler version of your code, with the looping issue removed:
Code: [Select]

#include "Servo.h"  // include the servo library

Servo servo1;       // creates an instance of the servo object to control a servo
int posServo1 = 0;
int analogPin = A0;      // the analog pin that the sensor is on
int analogValue = 0;    // the value returned from the analog sensor
int servoPin = 4;       // Control pin for servo motor

void setup()
{
servo1.attach(servoPin);  // attaches the servo on pin 4 to the servo object
Serial.begin(9600);
servo1.write(45);
delay(2000);
}

void loop()
{
analogValue = analogRead(analogPin);                 // read the analog input (value between 0 and 1023)
Serial.println(analogValue);
if(analogValue==0)
   {
   posServo1=0;
   }
else if(analogValue>=511)
   {
   posServo1+=1;
   }
else
   {
   posServo1-=1;
   }
posServo1=constrain(posServo1,0,180); 
servo1.write(posServo1);     // write the new mapped analog value to set the position of the servo
delay(50);                   // waits for the servo to get there
}


I'm still not entirely clear what the requirement is, But this version should move the Servo to 45 and delay a little, just to prove that the servo does move. Then it continuously reads the analog pin. If it's zero, servo goes to position 0. If it's >= 511 servo position is incremented, otherwise decremented. The constrain statement keeps the position between 0 and 180.

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy