Yes I actually need all of the 4 pins. I took a look into the aeroquad section and noticed that they have a similar solutoion to this, PWM with timers.
Code can be found here:
I copied the neccessary parts to give it a try.
#define PWM_FREQUENCY 50 // in Hz
#define PWM_PRESCALER 64
#define PWM_COUNTER_PERIOD (F_CPU/PWM_PRESCALER/PWM_FREQUENCY)
void initializeMotors(){
//http://arduino.cc/en/Hacking/PinMapping168 /328
DDRB = DDRB | B00001110; // Set ports to output PB1-3
DDRD = DDRD | B00001000; // Set port to output PD3
commandAllMotors(1000); // Initialise motors to 1000us (stopped)
// Init PWM Timer 1 16 bit
TCCR1A = (1<<WGM11)|(1<<COM1A1)|(1<<COM1B1);
TCCR1B = (1<<WGM13)|(1<<WGM12)|(1<<CS11);
ICR1 = PWM_COUNTER_PERIOD;
// Init PWM Timer 2 8bit // WGMn1 WGMn2 = Mode ? Fast PWM, TOP = 0xFF ,Update of OCRnx at BOTTOM
TCCR2A = (1<<WGM20)|(1<<WGM21)|(1<<COM2A1)|(1<<COM2B1); // Clear OCnA/OCnB on compare match, set OCnA/OCnB at BOTTOM (non-inverting mode)
TCCR2B = (1<<CS22)|(1<<CS21); // Prescaler set to 256, that gives us a resolution of 16us
// TOP is fixed at 255 // Output_PWM_Frequency = 244hz = 16000000/(256*(1+255)) = Clock_Speed / (Prescaler * (1 + TOP))
}
void writeMotors() {
OCR2B = motorCommand[MOTOR1] / 16 ; // 1000-2000 to 128-256
// OCR1A = motorCommand[MOTOR2] * 2 ;
// OCR1B = motorCommand[MOTOR3] * 2 ;
// OCR2A = motorCommand[MOTOR4] / 16 ;
}
void commandAllMotors(int command) {
OCR2B = command / 16 ; //MOTOR1
// OCR1A = command * 2 ; //MOTOR2
// OCR1B = command * 2 ; //MOTOR3
// OCR2A = command / 16 ; //MOTOR4
}
And main loop:
void setup(){
Serial.begin(9600);
initializeMotors();
}
void loop(){
for(int x = 1000; x < 2000; x++){
motorCommand[MOTOR1] = x;
writeMotors();
delay(200);
}
for(int y = 2000; y > 1000; y--){
motorCommand[MOTOR1] = y;
writeMotors();
delay(200);
}
}
I've tried to change the
PWM_FREQUENCY
parameter to even as low as 50hz, but the motors will just beep continously.
To see what the maximum refresh rate is I made a manual sketch where I can change the frequency and just put the digital pin as 1s and 0s.
The result was a maximum frequency of 285hz.
int freq = 3500; //in micros
void setup(){
Serial.begin(9600);
for(int x = 0; x <1000; x++){
digitalWrite(3, 1);
delayMicroseconds(1000);
digitalWrite(3, 0);
delayMicroseconds(freq);
}
}
void loop(){
for(int x = 1000; x < 2000; x++){
digitalWrite(3, 1);
delayMicroseconds(x);
digitalWrite(3, 0);
delayMicroseconds(freq);
}
for(int y = 2000; y > 1000; y--){
digitalWrite(3, 1);
delayMicroseconds(y);
digitalWrite(3, 0);
delayMicroseconds(freq);
}
}
Can any1 see whats wrong with the first code, from aeroquad?
Cheers