user66011: 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);
}


user31105: 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


66011: <p>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?</p>

<pre class="lang-cpp prettyprint-override"><code>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);
}
</code></pre>
 31105: <p>Simple but not fully accurate:</p>

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

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

<p>Thus better is:</p>

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