Incremental Servo Movement
Moderators: adafruit_support_bill, adafruit

Incremental Servo Movement

by downtownmjb on Sat Jun 01, 2013 4:45 pm

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 | TOGGLE FULL SIZE
#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!
downtownmjb
 
Posts: 3
Joined: Tue Apr 16, 2013 6:53 am
Location: Nashville, TN

Re: Incremental Servo Movement

by adafruit_support_mike on Sat Jun 01, 2013 10:01 pm

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

Code: Select all | TOGGLE FULL SIZE
  myServo.write(prevPos + 45);

is just a slightly more complicated way of saying:

Code: Select all | TOGGLE FULL SIZE
  myServo.write( 90 );

over and over again.

You need something like this at the end:

Code: Select all | TOGGLE FULL SIZE
    prevpos = (prevpos <= 135) ? prevpos + 45 : prevpos - 45;
When you void a product warranty, you give up your right to sue the manufacturer if something goes wrong and accept full responsibility for whatever happens next. And then you truly own the product.
User avatar
adafruit_support_mike
 
Posts: 9681
Joined: Thu Feb 11, 2010 1:51 pm