Pulse generator with varying width I am trying to generate a square pulse with a fixed delay of 5 second between pulses and varying width of the pulse. The code I wrote so far generates a sequence of pulses every 5 seconds. Is it possible to generate one pulse (with varying width) every 5 seconds instead? Could you please help me with it?

const int pin =  11;

int i  = 0; 

void setup() {
    Serial.begin(9600);
    pinMode(pin, OUTPUT);
}

void loop() {
    i = random(0 , 255);
    analogWrite(pin, i); // turn on LED
    delay(5000);
}
Simple but not fully accurate:


Turn on LED
Delay for the amount of pulse width (e.g. 20)
Turn off LED
Delay 5000 ms - pulse width (20) thus 4980 in this example


However, since turn on/off a LED will also take some time, this will take slightly more than 20 + 4980 = 5000 ms.

Thus better is:


Set time to a variable (use millis function).
Turn on LED
Wait until time >= pulse width
Turn off LED
Wait until time >= 5000