PWM buzzing with attiny13 and a MOSFET

I have an attiny13 driving a logic level MOSFET (IRL530) for controlling the brightness of an LED strip.

My problem is, I hear a buzzing when I change the duty cycle of the PWM on the pin0 with an potentiometer.

The code is quite simple.

int sensor = 3;
int output = 0;
int value = 0;

void setup()
{
  pinMode(sensor, INPUT);
  pinMode(output, OUTPUT);
}

void loop()
{
  value = analogRead(sensor);
  analogWrite(output,value/4);
}

I believe this buzzing is coming from the MOSFET. Most probably the frequency of the PWM signal is roughly in between 20-20.000Hz, so that I can hear it.

However, when I turn the potentiometer completely and give 100% duty cycle to PWM signal, I hear no buzzing. As I get close to the 100% Duty cycle this buzzing slowly fades away.

I think the frequency of the PWM signal should be fixed. So, how does the duty cycle affect the buzzing?

All these aside, I think setting the frequency of the PWM pin higher than 25kHz will make it ultrasonic and I will no longer be able to hear it.

So, how can I change the PWM frequency on the pin0?

Google “secrets of arduino PWM”, there’s a great page on it.

zoom:
I think the frequency of the PWM signal should be fixed. So, how does the duty cycle affect the buzzing?

Just like you hear when you turn your mains lamp dimmer up and down.

Paul__B:
Just like you hear when you turn your mains lamp dimmer up and down.

Ain't is supposed to be the frequency which leads to buzzing. Duty cycle is only the percentage of the high level signal in one period. So, when I turn the potentiometer, I only change the duty cycle, not the frequency. So, if the frequency is not audible already, it should be so for the whole duty cycle range from 0% to 100%.

What am I missing?

At zero, it never switches on, so no buzz. At 100%, it never switches off, so no buzz. Maximum buzz would presumably be around 50%, wouldn't it?


Oh, now as you move through the switching range, the shape of the square wave (or chopped sine wave in a mains dimmer) varies, so the harmonics of the sound changes, giving it different musical tones.

Paul__B:
At zero, it never switches on, so no buzz. At 100%, it never switches off, so no buzz. Maximum buzz would presumably be around 50%, wouldn't it?


Oh, now as you move through the switching range, the shape of the square wave (or chopped sine wave in a mains dimmer) varies, so the harmonics of the sound changes, giving it different musical tones.

Got it! Thank you.