Servo problems

Hello,

i cant get my servo to run. When i take the section of code out of my program and just upload that, it runs just fine. However when i run the actually program, the LEDs blink just fine and my if statements works.

i am powering the servo externally because i knew that was an issue.

Now im just stuck :frowning:

thanks in advance!!

#include <Servo.h>

Servo servo;

const int MaxNum = 3;      // number times beam can be tripped
const int LEDPIN = 6;      // Red LED
const int LEDPIN2 = 8;     // Green LED
const int SENSORPIN = 4;   // Servo Pin
const int RTime = 150;     // delay time for Red LED
const int GTime = 150;     // delay time for Green LED
const int Stime = 500;     // delay time for Servo
const int Angle = 80;      // max angle Servo moves

int sensorState = 0;       // variable for reading the pushbutton status

void setup() {
  servo.attach(2);
  pinMode(LEDPIN2, OUTPUT);
  pinMode(LEDPIN, OUTPUT);
  pinMode(SENSORPIN, INPUT);
  digitalWrite(SENSORPIN, HIGH);
}

int count = 0;
void loop() {
  sensorState = digitalRead(SENSORPIN); // check if the sensor beam is broken
  if (count < MaxNum) {
    digitalWrite(LEDPIN2, HIGH);
    if (sensorState == LOW) { //when beam is broken
      for (int x = 0; x <= 5; x ++) { // loop for LED.
        digitalWrite(LEDPIN2, HIGH);
        delay(GTime);
        digitalWrite(LEDPIN2, LOW);
        delay(GTime);
      }
      // runs Servo motor.
      for (int pos = 55; pos < Angle; pos++) {
        servo.write(pos);
      }
      for (int pos = Angle; pos > 55; pos--) {
        servo.write(pos);
      }
      count++;
    }
    else { // if beam is detected
      servo.write(55);
    }
  } else if (count == MaxNum) { // if the max count has been reached
    digitalWrite(LEDPIN, HIGH);

  }
}

Show us your wiring diagram. Hand drawn is OK.
You mentioned a version of the code where the servo works. Can we see that?
And the code you have already posted does not work, right? Just to confirm, the 'not works' is that the servo never moves at all, right?

I see several chunks of code that I would do differently, but I will wait for better info so I am not guessing.

      for (int pos = 55; pos < Angle; pos++)
      {
        servo.write(pos);
      }
      for (int pos = Angle; pos > 55; pos--)
      {
        servo.write(pos);
      }

These 2 for loops will happen so fast that the servo will not get a chance to move

i put a delay between the loops and it runs perfectly now!!! thanks!!!!!!!

WhiteT:
i put a delay between the loops and it runs perfectly now!!! thanks!!!!!!!

Do you mean between the loops or between the steps in the loops ?

If the former then why use for loops ? All you need to do is to write the destination value to the servo.