Python Script To Monitor RASPI GPIO

I’d like write a Python script to run on on a Raspberry Pi (3B+) to monitor several GPIO pins for an external button press.

When a button is pressed (shorted to 0 volts), I would like another GPIO output to trigger a Sainsmart relay card, to trigger a relay momentarily, and send an email when this occurs.

I have this working for ONE input and ONE output. Here’s that code:

import RPi.GPIO as GPIO
import time
import smtplib

GPIO.setmode(GPIO.BCM)

GPIO.setwarnings(False)

# Set GPIO 17 to act as input, and set it's state...this is the pins for the button
GPIO.setup(17,GPIO.IN, pull_up_down=GPIO.PUD_UP)
# Set GPIO 2 as an output, this will trigger the Sainsmart relay card 
GPIO.setup(2,GPIO.OUT)
GPIO.output(2,GPIO.HIGH)

while True:
# monitor the status of the INPUT GPIO 17, when button is preessed, trigger GPIO 2 OUTPUT
    input_state = GPIO.input(17)
    if input_state == False:
        print('Button Pressed')
        GPIO.output(2, GPIO.LOW)
        print ("RELAY FIRED")
        time.sleep(1.0);
        GPIO.output(2, GPIO.HIGH)
        time.sleep(0.5)
        # initialize connection to our email server we will use  here
        smtp = smtplib.SMTP('server.com', port='587')
        smtp.ehlo()  # send the extended hello to our server
        smtp.starttls()  # tell server we want to communicate with TLS encryption
        smtp.login('[email protected]', 'passwordhere')  # login to our email server
        # send our email message 'msg' to our boss
        smtp.sendmail('[email protected]', ['[email protected]', '[email protected]'], "Content Of Email")
        smtp.quit()  # finally, don't forget to close the connection
        time.sleep(0.5)
GPIO.cleanup()

How can I add additional INPUT and OUTPUT GPIO’s to this? Fairly new with Python. Worst case, I’ll just write eight scripts and run them all, all the time.

Right now, you have one pin each and store them in one place each.
If you want to use multiple pins (possibly for multiple purposes) a data structure such as an array would come in handy.
Arrays can hold multiple elements and allow you to easily access them sequentially.
Here’s an example, based on your code:

import RPi.GPIO as GPIO
import time
import smtplib

# Setup
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

# Define your input and output GPIO pins
input_pins = [17, 27]  # Replace with your input GPIO numbers
output_pins = [2, 3]   # Replace with your output GPIO numbers

# Setup GPIO inputs and outputs
for pin in input_pins:
    GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

for pin in output_pins:
    GPIO.setup(pin, GPIO.OUT)
    GPIO.output(pin, GPIO.HIGH)

try:
    while True:
        # Loop through each input pin and check its state
        for i, input_pin in enumerate(input_pins):
            input_state = GPIO.input(input_pin)
            if input_state == False:
                print(f'Button {i + 1} Pressed')
                GPIO.output(output_pins[i], GPIO.LOW)
                print(f"RELAY {i + 1} FIRED")
                time.sleep(1.0)
                GPIO.output(output_pins[i], GPIO.HIGH)
                time.sleep(0.5)

                # Send an email
                smtp = smtplib.SMTP('server.com', port='587')
                smtp.ehlo()
                smtp.starttls()
                smtp.login('[email protected]', 'passwordhere')
                smtp.sendmail('[email protected]', ['[email protected]', '[email protected]'], f"Button {i + 1} Pressed - Content Of Email")
                smtp.quit()
                time.sleep(0.5)

except KeyboardInterrupt:
    # Clean up GPIO on CTRL+C exit
    GPIO.cleanup()
finally:
    # Clean up GPIO on normal exit
    GPIO.cleanup()

This example loops through the array of input pins and checks each one individually.
If you’d want to send emails to different recipients, a dict (different data structure) might be better suited.

2

Here is an example of watching multiple lines using gpiod (the Python bindings for libgpiod).

You are only interested in the input going low so for the line settings use edge_detection=Edge.FALLING rather than edge_detection=Edge.BOTH,
and for the pull-up add bias=Bias.PULL_UP.

You can include the output lines in the same request, or do them separately as per the toggle_line_value.py example.

So, say for lines 17 and 27, it could be something like:

import gpiod
from gpiod.line import Bias, Direction, Edge, Value

input_lines = (17, 27)
output_lines = (2, 3)
with gpiod.request_lines(
    "/dev/gpiochip0",
    config={
        input_lines: gpiod.LineSettings(bias=Bias.PULL_UP, edge_detection=Edge.FALLING), 
        output_lines: gpiod.LineSettings(direction=Direction.OUTPUT, output_value=Value.ACTIVE)},
    ) as request:
        while True:
            for event in request.read_edge_events():
              # do whatever based on the event
              if event.line_offset == 17:
                  # fire relay
                  request.set_value(2, Value.INACTIVE)
                  # ...

That is using the latest gpiod which you can install using:

pip install gpiod

And it doesn’t waste CPU cycles polling.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật