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);
}
1 Answer 1
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
-
I wonder why OP used analogWrite.2020年05月01日 10:41:05 +00:00Commented May 1, 2020 at 10:41
-
@Juraj I assume he wants a 'random' pulse width (PWM) generated. so the pulse width I use in my example is some random time the OP should use.Michel Keijzers– Michel Keijzers2020年05月01日 10:48:56 +00:00Commented May 1, 2020 at 10:48
digitalWrite()
and themillis()
function to get decent precision and accuracy. If you need higher precision and accuracy though you may want to switch to using port registers to manipulate the pin directly. That is significantly faster to respond than thedigitalWrite()
function, so you can make your timing more exact. And if you need sub-millisecond precision you could use themicros()
function for your timing.