Go Down

Topic: Arduino & Continous Rotation Servos (Read 2167 times) previous topic - next topic

retrolefty

#15
Jan 10, 2013, 05:54 am Last Edit: Jan 10, 2013, 06:14 am by retrolefty Reason: 1

Here is the code I got to work. The question I was asking was a little more general... it can be worded as "How can I run two lines of code at the same time?"
This is my current code to run one servo, based on a library I found online. I just want to run two servos at once, and thought I might be able to get two lines of code to execute AT THE SAME TIME.
Code: [Select]
#include <ContinuousRotationServo.h>

ContinuousRotationServo Servo;
int distance;

void setup()
{
 Servo.begin(2); // port 2, this library works without PWM
}

void loop()
{
 Servo.rotateLeft(50,100);
 Servo.noMovement(500);
 Servo.rotateRight(50,100);
 Servo.noMovement(500);
}



Well first a microcontroller chip is a single core processor that is always capable of only executing one machine instruction at a time, so the whole concept of doing things "AT THE SAME TIME" is something you will have to come to terms with. The processor is very fast so many tasks can be done independently of each other such that from a human point of view it will indeed seem that it can do many things at the same time.

So taking your code example and adding a second servo and giving it the same commands, you would not be able to tell that the micro was not doing two things at the same time even though it is.

Code: [Select]
#include <ContinuousRotationServo.h>

ContinuousRotationServo Servo;
ContinuousRotationServo Servo2;
int distance;

void setup()
{
 Servo.begin(2); // port 2, this library works without PWM
 Servo2.begin(3);
}

void loop()
{
 Servo.rotateLeft(50,100);
 Servo2.rotateLeft(50,100);
  delay(1000);
 Servo.noMovement(500);
 Servo2.noMovement(500);
  delay(1000);
 Servo.rotateRight(50,100);
 Servo2.rotateRight(50,100);
  delay(1000);
 Servo.noMovement(500);
 Servo2.noMovement(500);
  delay(1000);
}


Lefty

Figured it out: this program works, and it runs two motors at the same time! The key, make sure a delay is after every instance. This program uses the standard Servo.h library.
Code: [Select]
// successfully runs 2 servos non-continuously
#include <Servo.h>
Servo mtrA;
Servo mtrB;
void setup(){
  mtrA.attach(9);
  mtrB.attach(10);
}
void loop(){
  fwd();
  delay(2000);
  STOP();
  delay(1000);
  turn();
  delay(2000);
  STOP();
  delay(1000);
}
void fwd(){
  mtrA.write(0);
  mtrB.write(180);
}
void turn(){
  mtrA.write(180);
  mtrB.write(180);
}
void STOP(){
  mtrA.write(90);
  mtrB.write(90);
}

Go Up