Python按钮打开/关闭日志记录

2024-05-03 14:03:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我想记录按下某个按钮的日期和时间。我只想让它记录(打印)一次。目前,由于while True:,它继续记录日志。如何将代码更改为只记录/打印一次操作

import RPi.GPIO as GPIO
import time
import datetime

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)

GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(27, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

while True:
    machine_1 = GPIO.input(22)
    machine_2 = GPIO.input(27)
    machine_3 = GPIO.input(17)

if machine_1 == True:
    date_time_1 = datetime.datetime.now().strftime('%y-%m-%d %H:%M:%S')
    split_datetime = date_time_1.split(" ")
    print "Machine 1 [ON]: ",split_datetime[0]," ",split_datetime[1]
time.sleep(0.2)

if machine_1 == False:
    date_time_1 = datetime.datetime.now().strftime('%y-%m-%d %H:%M:%S')
    split_datetime = date_time_1.split(" ")
    print "Machine 1 [OFF]: ",split_datetime[0]," ",split_datetime[1]
    time.sleep(0.2)

Tags: inimporttruedatetimedategpiotimesetup
1条回答
网友
1楼 · 发布于 2024-05-03 14:03:46

试试这个:

machine_1_prev = False
while True:
    machine_1 = GPIO.input(22)

    if machine_1 and not machine_1_prev:
        print("Machine 1 [ON]:", datetime.datetime.now().strftime('%y-%m-%d %H:%M:%S'))
    elif not machine_1 and machine_1_prev:
        print("Machine 1 [OFF]:", datetime.datetime.now().strftime('%y-%m-%d %H:%M:%S'))

    machine_1_prev = machine_1
    time.sleep(0.2)

我们所做的是让循环记住它看到machine_1引脚的最后一个状态,并对最后一个状态和当前状态之间的状态变化做出反应

0.2秒的延迟对于“去抖动”非常重要,当引脚被压下时,消除引脚在on和off之间快速切换的一小部分秒

这篇博文还有其他一些方法:http://shallowsky.com/blog/hardware/buttons-on-raspberry-pi.html

相关问题 更多 >