0

Board: "ATtiny25/45/85"

Processor: "ATtiny85"

Clock: "Internal 1 MHz"

Programmer: "Arduino as ISP"

I want to run a servo forwards and backwards on an ATtiny85. The servo library is not compatible with the ATtiny85 so I had to write code from scratch. At this point, the code that makes the servo go forwards (clockwise) is:

void setup() {
  pinMode(PB1, OUTPUT);
}

void loop() {
  digitalWrite(PB1, HIGH);
  delayMicroseconds(1000);
  // 1 millisecond determines the servo going forwards
  digitalWrite(PB1, LOW);
  delay(19);
}

And the code that makes the servo go backwards (anti-clockwise) is simply by changing the amount of microseconds to:

delayMicroseconds(2000); 

I want to have the servo motor go forwards one cycle for a few seconds and then go backwards for a few. I want this to keep looping. At this point my code is:

void setup() {
  pinMode(PB1, OUTPUT);
}

void loop() {
  digitalWrite(PB1, HIGH);
  delayMicroseconds(1000);
  digitalWrite(PB1, LOW);
  delay(19);
  digitalWrite(PB1, HIGH);
  delayMicroseconds(2000);
  digitalWrite(PB1, LOW);
  delay(19);
}

This however just makes the servo go back and forward at the same spot forever. I do realise I might need a for loop for this but I am confused as how I will do this.

1

The servo can't move back and forward in 40 milliseconds. It'll be more like tremble between both.

Try something like this:

// keep sending 0 position for about 400ms
for(int i = 0; i<20; ++i) {
  digitalWrite(PB1, HIGH);
  delayMicroseconds(1000);
  digitalWrite(PB1, LOW);
  delay(19);
}

// keep sending second position for about 400ms
for(int i = 0; i<20; ++i) {
  digitalWrite(PB1, HIGH);
  delayMicroseconds(2000);
  digitalWrite(PB1, LOW);
  delay(19);
}
  • Hi thanks a lot it really helped and it makes sense too. I just have one question, that delay(19) when changed to delay(20) the servo behaves differently. Why is that delay kept at 19 milliseconds and not something else? thanks again. – Utsav Sep 15 '17 at 14:35
  • 1
    The servo expects pulses at 20ms rate (= 50Hz) including High side pulse width. – KIIV Sep 15 '17 at 14:54

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.