I indeed want to control a servo. And i want to control it using a PWM signal based on Timer1 because i already use Timer2 to control 2 stepper motors.
I have been debugging further and created a new program from scratch.
void setup() {
uint8_t _servoPort = 9; // using pin D9
uint8_t _servoPinBitmask = digitalPinToBitMask(_servoPort); // translate pin number to port register bitmask for selected pin.
volatile uint8_t *_servoOutputRegister;
volatile uint8_t *_servoModeRegister;
_servoOutputRegister = portOutputRegister(digitalPinToPort(_servoPort)); // Get the output (PORT) port register for selected pin.
_servoModeRegister = (uint8_t *)portModeRegister(digitalPinToPort(_servoPort)); // get DDR register for pin
*_servoModeRegister |= _servoPinBitmask; // Set pin to output (HIGH) in DDR registe
// Clear OC1A on match, set on bottom
TCCR1A |= (1 << COM1A1);
TCCR1A &= ~(1 << COM1A0);
// Set OC1B on match, clear on bottom (inverted)
TCCR1A |= (1 << COM1B1);
TCCR1A |= (1 << COM1B0);
// Fast PWM Mode 14 ICR1=TOP
TCCR1B |= (1 << WGM13);
TCCR1B |= (1 << WGM12);
TCCR1A |= (1 << WGM11);
TCCR1A &= ~(1 << WGM10);
// frequency 16000000/(8*(40000-1)) = 50Hz
ICR1 = 0x9C40;
// Duty cycle 25%
OCR1A = 0x2710 ;
// Duty cycle 50%
OCR1B = 0x4E20 ;
// Prescaler to CLKio/8
TCCR1B &= ~(1 << CS12);
TCCR1B |= (1 << CS11);
TCCR1B &= ~(1 << CS10);
}
void loop() {
}
This code does exactly what i expect it to do. Create a pulse with a period of 20ms (50Hz) and a duty cycle on OCR1A of 25% and 50% on OCR1B. ![]()
When moving this code to the library in LandjeServo::Init the frequency of the pulse changes to 122.4Hz and the duty cycle for OCR1A to approx 76% and for OCR1B to 47%.
So went digging further ... and could only find one difference between the INO and the library i am working on. The header file includes the Arduino.h to define uint8_t, digitalPinToBitMask, port and register names etc.
Is there somebody who can explain me why including the Arduino.h in the library screws up the timer settings while it does not in the ino file. The ino file obviously includes the Arduino.h by default since i am able to use the types uint8_t etc.