element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
Raspberry Pi
  • Products
  • More
Raspberry Pi
Raspberry Pi Forum Writing threads into code for 4 channel relay on pi
  • Blog
  • Forum
  • Documents
  • Quiz
  • Events
  • Polls
  • Files
  • Members
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Join Raspberry Pi to participate - click to join for free!
Featured Articles
Announcing Pi
Technical Specifications
Raspberry Pi FAQs
Win a Pi
Raspberry Pi Wishlist
Actions
  • Share
  • More
  • Cancel
Forum Thread Details
  • State Suggested Answer
  • Replies 26 replies
  • Answers 9 answers
  • Subscribers 661 subscribers
  • Views 3724 views
  • Users 0 members are here
  • rasberry_pi_3_b_plus
Related

Writing threads into code for 4 channel relay on pi

john2674
john2674 over 5 years ago

Hi i am a super noob at all things PI, i have done a few simple projects. That said coding is really new to me. Ive read python for dummies and quite a few articles on the web so far, but my latest project im stuck.

Im trying to write a code to controll a 4 channel relay board with my pi. But i want my relays to turn off and on at different intervals independant of each other. So far i think i need to use threading commands, but im not sure how to write them? As an example of what im trying to accomplish.

Relay 1 on 3 seconds off 5 seconds repeating forever

Relay 2 on 5 minutes then off permanently

Relay 3 on permanently

Relay 4 on permanently

 

If anybody can point me in a direction where i can learn these code commands i will be super grateful!

Ive tried searching all over and cant find what i need. Im sure i just need to get better at searching though lol.

  • Sign in to reply
  • Cancel
  • shabaz
    0 shabaz over 5 years ago in reply to clem57

    Hi Clem,

     

    You're right, no need to separate it. I just did it to make it look like a timer ISR (the tick function) and the main code. With a microcontroller I would have separated it, so the ISR is never hung for a long time, so I just repeated with the Python code, i.e. the tick will always execute fast, whereas the main code can be slow if desired. In the OP use-case there's no need for that as you say.

    • Cancel
    • Vote Up +4 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • john2674
    0 john2674 over 5 years ago in reply to shabaz

    setting up another pi so i can play with some codes. i think i will start with yours shabaz. i actually have an old laptop somewhere with ubuntu on it also, maybe ill dig it out and update and use it for practice.

    • Cancel
    • Vote Up +2 Vote Down
    • Sign in to reply
    • Verify Answer
    • Reject Answer
    • Cancel
  • easyejl
    0 easyejl over 5 years ago

    I guess my question is whether the threads have to be aware of each other at all for any reason? if not, it isn't too bad. Coordinating communication between threads on the other hand is a total nightmare image

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • Sean_Miller
    0 Sean_Miller over 5 years ago

    Here's a working little ditty using threading.  Just change the "print" commands to a command for however you are switching the relays:

     

    import threading, time
    
    def relay1():
            while (True):
                    print("Relay 1 on!\n")
                    time.sleep(3)
                    print("Relay 1 off!\n")
                    time.sleep(5)
    
    def relay2():
            print("Relay 2 on!\n")
            time.sleep(300) #(5 x 60 =300 seconds)
            print("Relay 2 off!\n")
    
    # main execution
    relay1_thread=threading.Thread(target=relay1)
    relay2_thread=threading.Thread(target=relay2)
    
    relay1_thread.start()
    relay2_thread.start()
    print("Relay 3 On!")
    print("Relay 4 On!")

     

    Reference:  https://docs.python.org/3/library/threading.html

     

    See ya',

    Sean

    • Cancel
    • Vote Up +3 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • windsorperma
    0 windsorperma over 5 years ago in reply to Sean_Miller

    Check with...Python Multithreading

    • Cancel
    • Vote Up +2 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • ambitionhost
    0 ambitionhost 2 months ago

    Hi

    You're on the right track with threading! Since each relay operates independently, using threads will allow them to run at different intervals without blocking each other.

    Here’s a simple Python script to control your 4-channel relay board using a Raspberry Pi and the GPIO library:

    Steps to Follow:

    1. Install RPi.GPIO if not already installed:

      bash
      CopyEdit
      pip install RPi.GPIO
    2. Connect your relay board to the Raspberry Pi GPIO pins.

    3. Use threading to handle different relay timings.


    Python Code for Relay Control

    python
     
    import RPi.GPIO as GPIO import time import threading # Pin definitions (adjust based on your setup) RELAY_1 = 17 # GPIO pin numbers RELAY_2 = 27 RELAY_3 = 22 RELAY_4 = 23 # GPIO setup GPIO.setmode(GPIO.BCM) GPIO.setup([RELAY_1, RELAY_2, RELAY_3, RELAY_4], GPIO.OUT, initial=GPIO.LOW) # Function for Relay 1 (on 3s, off 5s forever) def relay_1_control(): while True: GPIO.output(RELAY_1, GPIO.HIGH) time.sleep(3) GPIO.output(RELAY_1, GPIO.LOW) time.sleep(5) # Function for Relay 2 (on 5 minutes, then off permanently) def relay_2_control(): GPIO.output(RELAY_2, GPIO.HIGH) time.sleep(300) # 5 minutes GPIO.output(RELAY_2, GPIO.LOW) # Function for Relay 3 (always on) def relay_3_control(): GPIO.output(RELAY_3, GPIO.HIGH) # Function for Relay 4 (always on) def relay_4_control(): GPIO.output(RELAY_4, GPIO.HIGH) # Create and start threads thread_1 = threading.Thread(target=relay_1_control) thread_2 = threading.Thread(target=relay_2_control) thread_1.start() thread_2.start() # Run Relay 3 & 4 directly (since they stay ON) relay_3_control() relay_4_control() # Keep the main thread running to prevent exit try: while True: time.sleep(1) except KeyboardInterrupt: GPIO.cleanup() # Clean up GPIO on exit print("GPIO Cleanup Done!")

    Explanation of the Code:

    • Relay 1 cycles every 3s ON / 5s OFF using a loop in a thread.

    • Relay 2 turns ON for 5 minutes, then OFF permanently.

    • Relay 3 & 4 stay ON permanently.

    • Threads allow independent timing for each relay.

    • GPIO.cleanup() ensures safe shutdown when stopping the script.


    Next Steps:

    • If you need more advanced control, look into asyncio or multi-threading queues.

    • Try adding a button or web interface to control the relays interactively.

    Let me know if you need any modifications!

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
<
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2025 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

ICP 备案号 10220084.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube