0

I have a ATTiny85 with a standard servo motor attached to it. I would expect the following sketch to make the servo to oscillate between position 60 and 100 but instead it just to to it's limit (180) and grinds there...

Any ideas ?

#include <avr/power.h>
#include <Adafruit_SoftServo.h>

Adafruit_SoftServo servo;

#define MOTOR_PIN 0

bool flip = true;

void setup() {
  if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
  // Set up the interrupt that will refresh the servo for us automagically
  OCR0A = 0xAF;            // any number is OK
  TIMSK |= _BV(OCIE0A);    // Turn on the compare interrupt (below!)

  servo.attach(MOTOR_PIN);
  servo.write(90);           // Tell servo to go to position per quirk
  delay(15);
}

void loop() {
  if(flip) {
    servo.write(60);
    delay(150);
    !flip;
  }
  else {
    servo.write(100);
    delay(150);
    !flip;
  }

  delay(500);

}

// We'll take advantage of the built in millis() timer that goes off
// to keep track of time, and refresh the servo every 20 milliseconds
volatile uint8_t counter = 0;
SIGNAL(TIMER0_COMPA_vect) {
  // this gets called every 2 milliseconds
  counter += 2;
  // every 20 milliseconds, refresh the servos!
  if (counter >= 20) {
    counter = 0;
    servo.refresh();
  }
}

Thanks.

4

!flip doesn't really do anything and will probably be optimized out by the compiler. You need to save the result: flip = !flip;

You can simplify the code a bit:

void loop() {
    if(flip) {
        servo.write(60);
    }
    else {
        servo.write(100);
    }
    flip = !flip;
    delay(650);
}

Or, get rid of the delay altogether:

uint32_t last_millis = 0;    
void loop() {
    if (millis() - last_millis >= 650) {
        servo.write(flip ? 60 : 100);
        flip = !flip; 
        last_millis = millis();
    }
}
  • That was part of it (must be doing too much Ruby these days). The other part is that I was compiling with an outdated Arduino core library... Updated and all is good now. Thanks. – Andre Courchesne Jun 27 '17 at 1:49

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.