[英]Script to read multiple raspberry pi input pins
我正在使用 Raspberry pi 3 Model B+ 和 Python 3 作為腳本。
我有 16 個紅外傳感器連接在板針上 - 針號(7、11、13、15、16、18、22、29、31、32、33、35、36、37、38、40)
每當任何 IR 傳感器接收到輸入時,它都應在現有計數器中加 1。 甚至多個傳感器同時觸發 - 它應該添加正確的結果。
我已經編寫了 python3 腳本來讀取一個引腳。 每當引腳檢測到 object 時,它就會在計數器中加 1。
我也有多個樹莓派板。 我將他們的序列號作為唯一 ID。
你能幫我同時理解/編寫多個傳感器嗎?
代碼片段:
import RPi.GPIO as GPIO
import time
sensor_list = [7, 11, 13, 15, 16, 18, 22, 29, 31, 32, 33, 35, 36, 37, 38, 40]
#print("IR Sensor Ready.....")
#print("..STATRED..")
sensor = 16
count_object = 0
def get_serial():
# Extract serial from cpuinfo file
cpuserial = "0000000000000000"
try:
f = open('/proc/cpuinfo','r')
for line in f:
if line[0:6]=='Serial':
cpuserial = line[10:26]
f.close()
except: cpuserial = "ERROR000000000"
return cpuserial
raspberry_serial = get_serial()
try:
while sensor:
GPIO.setmode(GPIO.BOARD)
GPIO.setup(sensor,GPIO.IN)
if GPIO.input(sensor):
count_object+=1
print(f"Total Objects: {count_object} counter on {raspberry_serial} for the sensor id {sensor}")
while GPIO.input(sensor):
time.sleep(0.2)
else:
pass
except KeyboardInterrupt:
GPIO.cleanup()
正如我將描述的那樣,我建議對您的核心循環進行一些更改。 我沒有測試過。
我不完全了解您要測量的內容或您的特定時序要求,所以我讓它每 0.2 秒讀取一次所有輸入。 我將繼續按照您的方式輪詢引腳更改。 但是,根據您的傳感器的行為方式,這可能會多次計算單個事件或完全錯過事件。 如果合適,您可能需要考慮觸發轉換事件。 還要確保檢查您的傳感器是否需要下拉。
我只是打印了計數。 您可以將其格式化為以任何您需要的方式包含您的董事會 ID。
import time
try:
# According to docs the import may raise an exception
import RPi.GPIO as GPIO
except RuntimeError:
print("Error importing RPi.GPIO! This is probably because you need superuser privileges. You can achieve this by using 'sudo' to run your script")
raise
sensor_list = [7, 11, 13, 15, 16, 18, 22, 29, 31, 32, 33, 35, 36, 37, 38, 40]
try:
# Initial setup for all pins only needs to be done once.
GPIO.setmode(GPIO.BOARD)
GPIO.setup(sensor_list, GPIO.IN)
# A separate counter initially zero for each input pin.
counts = { ch: 0 for ch in signal_list }
while True:
# flag changes in order to only report results when an event is detected
detected = False
for ch in signal_list:
if GPIO.input(ch):
detected = True
counts[ch] += 1
if detected:
print(counts)
# if an event remains high for more than 0.2 sec it might
# be counted again on the next loop. Likewise if an event
# comes and goes before the next loop it will be missed.
time.sleep(0.2)
finally:
GPIO.cleanup(sensor_list)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.