我正在制作自动喂狗器,我希望用户能够设置一个预设的时间,当时间到了,设备将通过一个电机功能分配食物。在
这是代码(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
类调用方法,那么通常是编写from datetime import datetime
,而不是只导入模块名(那么就不需要更改第22行)。在相关问题 更多 >
编程相关推荐