Skip to main content
 首页 » 编程设计

python之读取树莓派的gpio引脚

2024年09月07日12tintown

我正在使用 8 channel 中继,使用 raspberry pi 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);