Re: ServoTimer2 library giving errors..... PLEASE HELP

Hi !
It’s my first writing on this forum, but I followed Arduino issues since a long time.

I wanted to share my work on the ServoTimer2 library, because it could help someone like me in the future.

I managed to make it work on the 1.6.5 IDE, and it wasn’t that easy, so here are the codes :

First as mem explained in the first place, you need to create a folder called ServoTimer2 in the libraries directory of your IDE.

Then create a file called servoTimer2.cpp with this code inside :

/* ServoTimer2.cpp*/
extern "C" {
 // AVR LibC Includes
 #include <inttypes.h>
 #include <avr/interrupt.h>


}
#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include <wiring_private.h>
#include "ServoTimer2.h"
static void initISR();   
static void writeChan(uint8_t chan, int pulsewidth);

#define FRAME_SYNC_INDEX   0             // frame sync delay is the first entry in the channel array
#define FRAME_SYNC_PERIOD  20000         // total frame duration in microseconds 
#define FRAME_SYNC_DELAY   ((FRAME_SYNC_PERIOD - ( NBR_CHANNELS * DEFAULT_PULSE_WIDTH))/ 128) // number of iterations of the ISR to get the desired frame rate
#define DELAY_ADJUST       8             // number of microseconds of calculation overhead to be subtracted from pulse timings   

static servo_t servos[NBR_CHANNELS+1];    // static array holding servo data for all channels

static volatile uint8_t Channel;   // counter holding the channel being pulsed
static volatile uint8_t ISRCount;  // iteration counter used in the interrupt routines;
uint8_t ChannelCount = 0;          // counter holding the number of attached channels
static boolean isStarted = false;  // flag to indicate if the ISR has been initialised

ISR (TIMER2_OVF_vect)
{ 
 ++ISRCount; // increment the overlflow counter
 if (ISRCount ==  servos[Channel].counter ) // are we on the final iteration for this channel
 {
     TCNT2 =  servos[Channel].remainder;   // yes, set count for overflow after remainder ticks
 }  
 else if(ISRCount >  servos[Channel].counter)  
 {
     // we have finished timing the channel so pulse it low and move on
     if(servos[Channel].Pin.isActive == true)           // check if activated
         digitalWrite( servos[Channel].Pin.nbr,LOW); // pulse this channel low if active   

       Channel++;    // increment to the next channel
     ISRCount = 0; // reset the isr iteration counter 
     TCNT2 = 0;    // reset the clock counter register
     if( (Channel != FRAME_SYNC_INDEX) && (Channel <= NBR_CHANNELS) ){           // check if we need to pulse this channel    
         if(servos[Channel].Pin.isActive == true)         // check if activated
            digitalWrite( servos[Channel].Pin.nbr,HIGH); // its an active channel so pulse it high   
     }
     else if(Channel > NBR_CHANNELS){ 
        Channel = 0; // all done so start over               
     } 
  }  
}

ServoTimer2::ServoTimer2()
{
  if( ChannelCount < NBR_CHANNELS)  
     this->chanIndex = ++ChannelCount;  // assign a channel number to this instance
  else
     this->chanIndex = 0;  // todo      // too many channels, assigning 0 inhibits this instance from functioning 
}
uint8_t ServoTimer2::attach(int pin)
{
     if( isStarted == false)
      initISR();    
     if(this->chanIndex > 0)  
     {
      //debug("attaching chan = ", chanIndex);
      pinMode( pin, OUTPUT) ;  // set servo pin to output
      servos[this->chanIndex].Pin.nbr = pin;  
      servos[this->chanIndex].Pin.isActive = true;  
     } 
     return this->chanIndex ;
}

void ServoTimer2::detach()  
{
   servos[this->chanIndex].Pin.isActive = false;  
}

void ServoTimer2::write(int pulsewidth)
{      
  writeChan(this->chanIndex, pulsewidth); // call the static function to store the data for this servo          
}

int ServoTimer2::read()
{
 unsigned int pulsewidth;
  if( this->chanIndex > 0)
     pulsewidth =  servos[this->chanIndex].counter * 128 + ((255 - servos[this->chanIndex].remainder) / 2) + DELAY_ADJUST ;
  else 
      pulsewidth  = 0;
  return pulsewidth;   
}

boolean ServoTimer2::attached()
{
   return servos[this->chanIndex].Pin.isActive ;
}

static void writeChan(uint8_t chan, int pulsewidth)
{
  // calculate and store the values for the given channel
  if( (chan > 0) && (chan <= NBR_CHANNELS) )   // ensure channel is valid
  { 
     if( pulsewidth < MIN_PULSE_WIDTH )                // ensure pulse width is valid
         pulsewidth = MIN_PULSE_WIDTH;
     else if( pulsewidth > MAX_PULSE_WIDTH )
         pulsewidth = MAX_PULSE_WIDTH;       
     
       pulsewidth -=DELAY_ADJUST;                   // subtract the time it takes to process the start and end pulses (mostly from digitalWrite) 
     servos[chan].counter = pulsewidth / 128;      
     servos[chan].remainder = 255 - (2 * (pulsewidth - ( servos[chan].counter * 128)));  // the number of 0.5us ticks for timer overflow         
  }
}

static void initISR()
{   
     for(uint8_t i=1; i <= NBR_CHANNELS; i++) {  // channels start from 1    
        writeChan(i, DEFAULT_PULSE_WIDTH);  // store default values          
     }
     servos[FRAME_SYNC_INDEX].counter = FRAME_SYNC_DELAY;   // store the frame sync period       

     Channel = 0;  // clear the channel index  
     ISRCount = 0;  // clear the value of the ISR counter;
     
     /* setup for timer 2 */
     TIMSK2 = 0;  // disable interrupts 
     TCCR2A = 0;  // normal counting mode 
     TCCR2B = _BV(CS21); // set prescaler of 8 
     TCNT2 = 0;     // clear the timer2 count 
     TIFR2 = _BV(TOV2);  // clear pending interrupts; 
     TIMSK2 =  _BV(TOIE2) ; // enable the overflow interrupt        
       
     isStarted = true;  // flag to indicate this initialisation code has been executed
}

Thanks for sharing. That should be very useful.

...R

Then create a file named ServoTimer2.h and drop this code inside :

/*
 ServoTimer2.h - Interrupt driven Servo library for Arduino using 
/* 
 This library uses Timer2 to drive up to 8 servos using interrupts so no refresh activity is required from within the sketch. 
 The usage and method naming is similar to the Arduino software servo library http://www.arduino.cc/playground/ComponentLib/Servo
 except that pulse widths are in microseconds.

 
 A servo is activated by creating an instance of the Servo class passing the desired pin to the attach() method.
 The servo is pulsed in the background to the value most recently written using the write() method

 Note that analogWrite of PWM on pins 3 and 11 is disabled when the first servo is attached

 The methods are:

  ServoTimer2 - Class for manipulating servo motors connected to Arduino pins.

  attach(pin )  - Attaches a servo motor to an i/o pin.
  attach(pin, min, max  ) - Attaches to a pin setting min and max values in microseconds
   default min is 544, max is 2400  

  write()     - Sets the servo pulse width in microseconds.

  read()      - Gets the last written servo pulse width in microseconds. 

  attached()  - Returns true if there is a servo attached. 

  detach()    - Stops an attached servos from pulsing its i/o pin. 
 

The library takes about 824 bytes of program memory and 32+(1*servos) bytes of SRAM. 
The pulse width timing is accurate to within 1%

*/

// ensure this library description is only included once
#ifndef ServoTimer2_h
#define ServoTimer2_h

#include <inttypes.h>
//typedef uint8_t boolean;
typedef uint8_t byte;

#define MIN_PULSE_WIDTH       750        // the shortest pulse sent to a servo  
#define MAX_PULSE_WIDTH      2250        // the longest pulse sent to a servo 
#define DEFAULT_PULSE_WIDTH  1500        // default pulse width when servo is attached
#define FRAME_SYNC_PERIOD   20000        // total frame duration in microseconds 
#define NBR_CHANNELS 8                   // the maximum number of channels, don't change this 

typedef struct  {
     uint8_t nbr        :5 ;  // a pin number from 0 to 31
     uint8_t isActive   :1 ;  // false if this channel not enabled, pin only pulsed if true 
  } ServoPin_t   ;  

typedef struct {
 ServoPin_t Pin;
 byte counter;
 byte remainder;
}  servo_t;

class ServoTimer2
{
 public:
     // constructor:
     ServoTimer2();

     uint8_t attach(int);     // attach the given pin to the next free channel, sets pinMode, returns channel number or 0 if failure
                              // the attached servo is pulsed with the current pulse width value, (see the write method) 
     uint8_t attach(int, int, int); // as above but also sets min and max values for writes. 
   void detach();
   void write(int);         // store the pulse width in microseconds (between MIN_PULSE_WIDTH and MAX_PULSE_WIDTH)for this channel
   int read();                    // returns current pulse width in microseconds for this servo
     bool attached();      // return true if this servo is attached 
private:
      uint8_t chanIndex;      // index into the channel data for this servo

};


// the following ServoArrayT2 class is not implemented in the first version of this library
class ServoArrayT2
{
 public:
     // constructor:
     ServoArrayT2();

     uint8_t attach(int);     // attach the given pin to the next free channel, sets pinMode, returns channel number or 0 if failure
                              // channels are assigned consecutively starting from 1
                              // the attached servo is pulsed with the current pulse width value, (see the write method) 
   void detach(int);        // detach the servo on the given channel
     void write(int,int);     // store the pulse width in microseconds (between MIN_PULSE_WIDTH and MAX_PULSE_WIDTH)for the given channel
   int read(int);                    // returns current pulse width in microseconds for the given channel
     bool attached(int);   // return true if the servo on the given channel is attached 
private:
      uint8_t chanIndex;      // index into the channel data for this servo

};

#endif

And here a code for an example : the Sweep example of the Servo library, adapted to ServoTimer2
(with a function of conversion from degrees to microseconds)

/* Sweep adapted for TIMER2
 by BARRAGAN <http://barraganstudio.com> 
 This example code is in the public domain.

 modified 8 Nov 2013
 by Scott Fitzgerald
 http://www.arduino.cc/en/Tutorial/Sweep

 modified 27 nov 2015
 by Adrien Touche
 in order to work with ServoTimer2
*/ 

#include <ServoTimer2.h>  // the servo library

#define degreesToUS( _degrees) (_degrees * 6 + 900) // macro to convert degrees to microseconds
 
ServoTimer2 myservo;  // create servo object to control a servo 
                // twelve servo objects can be created on most boards
 
int pos = 0;    // variable to store the servo position 
 
void setup() 
{ 
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object 
} 
 
void loop() 
{ 
  for(pos = 0; pos <= 180; pos += 1) // goes from 0 degrees to 180 degrees 
  {                                  // in steps of 1 degree 
    myservo.write(degreesToUS(pos));              // tell servo to go to position in variable 'pos' 
    delay(15);                       // waits 15ms for the servo to reach the position 
  } 
  for(pos = 180; pos>=0; pos-=1)     // goes from 180 degrees to 0 degrees 
  {                                
    myservo.write(degreesToUS(pos));              // tell servo to go to position in variable 'pos' 
    delay(15);                       // waits 15ms for the servo to reach the position 
  } 
}

@mcflyos, I suggested to the Moderator to move your suggestion to its own Thread so it would be easier to find.

It would now be helpful if you would modify your original post and change the Title to "ServoTimer2 library updated for IDE 1.6.5"

...R