python - 读取树莓派的GPIO引脚

标签 python csv

我正在使用 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/

相关文章:

php - 使用上传的 CSV 中的值创建/填写表单

java - csv文件中一列的最大长度是多少?

java - 将 java.util.List 转换为 ResultSet?

mysql - Sql 查询从 csv 数据库获取票价

javascript - 如何使用 Javascript 或 Java 获取 CSV 动态更改的实际数字

python - 代码只正确运行了一半,并且在 f_num=num+num_rev 点处,这里输出只有 num_rev 而不是 f_num

python - 将包含矩阵对角线以下元素的列表转换为完整矩阵

python - Django 反向 URL 查找模板错误

python - lstrip(), rstrip() 用于列表

c++ - 用于嵌入式脚本/文本处理引擎的 Python vs Lua