raspberry pi 如何使用定时器控制 LED 的开关持续时间
how to use timer to control on off duration of a LED in raspberry pi
我想使用定时器来控制 LED 的开/关持续时间。我写了下面的代码,但它没有 运行.
def main ():
LED =27
GPIO.setup(LED, GPIO.OUT)
while (True):
now = datetime.datetime.now()
todayon = now.replace(hour = 17, minute=47, second =0, microsecond =0)
todayoff = now.replace(hour = 17, minute=48, second =0, microsecond =0)
turnon = now>todayon
turnoff = now>todayoff
if(turnon == True):
GPIO.output(LED, GPIO.HIGH)
time.sleep(1)
GPIO.output(LED, GPIO.LOW)
time.sleep(1)
if(turnoff == True):
GPIO.output(LED, GPIO.HIGH)
如果它没有 运行(什么都不做),可能是因为您从未调用 main
在这种情况下,在底部添加以下行:
if __name__ == '__main__':
main()
此外,您需要设置 GPIO 以使用端口号或引脚号。
使用 GPIO.setmode(GPIO.BCM)
将模式设置为端口号,因此当您调用 GPIO.setup(LED, GPIO.OUT)
.
时,GPIO 端口号 27 将用作输出
完整的脚本现在应该如下所示:
#!/usr/bin/python
import time
import datetime
import RP1.GPIO as GPIO
def main ():
LED =27
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED, GPIO.OUT)
while (True):
now = datetime.datetime.now()
todayon = now.replace(hour = 17, minute=47, second =0, microsecond =0)
todayoff = now.replace(hour = 17, minute=48, second =0, microsecond =0)
turnon = now>todayon and now<todayoff
turnoff = now>todayoff
if(turnon == True):
GPIO.output(LED, GPIO.HIGH)
time.sleep(1)
GPIO.output(LED, GPIO.LOW)
time.sleep(1)
if(turnoff == True):
GPIO.output(LED, GPIO.HIGH)
if __name__ == '__main__':
main()
我想使用定时器来控制 LED 的开/关持续时间。我写了下面的代码,但它没有 运行.
def main ():
LED =27
GPIO.setup(LED, GPIO.OUT)
while (True):
now = datetime.datetime.now()
todayon = now.replace(hour = 17, minute=47, second =0, microsecond =0)
todayoff = now.replace(hour = 17, minute=48, second =0, microsecond =0)
turnon = now>todayon
turnoff = now>todayoff
if(turnon == True):
GPIO.output(LED, GPIO.HIGH)
time.sleep(1)
GPIO.output(LED, GPIO.LOW)
time.sleep(1)
if(turnoff == True):
GPIO.output(LED, GPIO.HIGH)
如果它没有 运行(什么都不做),可能是因为您从未调用 main
在这种情况下,在底部添加以下行:
if __name__ == '__main__':
main()
此外,您需要设置 GPIO 以使用端口号或引脚号。
使用 GPIO.setmode(GPIO.BCM)
将模式设置为端口号,因此当您调用 GPIO.setup(LED, GPIO.OUT)
.
完整的脚本现在应该如下所示:
#!/usr/bin/python
import time
import datetime
import RP1.GPIO as GPIO
def main ():
LED =27
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED, GPIO.OUT)
while (True):
now = datetime.datetime.now()
todayon = now.replace(hour = 17, minute=47, second =0, microsecond =0)
todayoff = now.replace(hour = 17, minute=48, second =0, microsecond =0)
turnon = now>todayon and now<todayoff
turnoff = now>todayoff
if(turnon == True):
GPIO.output(LED, GPIO.HIGH)
time.sleep(1)
GPIO.output(LED, GPIO.LOW)
time.sleep(1)
if(turnoff == True):
GPIO.output(LED, GPIO.HIGH)
if __name__ == '__main__':
main()