蟒蛇。在一个循环函数内部调用的函数只运行一次,然后函数的其余部分重复

时间:2015-01-04 14:17:11

标签: python repeat gpio

我对python非常陌生,并尝试控制覆盆子pi上的gpio引脚以闪烁多个灯光。

试图设置一个功能来分别控制每个灯。然后是另一个允许它们闪烁的功能。

当我设置"颜色"作为变量在"闪烁"功能。灯只闪烁一次,然后重复功能的其余部分继续闪烁,直到重复完成。为什么它不重复"颜色"每次重复都会发挥作用。

任何帮助将不胜感激

import RPi.GPIO as GPIO ## Import GPIO Library
import time ## Import 'time' library.  Allows us to use 'sleep'
GPIO.setmode(GPIO.BOARD) ## Use BOARD pin numbering
GPIO.setup(7, GPIO.OUT) ## Setup GPIO pin 7 to OUT
GPIO.setup(11, GPIO.OUT)

## Prompt user for input
iterations = raw_input("Enter the total number of times to blink: ")
speed = raw_input("Enter the length of each blink in seconds: ")

## Define function named Blink()
def green(speed):
  print "green on"
  GPIO.output(7, True) ## Turn on GPIO pin 7
  time.sleep(speed) ## Wait
  print "green off"
  GPIO.output(7, False) ## Switch off GPIO pin 7
  time.sleep(speed) ## Wait

def red(speed):
    print "red on"
    GPIO.output(11, True) ## Turn on GPIO pin 7
    time.sleep(speed) ## Wait
    print "red off"
    GPIO.output(11, False) ## Switch off GPIO pin 7
    time.sleep(speed) ## Wait

def Blink(numTimes,color):
    while numTimes > 0:
        print "Iteration " + str(numTimes) ##Print current loop
        color
        numTimes = numTimes - 1


## Start Blink() function. 

Blink(int(iterations),green(float(speed)))
GPIO.cleanup()

1 个答案:

答案 0 :(得分:2)

当您将green(float(speed))作为参数传递时,会对该表达式进行求值(即调用green),结果 - 在本例中为None - - 被传递到Blink。因此,green只被调用一次。

color中的Blink表达式实际上是无操作。

您可以采取以下措施:

def Blink(numTimes, color, speed):
#                          ↑↑↑↑↑ Add a third argument
    while numTimes > 0:
        print "Iteration " + str(numTimes)
        color(speed)
        #    ↑↑↑↑↑↑↑ Call the function (with the right argument)
        numTimes = numTimes - 1


## Start Blink() function. 

Blink(int(iterations), green, float(speed))
#                      ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ pass the name of the function and the speed