Pages: 1 [2]   Go Down
Author Topic: How to move a servo with an analog input  (Read 1621 times)
0 Members and 1 Guest are viewing this topic.
New Jersey
Offline Offline
Faraday Member
**
Karma: 70
Posts: 3727
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Here is a simpler version of your code, with the looping issue removed:
Code:
#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.
Logged

Pages: 1 [2]   Go Up
Jump to: