我是一个初学者,所以我没有Python的丰富经验。我创建了一个超声波传感器系统,该系统使用树莓派记录水位。我的程序在控制台中运行良好,但是我想为其创建一个GUI,以使其在使用Tkinter时更具吸引力。我以前从未使用过Tkinter,所以不确定自己做错了什么。我做了一个应该开始读取实际读数的按钮,但是,每次运行时,我都会收到一条错误消息,告诉我我无权访问GPIO,我应该尝试以root用户身份运行-尽管当我执行此错误时出现。

有人知道我哪里出错了,或者是否有通过GUI运行它的其他方式?非常感谢您的帮助,因为我已经在这个问题上停留了两个多月,非常感谢!

我收到的错误消息是这样;

"Exception in Tkinter callback
Traceback (most recent call last):
     File 'user/lib/python3.2/tkinter/__init__.py', line 1426, in __call__
          return self.func(*args)
     File 'home.pi.tkinterproject.py', line 40 in run_code
          GPIO.setup(GPIO.OUT)
RuntimeErorr: No access to /dev/mem. Try running as root!"


这是代码:

from tkinter import *
import time
import datetime
import RPi.GPIO as GPIO
GPIO.setwarnings(False)

class Window(Frame):
def     __init__(self, master = None):
        Frame.__init__(self, master)

        self.master = master

        self.init_window()

def init_window(self):

        self.master.title("GUI")

        self.pack(fill=BOTH, expand=1)

        quitButton = Button(self, text = "Quit", command = self.exit_window)
        quitButton.place(x = 330,y = 260)

        runButton = Button(self, text = "Run", command = self.run_code)
        runButton.place(x = 0, y = 0)


def exit_window(self):
        exit()

def run_code(self):
        #set pins according to BCM GPIO references
        GPIO.setmode(GPIO.BCM)
        #set GPIO pins
        TRIG = 23
        ECHO = 24
        #sets trigger to send signal, echo to recieve the signal back
        GPIO.setup(TRIG,GPIO.OUT)
        GPIO.setup(ECHO,GPIO.IN)
        #sets output to low
        GPIO.output(TRIG,False)
        myLabell = Label(text = 'Initiating measurement').pack()
        print ("Initiating measurement..\n")
        #gives sensor time to settle for one second
        time.sleep(1)
        distance = averageReading()
        round(distance, 2)
        print ("Distance:", distance, "cm\n")
        print ("Saving your measurement to file..")
        ts = time.time()
        timestamp = datetime.datetime.fromtimestamp(ts).strftime('     %H: %M: %S     %d-%m-%Y')
        textFile = open("sensorReadings" , "a")
        textFile.write(str(distance)+ "cm     recorded at: ")
        textFile.write(str(timestamp)+ "\n")
        textFile.close()
        #resets pins for next time
        GPIO.cleanup()

global averageReading

def averageReading():
        readingOne = measure()
        time.sleep(0.1)

        readingTwo = measure()
        time.sleep(0.1)
        readingThree = measure()
        reading = readingOne + readingTwo + readingThree
        reading = reading / 3
        return reading

global measure

def measure():
        global measure
        #sends out the pulse to the trigger
        GPIO.output(TRIG, True)
        #short as possible
        time.sleep(0.00001)
        GPIO.output(TRIG,False)

        while GPIO.input(ECHO) == 0:
                pulse_start = time.time()
        while GPIO.input(ECHO) == 1:
                pulse_end = time.time()
                pulse_duration = pulse_end - pulse_start

                #half the speed of sound in cm/s
                distance = pulse_duration * 34300
                distance = distance / 2
                #python function that rounds measurement to two digits
                round(distance, 2)
                return distance

myGUI = Tk()

myGUI.geometry("400x300")
app = Window(myGUI)

myGUI.mainloop()

最佳答案

第一个错误:

RuntimeErorr: No access to /dev/mem. Try running as root!"


确切地说,它是什么意思:您需要以root身份运行代码,才能正确访问GPIO子系统。当以root身份运行时,会收到另一个错误:

NameError: global name 'averageReading' is not defined


这是由于您的代码中的错误而发生的。首先,您似乎同时拥有一个全局变量和一个具有相同名称的函数。删除此行:

global averageReading


并且:

global measure


global语句用于创建全局变量,并且仅在功能块内使用时才有意义。

您发布的代码中存在许多格式问题(在几行上缺少缩进),很难分辨这仅仅是复制/粘贴问题还是代码不正确。

请尝试解决问题中的所有格式问题,使其与您的实际代码匹配。

另外,在ECHO函数中使用了TRIGmeasure,但是从那里看不到它们,因此您需要对其进行修复。

10-04 21:57
查看更多