Put register setting into a loop for variable duty cycle PWM.

Hello, everyone.

I am very new to arduino programming. I am trying to generate PWM signal at 40kHz with duty cycle change between 0% to 50%. In other words, I am trying to turn this 40kHz singal on and off for every few periods. Is it doable to put the OCR1A setting into a loop to achieve this varable duty cycle?

Here is my code.

#include <avr/sleep.h>
#include <avr/power.h>

byte pattern = 0b10101010; //consecutive ports will have an opposite signal

void setup()
{
 //Port Registers: DDRC=>analog input pins, determine which pin is input/output, PORTC controls whether the pin is HIGH or LOW)
 DDRC = 0b00011111; //set pins A0 to A4 as outputs 
 PORTC = 0b00000000; //output low signal in all of them


 //
  // initialize timer1 
  noInterrupts();           // disable all interrupts
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1  = 0;

  ICR1= 399;              //16Mhz /(399+1) =40kHz In fast PWM top=ICR1, the output PWM frequency=timer clock/(ICR1+1) and the duty=OCR1A(B)/ICR1
  OCR1A = 199;            //Control PWM duty cycle %*ICR1
  TCCR1B |= (1 << WGM12);   // CTC mode
  TCCR1B |= (1 << CS10);    // 1 prescaler, no prescaling
  TIMSK1 |= (1 << OCIE1A);  // enable timer compare interrupt
  interrupts();             // enable all interrupts

  // disable ADC
  ADCSRA = 0;  
  
  // turn off everything we can
  power_adc_disable ();
  power_spi_disable();
  power_twi_disable();
  power_timer0_disable();
  power_usart0_disable(); 

//while(true); //avoid entering into the loop
}

ISR(TIMER1_COMPA_vect)          // timer compare interrupt service routine
{
  PORTC = pattern; //output portDV into ports 0 to 7
  pattern = ~pattern; //invert all the bits
}

void loop(){
//   if (OCR1A == 199)
      OCR1A == 79;
      delay(30);
  if (OCR1A == 79)
      OCR1A == 199;
      delay(30);  // something like...

}

Thank you very much!!!

  power_timer0_disable();

Bad idea, delay() depends on timer 0.

am trying to generate PWM signal at 40kHz with duty cycle change between 0% to 50%. In other words, I am trying to turn this 40kHz singal on and off for every few periods.

Describe in more detail what you're trying to achieve. A picture of the expected output might help too. What does "every few periods" mean? At the moment "few" means over 1000 in your sketch, not what the word usually stands for.

Have you tested if your sketch produces the PWM you expect? Every possibility I see in your described intention doesn't match what this sketch produces. But my interpretation might be wrong.

Please see attached file. I want something like that. Now I can have the TOP PWM shown in the picture, but not sure how to pause it and resume it after, for example, every 30ms.

Thanks.

Capture.JPG