Electronic – Arduino- Duty Cycle Changing When Frequency Is Increasing

arduinobuttonfrequencypwm

I’m currently trying to increase the frequency from a pin from an Arduino using PWM. I’m using the Timer1 library as it has functions to output signals.

I connected a push button to my Arduino and this is meant to increase the frequency of the pin once pressed . But every time the button is pressed, the duty cycle is also changed. Also the frequency changes multiple when the button is pressed. I think that has something to do with the lastButtonState logic.
I was wondering if there’s anything that can implemented in my code that can increase the frequency but keep the duty cycle the same.
Thanks in advance.

#include <TimerOne.h>

int buttonState = 0;
int lastButtonState = 0;
int period = 1000;
int sig_out = 9;
int sig_out2 = 10;
int button =2;

void setup() {

  pinMode(button,INPUT_PULLUP);
  pinMode(sig_out, OUTPUT);
  //pinMode(sig_out2, OUTPUT);
  Timer1.initialize(1000);
  Timer1.pwm(sig_out,507,period);
  Serial.print(period);
  //Timer1.pwm(sig_out2,456,900);
}
void loop(){
    buttonState = digitalRead(button);
  if (buttonState != lastButtonState){
     lastButtonState = buttonState;
     if (buttonState == 1){
      period -= 10;
      Timer1.setPeriod(period);  
     }
  }
}

Schematic

Best Answer

If you look at the Timer1.pwm() function call you will see that you are providing two timing parameters: the duty factor and the period. Both of these are specified as an integer number of clock cycles...the duty factor is not given as a percentage of the period.

So, when you change the period the output pin stays high for the same number of clock cycles that you specified in Timer1.pwm(), which effectively changes the duty factor. If you want to keep the duty factor constant then you need to call Timer1.pwm every time you change the period and give it a newly calculated value for the second parameter.