零售物价指数使用类时回调不起作用

2024-10-02 12:27:08 发布

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

我有以下课程:

import RPi.GPIO as GPIO

class DistanceSensor2:

    def __init__(self, GPIO_MODE, GPIO_TRIGGER, GPIO_ECHO):

        def set_times(channel):
            print("set_times")

        self.GPIO_TRIGGER = GPIO_TRIGGER
        self.GPIO_ECHO = GPIO_ECHO

        GPIO.setmode(GPIO_MODE)

        GPIO.setup(self.GPIO_ECHO, GPIO.IN)      # Echo

        GPIO.add_event_detect(self.GPIO_ECHO, GPIO.RISING, callback = set_times)

然后,在我的主菜单中,我有:

^{pr2}$

我得到了一个错误:

  Traceback (most recent call last):
  File "PythonHelloWorld.py", line 8, in <module>
  test = DistanceSensor2(GPIO_MODE, GPIO_TRIGGER, GPIO_ECHO)
  File "/home/pi/PythonHelloWorld/PythonHelloWorld/DistanceSensor2.py", line 31, in __init__
  GPIO.add_event_detect(self.GPIO_ECHO, GPIO.RISING, callback = set_times)
  RuntimeError: Failed to add edge detection

当我直接在main.py中使用下面的代码时,它是有效的。在

import RPi.GPIO as GPIO
import time

GPIO_MODE = GPIO.BCM
GPIO_ECHO = 18

def set_times(channel):
    print("set_times")

GPIO.setmode(GPIO_MODE)

GPIO.setup(GPIO_ECHO, GPIO.IN)      # Echo

GPIO.add_event_detect(GPIO_ECHO, GPIO.RISING, callback = set_times)

while 1:
    print("inside while")
    time.sleep(1)

有人能看出问题在哪里吗?我也尝试过将set_times()移到方法之外,但它也不起作用。在


Tags: importechoselfeventaddgpiomodedef
1条回答
网友
1楼 · 发布于 2024-10-02 12:27:08

终于看到了错误。我的新代码如下:

我的班级:

import RPi.GPIO as GPIO
import time

class DistanceSensor2:
    def __init__(self, GPIO_MODE, GPIO_TRIGGER, GPIO_ECHO):
        self.GPIO_TRIGGER = GPIO_TRIGGER
        self.GPIO_ECHO = GPIO_ECHO

        GPIO.setmode(GPIO_MODE)

        GPIO.setup(self.GPIO_ECHO, GPIO.IN)      # Echo
        GPIO.add_event_detect(self.GPIO_ECHO, GPIO.RISING, callback = self.set_times)

        GPIO.setup(self.GPIO_TRIGGER, GPIO.OUT, initial = GPIO.LOW )

        while 1:
            print("while")
            time.sleep(1)

    def set_times(self, channel):
        print("channel:", channel)

我的主。py

^{pr2}$

相关问题 更多 >

    热门问题