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:
#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

 void loop()
 analogValue = analogRead(analogPin);                 // read the analog input (value between 0 and 1023)
 else if(analogValue>=511)
 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.

Pages: 1 [2]   Go Up
Jump to: