Incremental Servo Movement

Post here about your Arduino projects, get help - for Adafruit customers!

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
Locked
downtownmjb
 
Posts: 3
Joined: Tue Apr 16, 2013 7:53 am

Incremental Servo Movement

Post by downtownmjb »

Hello All,

I'm on another arbitrary project (using Arduino Starter Kit) I conjured up just to continue practicing the basics.

I've got my project wired up so that 3 successive LED's strike. But after the 3rd I'd like my attached servo motor to move in a desired increment (not the popular sweeping situation).

Right now, the LED's are working great but just the servo...not so much. Here is the code, which may not be very logical at this point after a few hours of tinkering with the code and trying anything I could think of -

Code: Select all

#include <Servo.h>
Servo myServo;
int pos = 0;
int prevPos = pos + 45;
int greenPin = 11;
int redPin = 12;
int bluePin = 13;

void setup(){
  myServo.attach(9);
  pinMode (greenPin, OUTPUT);
  pinMode(redPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
}

void loop()
{
  digitalWrite (greenPin, HIGH);
  digitalWrite (redPin, LOW);
  digitalWrite (bluePin, LOW);
  delay(250);
  
  digitalWrite (greenPin, HIGH);
  digitalWrite (redPin, HIGH);
  digitalWrite (bluePin, LOW);
  delay(250);
  
  digitalWrite (greenPin, HIGH);
  digitalWrite (redPin, HIGH);
  digitalWrite (bluePin, HIGH);
  delay(250);
  
  digitalWrite (greenPin, LOW);
  digitalWrite (redPin, LOW);
  digitalWrite (bluePin, LOW);
  myServo.write(prevPos + 45);
  delay(250);
}
Thanks so much and Be well!

User avatar
adafruit_support_mike
 
Posts: 67446
Joined: Thu Feb 11, 2010 2:51 pm

Re: Incremental Servo Movement

Post by adafruit_support_mike »

Your code doesn't change the value stored in the variable 'prevpos'. This line:

Code: Select all

  myServo.write(prevPos + 45);
is just a slightly more complicated way of saying:

Code: Select all

  myServo.write( 90 );
over and over again.

You need something like this at the end:

Code: Select all

    prevpos = (prevpos <= 135) ? prevpos + 45 : prevpos - 45;

Locked
Please be positive and constructive with your questions and comments.

Return to “Arduino”