gpt4 book ai didi

python - 使用设定时间触发运动功能

转载 作者:行者123 更新时间:2023-12-01 05:04:27 24 4
gpt4 key购买 nike

我正在制作自动狗喂食器,我希望用户能够设置预设时间,当到了这个时间时,设备将通过电机功能分配食物。

这是代码(60 行):

import RPi.GPIO as GPIO

import time

import datetime


PIN_MOTOR = 14

PIN_LIMITSENSOR = 15


GPIO.setmode(GPIO.BCM)

GPIO.setup(PIN_MOTOR, GPIO.OUT)

GPIO.setup(PIN_LIMITSENSOR, GPIO.IN, GPIO.PUD_DOWN)

GPIO.output(PIN_MOTOR, GPIO.LOW)


def doCycle():

GPIO.output(PIN_MOTOR, GPIO.HIGH)

while not GPIO.input(PIN_LIMITSENSOR):

time.sleep(0.2)

GPIO.output(PIN_MOTOR, GPIO.LOW)

time.sleep(3)

def hour():

return int(datetime.now().hour)


def minute():

return int(datetime.now().minute)


option = raw_input("Would you like manual or automatic mode [manual/auto]?: ")

if option == "manual":

while True:

selection = str(raw_input("How big is your dog (small/medium/large/exit)?: "))

if selection == "small":

doCycle()

elif selection == "medium":

doCycle()

doCycle()

elif selection == "large":

doCycle()

doCycle()

doCycle()

elif selection == "exit":

break

else:

print("Invalid selection")

else:
print("Automatic mode selected.")

schedhr = int(raw_input("Please enter the hour to schedule: "))

schedmin = int(raw_input("Please enter the minute to schedule: "))

iterations = 1

selection = str(raw_input("How big is your dog (small/medium/large)?: "))

if selection == "small":

iterations = 1

elif selection == "medium":

iterations = 2

elif selection == "large":

iterations = 3

print("Now scheduled to do " + str(iterations) + "cycles at "+str(schedhr)+":"+str(schedmin))

while (hour() != schedhr) or (schedmin != minute()):

time.sleep(1)

for x in xrange(iterations):

print ("Doing cycle.")

doCycle()

这是错误消息:

Automatic mode selected.

Please enter the hour to schedule: 19

Please enter the minute to schedule: 00

How big is your dog (small/medium/large)?: small

Now scheduled to do 1cycles at 19:0

Traceback (most recent call last):

File "code4.py", line 59, in

while (hour() != schedhr) or (schedmin != minute()):

File "code4.py", line 22, in hour

return int(datetime.now().hour)

AttributeError: 'module' object has no attribute 'now'

最佳答案

datetime 模块包含同名的 datetime 类,其中 now() 是一个类方法。

因此,要调用 now() 并返回日期时间实例,您需要在第 22 行中编写:

datetime.datetime.now().hour 

或者,如果您只是从 datetime 类调用方法,通常会编写 from datetime import datetime 而不是仅导入模块名称(那么您需要不要更改第 22 行)。

关于python - 使用设定时间触发运动功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25338661/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com