我正在使用 8 channel 继电器,带有树莓派 3 和 python 编程。我想每 5 秒读取或感测引脚是否处于低电平,并在 .txt 或 .csv 文件中打印输出。对于单引脚,我已附加代码,它工作正常,但我如何扩展到所有 8 个 channel (继电器)。
Python 代码:
import time
from time import sleep # Allows us to call the sleep function to slow down
our loop
import RPi.GPIO as GPIO # Allows us to call our GPIO pins and names it just
GPIO
GPIO.setmode(GPIO.BCM) # Set's GPIO pins to BCM GPIO numbering
INPUT_PIN = 26 # Write GPIO pin number.
GPIO.setup(INPUT_PIN, GPIO.IN) # Set our input pin to be an input
# Start a loop that never ends
while True:
if (GPIO.input(INPUT_PIN) == True):
# load is turned off.
print (time.strftime ("%Y/%m/%d , %H:%M:%S"),"0")
else:
#now 20 watt load is turned ON!.
print(time.strftime ("%Y/%m/%d , %H:%M:%S"),"20")
sleep(10); # Sleep for 10 seconds.
我想将所有数据保存在 .csv 或 .txt 文件中,并在开始处加上时间戳,以及与继电器连接的引脚状态的其他 8 列。
我的输出应该如下所示:
06/01/2018,18:54:00,1,0,1,1,1,0,0,0
06/01/2018,18:54:05,1,0,1,1,1,0,0,0
06/01/2018,18:54:10,1,0,1,1,1,0,0,0
06/01/2018,18:54:15,1,0,1,1,1,0,0,0
06/01/2018,18:54:20,0,0,0,0,0,0,0,0
最佳答案
import csv
import time
from time import sleep
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
INPUT_PINS = [26, 27, 28, ] # FILL ALL 8 PIN NUMBERS HERE
[GPIO.setup(pin, GPIO.IN) for pin in INPUT_PINS]
while True:
output = []
for pin in INPUT_PINS:
if (GPIO.input(pin) == True):
# load is turned off.
value = 0
else:
#now 20 watt load is turned ON!.
value = 20
output.append(value)
with open('logs.csv', 'wa') as csvfile:
logcsv = csv.writer(csvfile, delimiter=',')
logcsv.writerow([time.strftime ("%Y/%m/%d , %H:%M:%S")] + output)
sleep(10);
关于python - 读取树莓派的GPIO引脚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48130844/