I am writing code to output PWM signals from my Arduino Mega. I need a PWM signal that refreshes on the order of 300Hz for my quadcopter. I can't use the Servo.h library because that only works at 50Hz, and besides, I don't want to modify it because I would like to be able to use the servo library as well. So far my Motor class works perfectly, except for some reason it doesn't work on pin 8. I am using timer3 and timer4 so I thought it should work for pins 2,3,5,6,7,8, and it works for everything except pin 8. I don't have an oscilloscope so I can't really check what it is doing for pin 8, though connecting an LED, it "appears" to be changing the pulse width. Please let me know how I can fix this.
This is my <Motor.h> file:
#ifndef _Motor_h
#define _Motor_h
class Motor{
public:
Motor();
void attach(int port);
void write(int n);
private:
int pin;
};
#endif
This is my <Motor.cpp> file:
#include <Arduino.h>
#include <Motor.h>
Motor::Motor(){
}
void Motor::attach(int p){
TCCR3A =((1<<WGM31)|(1<<COM3A1)|(1<<COM3B1)|(1<<COM3C1));
TCCR3B = (1<<WGM33)|(1<<WGM32)|(1<<CS30);
TCCR4A =((1<<WGM41)|(1<<COM4A1)|(1<<COM4B1)|(1<<COM4C1));
TCCR4B = (1<<WGM43)|(1<<WGM42)|(1<<CS40); //Set timer divider to 1;
ICR3 = 53333; //300Hz Refresh rate
ICR4 = 53333;
if(p!=2 && p!=3 && p!=5 && p!=6 && p!=7 && p!=8){
Serial.println("Error: Motors can only be attached to pins 2,3,5,6,7,8.");
}
else{
pin = p;
pinMode(pin, OUTPUT);
write(0);
}
}
void Motor::write(int n){
n = min(1000, n);
n = max(0, n);
n = (n+1000)*16;
if(pin == 2) OCR3B = n;
else if(pin == 3) OCR3C = n;
else if(pin == 5) OCR3A = n;
else if(pin == 6) OCR4A = n;
else if(pin == 7) OCR4B = n;
else if(pin == 8) OCR4C = n;
}
And this is my Arduino sketch to test if it is working:
#include <Servo.h>
#include <Motor.h>
Motor motor;
void setup(){
motor.attach(8);
motor.write(200); //1200us pulse to get motor going
delay(500);
motor.write(0); //1000us pulse to stop motor
}
void loop(){}