7

I have a problem with the Servo library.

I need to read a PPM signal and create a PWM signal of each channel. The problem is that PPM has a higher resolution than PWM so I want to use the 16 bit Timer1 for reading PPM. However the Servo library that writes the PWM signal also uses Timer1.

Is it possible to generate a PWM signal with 8 bit / Timer2? And has someone made an example, or an explanation about, how to do that?

Greenonline
  • 3,152
  • 7
  • 36
  • 48
betion
  • 115
  • 2
  • 6

3 Answers3

2

Yes, Arduino Servo library uses Timer1 (and other ones, depending on Arduino boards) to manage FastPWM via software interrupts. Timer2 is used by tone() function: be careful if you are using that function.

A good example using Timer2 to generate PWM is the Infrared remote library for Arduino. If IR_USE_TIMER2 is defined it will use Timer2. The key code is at IRremote.cpp where the ISR is managed.

caligari
  • 221
  • 1
  • 9
2

Here is a simple example from my page about timers of using Timer 2 to output a square wave of 50 kHz:

const byte LED = 3;  // Timer 2 "B" output: OC2B

const long frequency = 50000L;  // Hz

void setup() 
 {
  pinMode (LED, OUTPUT);

  TCCR2A = bit (WGM20) | bit (WGM21) | bit (COM2B1); // fast PWM, clear OC2B on compare
  TCCR2B = bit (WGM22) | bit (CS21);         // fast PWM, prescaler of 8
  OCR2A =  ((F_CPU / 8) / frequency) - 1;    // zero relative  
  OCR2B = ((OCR2A + 1) / 2) - 1;             // 50% duty cycle
  }  // end of setup

void loop()
  {
  // do other stuff here
  }
Nick Gammon
  • 38,901
  • 13
  • 69
  • 125
1

Is it possible to generate a PWM signal with 8 bit / Timer2?

yes. I implemented multiple approaches, some on avrs and some on pics but the basic principles are the same: https://dannyelectronics.wordpress.com/2017/02/18/driving-multiple-servos-off-a-pic-timer2-ranged-extended/

that post provided a list of links to other implementations - one of them off a timer 2 on avr.

dannyf
  • 2,813
  • 11
  • 13