I want to write a program that can operate 2 gpio pins with different ON-OFF times at same time.

Say the time duration is 2 sec. In this time duration, I want to set GPIO 4 HIGH for 1 sec and LOW for 1 sec. And in that 2-sec same duration, I want to set GPIO 5 HIGH for 0.5 sec and LOW for 1.5 sec. I am not getting the logic on how to do this.

  • 1
    Comments are not for extended discussion; this conversation has been moved to chat. Comments should not be used to post answers. Thank you.
    – Ghanima
    Feb 8, 2020 at 15:47
  • 3
    you are overthinking this ... turn on 4&5 ... wait 1/2 sec .... turn off 5 .... wait 1/2 sec ... turn off 4 .... wait 1 sec
    – jsotola
    Feb 8, 2020 at 21:48
  • @jsotola, Yes, your trick is very clever very simple, very clean, and very appropriate for the OP's situation. My suggested multi-threading/multi-processing solutions are indeed overthinking, and very over-killing. Cheers.
    – tlfong01
    Feb 9, 2020 at 1:02
  • My big apologies to all those who might be misled by my proposed multi-processing solutions. As @jsotola is saying, I am overthinking. My over killing suggestion is indeed ALL WRONG for the OP's application. Actually I thought about other solutions, like using Rpi hard ware realtime clock module (DS3231), NTC network time and elapsed time, Rpi GCLK pin time counter etc etc, but they are all rubbish compared #jsotola's very simple, but perfect solution. #jsotola's accompanying explanation and example procedure is also very concise and clear, compared to my long winding, clumsy blah blah blahs.
    – tlfong01
    Feb 9, 2020 at 1:34
  • Is there any trick or program where I can give phase difference (in time) to gpio 4 signal? Means GPIO 4 will be for 1 sec ON and 1 sec OFF. GPIO 5 will be 0.5 sec OFF, then 1 sec ON and then 0.5 sec OFF. So phase difference will be 0.5 sec(In time). I am making 3 phase Inverter so in that switches signal is of 60 Degree phase difference Feb 21, 2020 at 13:14

1 Answer 1


Maintain a list of GPIO event times, e.g. a list containing a GPIO number, a time, and a new level for the GPIO.

GPIO Time Level
23   10.0   1
23   14.0   0
15   15.4   1
23   16.2   1
15   17.4   0
23   20.2   0

Run a main loop which executes regularly, say 10 times a second. Check if events are due. If any are process the event and then sleep for the loop period.

while true
   now = current_time
   for each event
      if now >= event.Time
         set GPIO event.GPIO to level event.Level
         delete event

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.