锁定变量?

2024-03-29 05:25:02 发布

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

这里是我从pygames和xboxdrv以及其他一些教程中拼凑出来的关于如何从RPi上的GPIO管脚供电的教程。我正在尝试使用连接到RPi的xbox控制器。下面是当按下“A”按钮时打开LED的代码。这对我来说很好。在

当值==1时,灯将闪烁,按钮一松开,值==0,当前没有编码。在

我想做的是,当按下“A”时,LED保持通电,松开按钮时保持点亮,但当再次按下“A”按钮时,LED将熄灭。在

def controlCallBack(xboxControlId, value):
    print "Control Id = {}, Value = {}".format(xboxControlId, value)
            if xboxControlId == 6 and value == 1:
                pin = 7 
                GPIO.setmode(GPIO.BOARD)
                GPIO.setup(pin, GPIO.OUT)
                GPIO.output(pin, GPIO.HIGH)
                time.sleep(.05) 
                GPIO.output(pin, GPIO.LOW)
                time.sleep(.05)
                GPIO.cleanup()

如果有任何帮助,我将不胜感激,我对Python和编程非常陌生。在


Tags: outputledgpiotimevaluepin教程sleep
2条回答
led_powered = False

def setup():
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(pin, GPIO.OUT)    

def teardown():
    GPIO.cleanup()

def power_led():
    GPIO.output(7, GPIO.HIGH)
    global led_powered 
    led_powered = True


def unpower_led():
    GPIO.output(7, GPIO.LOW)
    global led_powered 
    led_powered = False

def controlCallBack(xboxControlId, value):
    print "Control Id = {}, Value = {}".format(xboxControlId, value)
    if xboxControlId == 6 and value == 1:
        if led_powered:
            unpower_led()
        else:
            power_led()

在程序开始时调用setup(),在程序结束时调用teardown()。在

以下是user2804197代码的面向对象版本:

class Led(object):
    LED_PIN = 7

    def __init__(self):
        self.powered = False
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(self.LED_PIN, GPIO.OUT)

    def __del__(self):
        GPIO.cleanup()

    def power(self):
        GPIO.output(self.LED_PIN, GPIO.HIGH)
        self.powered = True

    def unpower(self):
        GPIO.output(self.LED_PIN, GPIO.LOW)
        self.powered = False

    def toggle(self):
        if self.powered:
            self.unpower()
        else:
            self.power()

led = Led()

def controlCallBack(xboxControlId, value):
    print "Control Id = {}, Value = {}".format(xboxControlId, value)
    if xboxControlId == 6 and value == 1:
        led.toggle()

也可以直接调用led.power()led.unpower()。在

相关问题 更多 >