0

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
    use digitalWrite and set the pin HIGH for desired duration – Juraj May 1 at 10:11
  • AnalogWrite generates a series of pulses with a varying duty cycle. If you only want a single pulse, you should probably write the code manually. What range of pulse widths do you want, and with what precision and accuracy? – Duncan C May 1 at 11:43
  • As others have said, you could use digitalWrite() and the millis() 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 the digitalWrite() function, so you can make your timing more exact. And if you need sub-millisecond precision you could use the micros() function for your timing. – Duncan C May 1 at 11:44
  • Thank you for your replies and suggestions. I am trying to synchronize two neural recording systems. Therefore I am trying to generate those pulses with varying width and fixed time so I can align them later on offline, to set a proper off set time in data analysis. I was thinking of pulse widths (5-500)ms. – Kasia May 1 at 12:00
3

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
| improve this answer | |
  • I wonder why OP used analogWrite. – Juraj May 1 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 May 1 at 10:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.