Weird sound when modulating the pulse width on Arduino I'm trying to generate a pulse width modulated sound using Arduino Nano.

But it generates the weird sound unlike my expectation.

Here's my code:

class Phasor
{
public:
    Phasor(const float frequency)
    :frequency(frequency)
    ,phase(1.0f)
    ,lastTimeMicros(0){};
    virtual ~Phasor(){};
    void setFrequency(const float frequency)
    {
        this-&gt;frequency = frequency;
    }
    float process()
    {
        const unsigned long currentTimeMicros = micros();
        if (phase == 1.0f) lastTimeMicros = currentTimeMicros;
        const unsigned long elapsedTimeMicros = currentTimeMicros - lastTimeMicros;
        const unsigned long cycleDurationMicros = static_cast&lt;unsigned long&gt;(1000.0f / frequency) * 1000;
        if (elapsedTimeMicros &lt; cycleDurationMicros)
            phase = static_cast&lt;float&gt;(elapsedTimeMicros) / static_cast&lt;float&gt;(cycleDurationMicros);
        else
            phase = 1.0f;
        return phase;
    }
private:
    float frequency;
    float phase;
    unsigned long lastTimeMicros;
};

class PulseOsc
{
public:
    PulseOsc(const float frequency, const float pulseWidth)
    :phasor(frequency)
    ,pulseWidth(pulseWidth){};
    virtual ~PulseOsc(){};
    void setFrequency(const float frequency)
    {
        this-&gt;phasor.setFrequency(frequency);
    }
    void setPulseWidth(const float pulseWidth)
    {
        this-&gt;pulseWidth = pulseWidth;
    }
    float process()
    {
        const float phase = phasor.process();
        if (phase &lt;= pulseWidth)
            return 1.0f;
        else
            return -1.0f;
    }
private:
    Phasor phasor;
    float pulseWidth;
};

Phasor *phasorLFO;
PulseOsc *pulseOsc;

void setup()
{
    Serial.begin(9600);
    pinMode(9, OUTPUT);
    phasorLFO = new Phasor(0.1f);
    pulseOsc = new PulseOsc(440.0f, 0.5f);
}

void loop()
{
    pulseOsc-&gt;setPulseWidth(phasorLFO-&gt;process());
    int outVal = LOW;
    if (pulseOsc-&gt;process() &gt; 0.0f) outVal = HIGH;
    digitalWrite(9, outVal);
}


The resulting sound is very weird and glitchy.
It works fine when I fix the pulse width value. (without LFO)

What is wrong with my code?
How do I fix this? I would appreciate any advice.
Seems like you are using the system clock micros() to  calculate elapsedTimeMicros, so probably the time spent on the process of calculation and sending signal to the pin may affect it, which may lead to inconsistent duty cycle.