Hi all,
I have created a class to control the PWM output of a pin. In the constructor of the class, I set the TCCRnA, TCCRnB, ICRn registers. I have noticed however that, the values of the TCCRnA and B registers get changed to some other value and the ICR value can also change.. Does anyone have any suggestions why this is?
My example code for my arduino mega ADK is as follows:
class MyClass{
public:
MyClass(const uint8_t & pin, volatile unsigned int & ICRn,
volatile unsigned int & OCRnX, volatile unsigned char & TCCRnA_in,
volatile unsigned char & TCCRnB, int ocrEnableBit,
const double & pwmTop);
void init();
private:
const uint8_t & myPin;
double desiredOCR;
volatile unsigned int & ICRn;
volatile unsigned char & TCCRnA;
volatile unsigned char & TCCRnB;
volatile unsigned int & OCRnX;
int ocrEnableBit;
const double & PWM_TOP;
};
MyClass::MyClass(const uint8_t & pin, volatile unsigned int & ICRn,
volatile unsigned int & OCRnX, volatile unsigned char & TCCRnA_in,
volatile unsigned char & TCCRnB, int ocrEnableBit,
const double & pwmTop):myPin(pin), ICRn(ICRn), TCCRnA(TCCRnA_in),
TCCRnB(TCCRnB), OCRnX(OCRnX), ocrEnableBit(ocrEnableBit),
PWM_TOP(pwmTop){
pinMode(myPin, OUTPUT);
digitalWrite(myPin, LOW);
init();
ICRn = (unsigned int) (PWM_TOP) ;
OCRnX = 0;
}
void MyClass::init(){
TCCRnA = B00000010;//_BV(WGM31) ; // dont enable output compare until PWM is needed, otherwise, get output spikes when OC == 0
TCCRnB = B00011001;//_BV(WGM33) | _BV(WGM32) | _BV(CS30);
ICRn = (unsigned int) (PWM_TOP) ;
}
const double PWM_TOP = 0xFFFE; //was 8192
const uint8_t myPin = 44;
MyClass myClass(myPin, ICR5, OCR5C, TCCR5A, TCCR5B, COM5C1, PWM_TOP);
void setup(){
Serial.begin(57600);
//why are the values here not the same as when i set them in MyClass constructor and i power the arduino with external power?
Serial.println(ICR5);
Serial.println(TCCR5A, BIN);
Serial.println(TCCR5B, BIN);
//I have to set them again to get what I want
myClass.init();
Serial.println(ICR5);
Serial.println(TCCR5A, BIN);
Serial.println(TCCR5B, BIN);
}
void loop(){
}
when the arduino is powered by usb, my output is
65534
11
11011
65534
10
11001
when i power my power with an external supply, i get
199
11
11011
65534
10
11001
why are the TCCR values not the same as what I set them in the constructor and why do i get different behaviour when powered by an external supply?
Thanks in advance