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 3716 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
Parents
  • shabaz
    0 shabaz over 5 years ago

    Hi John,

     

    The periodic counter/tick system recommended by Frank and Cris is a decent way to implement this.

    For what it's worth, here's some code just tried - it too uses a tick, in this case using some 'asyncio' library.

    This only works with very recent versions of Python though (Python 3.8, and perhaps Python 3.7).

     

    The beginning bit (lines 1-32) just sets up the framework for the ticks. Lines 33 onward handle the relay logic.

    There is a tick for 1 second, a tick for 10 seconds, and a tick for 60 seconds. I just used the 1 second and 60 second ticks.

     

    I'm a Python beginner (I don't like it much but slowly beginning to appreciate its usefulness) so I'm sure there are better ways to do it in Python, but this seemed to work. You'd need to replace or augment the lines containing print messages, to perform the actual relay switching.

    It outputs a dot every second, a D every 10 seconds, and an M every 60 seconds, and a relay-related message after 3, 8 seconds and 5 minutes.

     

    The program starts at line 67, because everything above it are functions.

     

    #!/usr/bin/python3.8
    import asyncio
    
    
    PERIOD = 1.0
    FOREVER = True
    counter=0
    
    
    # these three variables become 1 when 1, 10 or 60 seconds expire
    event1=0
    event10=0
    event60=0
    
    
    # counters for relays. rel1ctr counts in seconds, rel2ctr counts in minutes
    rel1ctr=0
    rel2ctr=0
    
    
    # tick routine. This updates the event variables
    async def tick():
      await asyncio.sleep(PERIOD)
      global counter, event1, event10, event60
      counter=counter+1
      if (counter%10==0):
        event10=1
      if (counter%60==0):
        event60=1
        counter=0
      event1=1
    
    
    # main function which checks the event variables and handles the relay states
    async def mainprog():
      global event1, event10, event60
      global rel1ctr, rel2ctr
      await asyncio.sleep(0.1)
    
    
      if (event1):
        event1=0
        print(".")
        rel1ctr=rel1ctr+1
        if (rel1ctr==3): # 3 seconds expired?
          print("relay 1 ON")
        if (rel1ctr>=8): # 3+5=8 seconds expired?
          print("relay 1 OFF")
          rel1ctr=0 # set back to zero so we can repeat the sequence for relay 1
    
    
      if (event10):
        event10=0
        print("D")
    
    
      if (event60):
        event60=0
        print("M")
        rel2ctr=rel2ctr+1
        if (rel2ctr>=5): # 5 minutes expired?
          print("relay 2 OFF")
    
    
    
    
    print("set relay 1 off")
    print("set relay 2 on")
    print ("set relay 3 on")
    print ("set relay 4 on")
    while FOREVER:
      asyncio.run(tick())
      asyncio.run(mainprog())

    • Cancel
    • Vote Up +3 Vote Down
    • Sign in to reply
    • Verify Answer
    • Reject Answer
    • Cancel
  • clem57
    0 clem57 over 5 years ago in reply to shabaz

    shabaz your usage of https://docs.python.org/3/library/asyncio.html  does fit the Python language. My only question is why divide the Ticks from the mainprog logic? They could be done in just one routine as the .1 divides period 1.0 in exactly 10.

    Thanks,

    Clem

    • Cancel
    • Vote Up +3 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
Reply
  • clem57
    0 clem57 over 5 years ago in reply to shabaz

    shabaz your usage of https://docs.python.org/3/library/asyncio.html  does fit the Python language. My only question is why divide the Ticks from the mainprog logic? They could be done in just one routine as the .1 divides period 1.0 in exactly 10.

    Thanks,

    Clem

    • Cancel
    • Vote Up +3 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
Children
  • 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
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