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
Raspberry Pi requires membership for participation - click to join
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 664 subscribers
  • Views 3603 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
  • john2674
    0 john2674 over 5 years ago in reply to john2674

    Well Im not giving up yet, but I really want to make some advancement on the mechanical side of my project while i am on holiday. So for now i am thinking of running 2 seperate raspberry pis. for now 1 will run the 2 always on relays and the on 5 minute on and then off timer. and the second will run the feed timer.

    this should give me the control i need for testing! and as long as my 5volt power supply is adequate i should be able to power the 2nd pi from the vcc rail...i think.

    I do agree that an arduino is probably better suited for this project, but A i dont have one and B im looking into using the wifi and posibbly bluetooth capabilities of the pi as the project matures. I do however have a parts drawer with several pi zerow's laying in it image.

    I work a a small community college and when school resumes i plan on visiting with the computer teacher , and seeing if he will let me sit in on some coding clases or possibly offer me some tutoring on my specific project. I am a teacher myself , but i teach heavy equipment operating. not much help in this area lol.

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

    Since the Pi runs an operating system you can have multiple Python scripts running on a single Pi  at once — almost as if there were multiple computers. You could start and stop them from a bash shell or write a little script to do it.

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

    will do

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

    I really like that idea! ive heard about bash scripts. might be just what i need for this! i have to step away from my pc for a while to do some christmas activities, but i will look into that as soon as i return! ohh and while i was at it i signed up for an online course through my school titled introduction to python!

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

    btw, dont give up :-).  What you are trying to do is within your capabilities.  It is great that you have access to someone knowledgeable to talk to and that is very useful but don’t hesitate to post here as well if needed.

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • 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
  • john2674
    0 john2674 over 5 years ago in reply to fmilburn

    SUCCESS!! WOOT! WOOT!

    i wrote 2 simple scripts and used the & command in the bashrc file that way it starts on boot.

    its very ugly but it is working!

    And ohh i dont plan on giving up!  i plan to keep learning and keep improving this program and hopefully many more to come!

    I cant thank all of you who have chimed in and offered me help enough! i plan on looking into all the samples you have provided and using them as teaching aids for myself as my abilities progress!

    i plan on reporting back here as the project progresses and will probably have many more questions to come!

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

    Thanks for posting that Shabaz.  My experience with Python is limited and I am coming back to it after quite a bit of time away and am not familiar with the asyncio library.  Will check it out...

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

    Hi Frank,

     

    Thanks! It is new to me too, not sure I like it or if I'm using it correctly, apparently it's the new way to do asynchronous stuff. Much of the documentation for it, perhaps because it is recent, expects a higher level of knowledge than I had..

    For simple stuff JavaScript has a 'setTimer' capability to create a type of tick function. It isn't pretty either, but at the end of the day we're trying to replicate a simple old-school timer interrupt type capability, rather than require a decent app framework so it's not so bad I guess..

    • Cancel
    • Vote Up +1 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
<>
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