Using Servo.h with millis SIMPLE code

Hi,

Having looked at different example codes and tried to simplify this "complicated" codes for my project i could get it to run the way i need it to run.

Need a simple code to use with servo.h and millis to get a servo to go to position 100 and when a criteria is met go back to position 0.

Tried to use the ROBIN's multiple task example code and strip it down to the basics i need.
But i could not get it to move the right way for me.

The right way is: from position 0 to 100. and that when a criteria is met back to 0.

There should me a "simple" way to call millis in the looop() after setting a position.

Need i simple code like this but without delay

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

void setup() {
  myservo.attach(13);  // attaches the servo on pin 9 to the servo object
}

void loop() {
if (critearia == met)
{
    myservo.write(0);              // tell servo to go to position in variable 'pos'
    delay(500); 
}

   if (other criteria == met)
   {
    myservo.write(100);              // tell servo to go to position in variable 'pos'
    delay(500);// waits 15ms for the servo to reach the position
   }
}

Thank for the help!

Why don't you just take the delay() calls out of your code above? What if anything goes wrong if you don't have them?

Something like this pseudo code perhaps

moving = false

start of loop()
current time = millis()
  if criteria A are met and moving is false
    moving = true
    stepsize = 1
    pos = 0
    start time = millis()
  end if

  if criteria B are met and moving is false
    moving = true
    stepsize = -1
    pos = 100
    start time = millis()
  end if

  if moving = true
    if current time - startTime > period  //time for another move
      write pos to servo
      pos = pos + stepsize
      start time = current time
      if pos <= 0 or pos >= 100
        moving = false
      end if
    end if
  end if
end of loop()

Tnx for the help! i really need it :confused:

i have been testing your pseudo code but i think i have found an other problem.

While using servo.h a clean skatch everything goes fine.

But when i implement it in to my "real" skatch the servo moves wildly few steps forward and back.
I think by adding another library to the real skatch the librarys interfear with each other.

So i found this manually servo control code but uses delays again.
And i know a little bit of implementing millis but with this i can't seem to get it working.

Manual servo control :

// Manual servo control 
// Copyright 2012 by Zipwhip. 
// You are free to use and modify this code in your own software.

#define SERVO_PIN         39  // Any pin on the Arduino or Mega will work.

void setup()
{
  pinMode(SERVO_PIN, OUTPUT);

}

int lenMicroSecondsOfPeriod = 20 * 1000; // 20 milliseconds (ms)
int lenMicroSecondsOfPulse = 1.8 * 1000; // 1.0 ms is 0 degrees

void loop()
{

 // Servos work by sending a 20 ms pulse.  
 // 1.0 ms at the start of the pulse will turn the servo to the 0 degree position
 // 1.5 ms at the start of the pulse will turn the servo to the 90 degree position 
 // 2.0 ms at the start of the pulse will turn the servo to the 180 degree position 
 // Turn voltage high to start the period and pulse
 digitalWrite(SERVO_PIN, HIGH);

 // Delay for the length of the pulse
 delayMicroseconds(lenMicroSecondsOfPulse);

 // Turn the voltage low for the remainder of the pulse
 digitalWrite(SERVO_PIN, LOW);

 // Delay this loop for the remainder of the period so we don't
 // send the next signal too soon or too late
 delayMicroseconds(lenMicroSecondsOfPeriod - lenMicroSecondsOfPulse); 

}

"Real" code: (had to delete last part of the code due to 9000 characters..

//DRV8825 VREF voltage NEMA 17= 0,65V can be 0.8V
//DRV8825 VREF voltage NEMA 23= 0,6AV can be 0.6V

//NEOPIXELS
#include <Adafruit_NeoPixel.h>
#define PIN            A5
// How many NeoPixels are attached to the Arduino?
#define NUMPIXELS      8
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
int delayval = 200; // delay for half a second

#include <AccelStepper.h>
//NEMA 17 (Actuator)
AccelStepper stepperA(AccelStepper::DRIVER, 3, 4);     // (DRIVER, Step, Directon)
int enableA = 2;

//NEMA 23 (Linear motion)
AccelStepper stepperL(AccelStepper::DRIVER, 7, 8);     // (DRIVER, Step, Directon)
int enableL = 11;
//_____________________________________________________________
unsigned long currentMillis;
unsigned long endFirstRunMillis;
const long interval = 2000;
enum motorStateENUM {
  WAITING,
  FIRSTRUN,
  BETWEENRUNS,
  SECONDRUN,
  SECONDRUNDONE,
  THIRDRUN,
  FINISHED,
};
motorStateENUM motorState = WAITING;

//_______________________________________________________________
//LDR
const int ledPinLDR = 6;
const int crashPin1 = A0;
int crashPin1State;
boolean crashButtonPressed = false;

//ACTUATOR
const int homePinA = 10;
int homePin2StateA;


//STARTBUTTON
const int startButton = 13;
int startButtonState = 0; //1 = open->not pressed

//STRATBUTTON TOGGLE
int startButtonReading;           // the current reading from the input pin
int previouStartButtonReading = 0;    // the previous reading from the input pin

//LINEAR MOTION MOTOR
const int homePinL = 5;
int homePinStateL;

boolean atStartPosition = false;


//SERVO
unsigned long currentServoMillis;
unsigned long previousServoMillis;
//const long servoInterval = 2000;
#define SERVO_PIN         9
int lenMicroSecondsOfPeriod = 20 * 1000; // 20 milliseconds (ms)
const long lenMicroSecondsOfPulse = 2.5 * 1000; // 1.0 ms is 0 degrees




void setup() {//================================================================
  pinMode(SERVO_PIN, OUTPUT);
  pixels.begin();
  pixels.show();
  stepperA.setMaxSpeed(19000);
  stepperA.setAcceleration(20000);
  pinMode(ledPinLDR, OUTPUT);
  pinMode(crashPin1, INPUT);
  pinMode(startButton, INPUT_PULLUP);
  pinMode(homePinA, INPUT_PULLUP);
  pinMode(homePinL, INPUT_PULLUP);
  pinMode(enableA, OUTPUT);
  pinMode(enableL, OUTPUT);
  digitalWrite(enableA, HIGH);
  digitalWrite(enableL, HIGH);
  Serial.begin(115200);
  delay(200);

  for (int i = 0; i < NUMPIXELS; i++) {

    // pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
    pixels.setPixelColor(i, pixels.Color(0, 150, 0)); // Moderately bright green color.

    pixels.show(); // This sends the updated pixel color to the hardware.

    delay(delayval); // Delay for a period of time (in milliseconds).

  }




}
void loop() {//=========================================================
  currentServoMillis = micros();
  if (atStartPosition == false)
  {

    //Serial.print ("in the if loop");
    //Serial.println(startButtonState);

    homePin2StateA = digitalRead(homePinA);
    homePinStateL = digitalRead(homePinL);
    //_______________________________\\

    if (homePin2StateA == 0 ) // 0 = not at his start position - 1 = at his position
    { //Serial.println (homePin2StateA);
      digitalWrite(enableA, LOW);
      stepperA.setSpeed(-3000); //set to -1900
      stepperA.runSpeed();
    }
    if (homePin2StateA == 1)
    {
      stepperA.setCurrentPosition(0);
    }

    if (homePinStateL == 1 )
    { digitalWrite(enableL, LOW);
      stepperL.setMaxSpeed(500);
      stepperL.setAcceleration(400);
      stepperL.moveTo(-2500);
      stepperL.run();

 // Below is the servo code where i need servo to go to 90 degrees

      ///////SERVO/////////////////
      if (currentServoMillis - previousServoMillis >= lenMicroSecondsOfPulse)
      {
        digitalWrite(SERVO_PIN, HIGH);
        previousServoMillis = currentServoMillis;
      }
      //delayMicroseconds(lenMicroSecondsOfPulse);
      digitalWrite(SERVO_PIN, LOW);
      delayMicroseconds(lenMicroSecondsOfPeriod - lenMicroSecondsOfPulse);
    }



    if (homePinStateL == 0 )
    {
      stepperL.setCurrentPosition(0);
    }

    if (stepperA.currentPosition() == 0 and stepperL.currentPosition() == 0 )
    {
      (atStartPosition = true);

////////HERE SCHOULD THE SERVO GO TO 0 degrees
    }




    if (homePin2StateA == 0  or homePinStateL == 1 )
    {
      pixels.setPixelColor(0, 255, 0, 0);
      pixels.setPixelColor(1, 255, 0, 0);
      pixels.setPixelColor(2, 255, 0, 0);
      pixels.setPixelColor(3, 255, 0, 0);
      pixels.setPixelColor(4, 255, 0, 0);
      pixels.setPixelColor(5, 255, 0, 0);
      pixels.setPixelColor(6, 255, 0, 0);
      pixels.setPixelColor(7, 255, 0, 0);
    }
    if (homePin2StateA == 1  or homePinStateL == 0 )
    {
      pixels.setPixelColor(0, 0, 155, 0);
      pixels.setPixelColor(1, 0, 155, 0);
      pixels.setPixelColor(2, 0, 155, 0);
      pixels.setPixelColor(3, 0, 155, 0);
      pixels.setPixelColor(4, 0, 155, 0);
      pixels.setPixelColor(5, 0, 155, 0);
      pixels.setPixelColor(6, 0, 155, 0);
      pixels.setPixelColor(7, 0, 155, 0);
      //pixels.show();
    }

    pixels.show();
  }
  //**********************STEPPERS AT START POSITION****************************//
  startbutton();

  crashPin1State = analogRead(crashPin1);
  //Serial.println(crashPin1State);
  homePin2StateA = digitalRead(10);
  homePinStateL = digitalRead(homePinL);


  //////////////////////////READ THE LDR/////////////////////////////////////////
  if (crashPin1State <= 40 and homePin2StateA == 1 ) {
    digitalWrite(ledPinLDR, HIGH);
    crashButtonPressed = true;
  }
  else {
    //crashButtonPressed = false;
    digitalWrite(ledPinLDR, LOW);
  }
  //////////////////////////FORWARD MOVE STEPPER L/////////////////////////////////////////

  if (startButtonState == 0 && homePin2StateA == 1 && crashButtonPressed == false
      && stepperL.currentPosition() == 0)
  {
    stepperL.setMaxSpeed(400);
    stepperL.setAcceleration(500);
    stepperL.moveTo(1300); //set to 1300
  }
  if (startButtonState == 0 && homePin2StateA == 1 && crashButtonPressed == false
      && stepperL.currentPosition() == 1300 && stepperL.targetPosition() == 1300)
  {
    stepperL.setMaxSpeed(200);
    stepperL.setAcceleration(500);
    stepperL.moveTo(2320); //set to 2380
  }

  if (startButtonState == 0 && homePin2StateA == 1 && crashButtonPressed == false
      && stepperL.currentPosition() == 2320)
  {
    stepperL.setMaxSpeed(750);
    stepperL.setAcceleration(2000);
    stepperL.moveTo(0); //set to 2380
  }

  if (homePinStateL == 0 and stepperL.targetPosition() == 0)
  {
    startButtonState = 1;
  }

  stepperL.run();

  ////////////////////////////////////////////
  if (homePinStateL == 0 && startButtonState == 1)
  {
    digitalWrite(enableL, HIGH);
  }

  else {
    digitalWrite(enableL, LOW);
  }
  //    Serial.print ("in the main loop");
  Serial.print(startButtonState);

  ///////////////////////////////////////////
      if (currentServoMillis - previousServoMillis >= lenMicroSecondsOfPulse)

Can you please explain what this line of code does and why the variable names make no sense ?

Why aren't you using the Servo library ?

read post #3. I think it slipt your attention.

I'm having problems with de accelstepper.h, Adafruit_NeoPixel.h and de servo.h , i think.

When using servo.h the servo goes wild.

When using manual code it does not. but the code i have is with micros().
And these make the steppers skip steps and operate badly.

Actually they are Micros() so the code should be something like this.
But with this code there is something off in the timing.

      if (currentServoMicros - previousServoMicros >= lenMicroSecondsOfPeriod - lenMicroSecondsOfPulse)
      {
        digitalWrite(SERVO_PIN, HIGH);
        previousServoMicros = currentServoMicros;
      }

      
      if (currentServoMicros - previousServoMicros2 >= lenMicroSecondsOfPulse)
      {digitalWrite(SERVO_PIN, LOW);
        previousServoMicros2 = currentServoMicros;
         
      }

Found the cause of the problem.
It was this peace of code that made the servo go wild.

Does anyone know if there is a beter way to do the same like below?

tnx for the help.

    if (homePin2StateA == 0  or homePinStateL == 1 )
    {
      pixels.setPixelColor(0, 255, 0, 0);
      pixels.setPixelColor(1, 255, 0, 0);
      pixels.setPixelColor(2, 255, 0, 0);
      pixels.setPixelColor(3, 255, 0, 0);
      pixels.setPixelColor(4, 255, 0, 0);
      pixels.setPixelColor(5, 255, 0, 0);
      pixels.setPixelColor(6, 255, 0, 0);
      pixels.setPixelColor(7, 255, 0, 0);
    }
    if (homePin2StateA == 1  or homePinStateL == 0 )
    {
      pixels.setPixelColor(0, 0, 155, 0);
      pixels.setPixelColor(1, 0, 155, 0);
      pixels.setPixelColor(2, 0, 155, 0);
      pixels.setPixelColor(3, 0, 155, 0);
      pixels.setPixelColor(4, 0, 155, 0);
      pixels.setPixelColor(5, 0, 155, 0);
      pixels.setPixelColor(6, 0, 155, 0);
      pixels.setPixelColor(7, 0, 155, 0);
      //pixels.show();
    }

    pixels.show();

Those lines of code don't have anything to do with your Servo. Removing them may have caused a different behavior, but not because those lines were doing anything wrong.

Ok, thanks for the input.

With these lines servo is going crazy. Without them everything is working fine.

Now i don't know how to control NeoPixel stick?

Is there another way to control the adafruit NeoPixel stick?

See The Issue | Using NeoPixels and Servos Together | Adafruit Learning System

YOU ARE MY HERO HELIBOB!!!

2 days i'm struggeling with this. :confused:
And i figured out it was the 2 liberarys problem.
But was not that smart to google this the specifiek issue!!

THANK YOU SO MUCH!!!!! IT WORKS LIKE CHARM!! ;D :smiley:

I'm glad it worked. For information, the search phrase that I used was "does Adafruit_NeoPixel library use timer" without the quotes.