Skip to content

hertz()

Arnd edited this page Jan 20, 2021 · 2 revisions

hertz( {value} );

This function defines the LED refresh rate, defaulting to 30Hz. Since the PWM is done in software using interrupts, the higher the interrupt frequency the more CPU cycles are used and fewer CPU time is left for the main program. At lower refresh speeds and with certain LEDs at lower PWM rates there will be noticeable flickering, requiring a higher refresh rate. This value should be set as low as possible in order to give the main program as much CPU time as possible.

Although the hertz() function can be called with any instance, the value is global - all LEDs use the same hertz rate and the Hz rate is always set to the value in the most recent call to the hertz() function.

The routine uses the following formula to compute the highest legal Hertz value; any values higher (or 0) will result in using this value:

Maximum Hertz = 120Hz - (10 * {number of LEDs});

The following chart shows how much CPU is used for some typical configurations.

Program slowdown chart for a 16MHz Arduino:
(all pins at 50% duty cycle)
Hertz 1 LED% 2 LEDs% 3 LEDs% 4 LEDs% 5 LEDs% 6 LEDs%
off 0% 0% 0% 0% 0% 0%
20 15.7% 21.0% 26.7% 33.0% 40.0% 47.8%
25 20.5% 27.7% 35.8% 45.1% 55.7% 68.0%
30 25.6% 35.2% 46.3% 59.4% 75.2% 94.3%
35 31.3% 43.7% 58.6% 77.1% 100.5% 131.0%
40 37.3% 53.1% 72.9% 98.7% 133.5% 183.0%
45 44.1% 64.1% 90.5% 127.1% 181.1% 268.7%
50 51.6% 76.8% 112.0% 164.9% 252.7% 427.8%
55 59.7% 91.3% 138.4% 216.3% 369.8% 812.5%
60 69.0% 108.9% 173.2% 295.2% 613.2% -
65 79.4% 129.7% 219.4% 424.1% - -
70 90.9% 155.0% 283.6% 674.3% - -
75 104.3% 187.0% 382.1% - - -
80 119.5% 227.9% 547.1% - - -
85 136.5% 279.6% 861.6% - - -
90 159.0% 361.7% - - - -
95 183.7% 476.0% - - - -
100 213.2% 661.7% - - - -

Any PWM value where the program slowdown is >1000% (meaning the program is 10x slower or just 1/10 of the time goes to the program and the rest is spent servicing PWM) is deemed unacceptable and isn't shown on the chart. If the program does nothing but waiting in "delay()" or similar loops then this would still work.


Example:

...    
...    
smoothLED Board, Red;  // Instantiate 2 LEDs     
const uint8_t RED_PIN{11};
...    
...    
Serial.print(F("BOARD LED: "));
if (Board.begin(LED_BUILTIN)) // Start the "Board" instance on pin 13
  Serial.println(F("OK"));
else
  Serial.println(F("ERROR!"));
Board.set(512); // set to 50% duty cycle
Serial.print(F("BOARD LED: "));
if (Red.begin(RED_PIN,INVERT_LED)) // Red pin inverted
  Serial.println(F("OK"));
else
  Serial.println(F("ERROR!"));
Red.set(0); // Turn pin off
Red.hertz(40); // Set refresh rate to 40Hz
...    
...