Goodmorning everybody!
I'm trying to implement 10bits resolution and 10kHz pwm frequency for my auto balancing robot.
Pololu - Dual VNH3SP30 Motor Driver Carrier MD03A (max pwm frequency 10kHz)
https://www.sparkfun.com/products/9947
https://www.pololu.com/product/1443
For the mega2560 16 bits timers are 1,3,4,5:
timer 1 for pin 11 12
timer 3 for pin 2 3 5
timer 4 for pin 6 7 8
timer 5 for pin 44 45 46
I want to use timer5 and here Advanced Arduino: direct use of ATmega counter/timers at the end of the page shows pem modes: Fast Pwm at different resolutions, phase correct, phase and frequency correct. I usually read balancebot codes using phase and frequency, but don't really know why and how to set it in code.
#include <avr/io.h>
void setup(){
pinMode(44, OUTPUT);
pinMode(45, OUTPUT);
}
void loop(){
main();
}
void main(){
// In the next line of code, we:
// 1. Set the compare output mode to clear OC2A and OC2B on compare match.
// To achieve this, we set bits COM2A1 and COM2B1 to high.
// 2. Set the waveform generation mode to fast PWM (mode 3 in datasheet).
// To achieve this, we set bits WGM21 and WGM20 to high.
TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
//not able to understand HOW CAN I CHANGE THAT MODE
// In the next line of code, we:
// 1. Set the waveform generation mode to fast PWM mode 7 —reset counter on
// OCR2A value instead of the default 255. To achieve this, we set bit
// WGM22 to high.
// 2. Set the prescaler divisor to 1, so that our counter will be fed with
// the clock's full frequency (16MHz). To achieve this, we set CS20 to
// high (and keep CS21 and CS22 to low by not setting them).
// TCCR2B = _BV(WGM22) | _BV(CS20);
TCCR5B = B10010; // prescaling by 8 the system clock
// OCR2A holds the top value of our counter, so it acts as a divisor to the
// clock. When our counter reaches this, it resets. Counting starts from 0.
// Thus 63 equals to 64 divs.
// OCR2A = 63;
OCR5A = 14970; // 66,8002672Hz
// This is the duty cycle. Think of it as the last value of the counter our
// output will remain high for. Can't be greater than OCR2A of course. A
// value of 0 means a duty cycle of 1/64 in this case.
OCR5A = 0;
while(1);
}
Moderator edit:
</mark> <mark>[code]</mark> <mark>
</mark> <mark>[/code]</mark> <mark>
tags added.