help with trying to pwm an output at 128hz for duty cycle 65%

I have a circuit I need to build...
basically I need to turn on an output
outputting pwm at 128hz and 65% duty cycle

I've read a few help articles, and dont quite understand how I can get it to output at 128hz...

128hz is the required pwm frequency for the device I am sending a signal to
potentially I would end up varying the output based on another input, changing the duty cycle depending on another variable, but I'm not at that point yet

I've read a few tutorials on setting the pwm frequency base, but none of the values match what I need it to do
like, I understand I could just use microseconds and turn it on and off based on that... but it would require 7812.5 microseconds I could do on for 5078 on and 2734 off as an example...and then just do a second run of it with 5079 on and 2734 off to make up the 0.5 that gets dropped off the first one

is there a more exact way to tell it to output 128hz pwm

I am using a nano board
Just looking for the best way to create the signal I need to send

I dont really have any code yet as I juts simply want to figure out and get the pwm frequency right before I wrote the other code I need as this is the only part I am unsure about at the moment

May this post (and library) can help?

On an Arduino UNO or Nano the system clock is16 MHz. 16 MHz / 128 kHz = 125 clocks per cycle. That is below 256 so it will work on any 8-bit or 16-bit timer. You set 'TOP' to 124 to get a 128 kHz output. Then you set the Output Compare Register to 65% of full range: 81. The Fast PWM mode will turn on the output pin when the timer is at 0 and turn it off when the timer reaches 81 so it will be on for 81/125ths (64.8%) of each 128 kHz cycle.

void setup()
  // Shut down the timer
  TCCR2A = 0;  // Clear Control Register A
  TCCR2B = 0;  // Clear Control Register B
  TIMSK2 = 0;  // Clear the Interupt Mask Register

  // Set up Waveform Generation Mode 7 (Fast PWM, TOP in OCR2A) by setting bits WGM20, WGM21,and WGM22
  TCCR2A |= (1<<WGM20) | (1<<WGM21);
  TCCR2B |= (1<<WGM22); // Yes, the three bits of WGM are SPLIT across two registers

  // Set the OC2B pin (Pin 5 on UNO or Nano) to turn on at 0 and off at OCR2B
  TCCR2A |= (1<<COM2B1);

  // Set the TOP to 124 to get 128 kHz ((16 MHz / 128 kHz)-1)
  OCR2A = 124; // 125 clocks per cycle

  // Set the PWM value to 65%
  OCR2B = 81;  // 125 * 0.65

  // Start the clock at full speed (16 MHz)
  TCCR2B |= (1<<CS20); 

void loop() {} // Nothing to do since the hardware does everything

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.