1

So I'm trying to control 4 servo motors simultaneously using the Protothreads library by Ben Artin, but I am starting with 2 just to see if it works.

I have succeeded in getting two LEDs to blink at the same time but at different frequencies.

When I try to connect the 2 servo motors using exactly the same technique as the LEDs to get them to sweep simultaneously, they don't work together. Only one works.

Below is the code I am using:

#include <protothreads.h>
#include <Servo.h>

Servo myservo1;
Servo myservo2;

int pos1 = 0;
int pos2 = 0;

////////////////////////     T H R E A D    1     /////////////////////////

pt ptServo1;
int servoThread1(struct pt* pt) {
  PT_BEGIN(pt);
  for(;;) {
    for (pos1 = 0; pos1 <= 180; pos1 += 1) {
      // in steps of 1 degree
      myservo1.write(pos1);
      delay(2);
    }
    delay(500);
    for (pos1 = 180; pos1 >= 0; pos1 -= 1) {
      myservo1.write(pos1);
      delay(2);
    }
    delay(500);
  }
  PT_END(pt);
}


////////////////////////     T H R E A D    2     /////////////////////////
pt ptServo2;
int servoThread2(struct pt* pt) {
  PT_BEGIN(pt);
  for(;;) {
    for (pos2 = 0; pos2 <= 180; pos2 += 1) {
      // in steps of 1 degree
      myservo2.write(pos2);
      delay(2);
    }
    delay(500);
    for (pos2 = 180; pos2 >= 0; pos2 -= 1) {
      myservo2.write(pos2);
      delay(2);
    }
    delay(500);
  }
  PT_END(pt);
}



void setup() {
  myservo1.attach(9); 
  myservo2.attach(6);
}

void loop() {
  PT_SCHEDULE(servoThread2(&ptServo2));
  PT_SCHEDULE(servoThread1(&ptServo1));
}

In the loop() function, whichever thread is called first, that's the servo that sweeps. The second servo does not do anything at all.

Any help would be greatly appreciated!

Thank you so much,

H

2
  • 5
    You must use PT_SLEEP not delay to allow your threads to co-exist. That's what the examples use, so why did you decide not to?
    – Majenko
    Sep 1 at 20:56
  • 1
    @Majenko Thank you, yes that has indeed solved my first problem....I have another problem which I will post in another question. Thank you so much, please have a look at that also if you can! Thank you so much :)
    – H. M
    Sep 1 at 22:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.