我是初学程序员,所以我没有丰富的Python经验。我创建了一个超声波传感器系统,使用树莓派记录水位。我的程序在控制台中工作正常,但我想为它制作一个GUI,使其更吸引人使用Tkinter。我之前从未使用过Tkinter,所以我不确定我做错了什么。我已经创建了一个按钮,应该开始实际读取,但是每次运行时都会收到一条错误,告诉我我无法访问GPIO,我应该尝试以root身份运行 - 尽管我这样做同样的错误出现。
有没有人知道我哪里出错或者通过GUI运行它的其他方法?我很感激任何帮助,因为我已经在这个问题上坚持了两个多月了,非常感谢!
我得到的错误信息就是这个;
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()
这是代码:
onDiscoveryStarted
答案 0 :(得分:1)
第一个错误:
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
和TRIG
在measure
功能中使用,但从那里看不到,因此您需要解决此问题。