阅读覆盆子pi的gpio别针

时间:2018-01-06 19:06:08

标签: python csv

我正在使用8通道中继,使用raspberry pi 3并在python中编程。我想读取或感知引脚,如果它们每5秒钟或低,并在.txt或.csv文件中打印输出。对于单引脚我已经附加了代码,它工作正常,但我如何扩展到所有8个通道(继电器)。请帮帮我 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列用于与继电器连接的引脚状态。 我的输出应该是这样的 6月1日/ 2018,18:54:00,1,0,1,1,1,0,0,0
6月1日/ 2018,18:54:05,1,0,1,1,1,0,0,0
6月1日/ 2018,18:54:10,1,0,1,1,1,0,0,0
6月1日/ 2018,18:54:15,1,0,1,1,1,0,0,0
6月1日/ 2018,18:54:20,0,0,0,0,0,0,0,0

1 个答案:

答案 0 :(得分:2)

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);