PMW with duty cycle?

How would one program a 10Hz PWM to have a duty cycle from 0-100% in the Arduino IDE? Is it possible to do this in such a way that if I wanted a 50% duty cycle that the PWM would alternate like the first picture below? image

Someone else will have to help you with the frequency but analoWrite() is 8-bit PWM.

With 8-bits 100% is 255 so 50% is 127 or 128. (It's integer so you can't have 127.5).

Read this :

For such a low frequency, it may be easier to do it with software PWM, rather than the hardware timers.

10Hz = 100 milliseconds.
What input will trigger the change in duty cycle?

int i = 50;
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(100 - i);                    // 10 Hz = 100 millis
1 Like

I am seeing that the link @guix shared is for the Atmega IC timer, and the frequencies are very high. But I am using an esp32 and I saw this link: PWM example for LED that said one could use this code to accomplish the task

ledcSetup(0, 5000, 8); //(channel,frequency, bit resolution)
ledcAttachPin(2, 0); //(pin, channel)
ledcWrite(0, 127); //(channel, duty cycle [0-255]

@gerivega this is certainly an option and I think the first link that was posted refers to this as "bit banging a PWM". The disadvantage I see is that the duty cycle is not evenly distributed per unit time but is high at the beginning and low at the end of the time cycle. Seems like the quickest way to get the job done though.

but that's what duty cycle refers to -- over the period of the cycle, the output is HIGH during that % of the period staring at the beginning of the period which you specified is 100 msec (i.e. 10 Hz) as shown in your diagrams

of course the same average output would result at different frequencies if the output is on for the same % during each cycle

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