在运行 GUI 时操纵 Raspbery PI 的直流电机速度



树莓派初学者

我正在编写GUI应用程序(使用PyQt5(来控制直流电机。到目前为止,我能够通过电机驱动器控制我的电机并在终端中更改其速度(使用 PWM(。

当我

想要我的 GUI 应用程序中的电机控制器代码时,问题就来了,因为当我运行电机运动函数时,我的 time.sleep(x( 会停止整个 GUI 应用程序,所以我无法更改电机的速度。

发现线程可能会节省我的问题,但我不知道如何在线程运行时修改速度。

这是我运行电机的代码:

import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
# set pins as output
GPIO.setup(4,GPIO.OUT)
GPIO.setup(18,GPIO.OUT)
GPIO.setup(17,GPIO.OUT)

p = GPIO.PWM(17,80)
p.start(40)
p.ChangeDutyCycle(50)
GPIO.output(18,GPIO.LOW)
GPIO.output(4,GPIO.HIGH)
print("4 is HIGH")
time.sleep(5)
p.ChangeDutyCycle(70)#speed change
#change direction of motor spinning
GPIO.output(4,GPIO.LOW)
GPIO.output(18,GPIO.HIGH)
print("18 is HIGH")

p.stop()
GPIO.cleanup()

Python for GUI:

from PyQt5 import QtWidgets,uic, QtCore
...
def start():
    while True:
        #run motor here

dlg.btn_start.clicked.connect(start)
...

我希望我没有让这件事变得比现在更复杂,谢谢大家的回答!

此致敬意!

解决方案:

我让它与Python多处理一起工作。

我的程序现在分为两个进程:

1.GUI过程,运行GUI和信号,运行滑块更改速度功能。每当滑块的位置发生变化时,该值都会保存到文本文件中。

2.电机过程是一直读取同一文件并将文件值应用于电机速度的过程。如果该值设置为 0,则电机为关闭。

我认为这不是唯一的解决方案,当然也不是最好的,但它对我有用。

我希望这对你们中的一些人也有帮助!

干杯!

当然还有代码:

from PyQt5 import QtWidgets,uic, QtCore
from PyQt5.QtWidgets import QMessageBox,QApplication, QWidget, QInputDialog, QLineEdit, QFileDialog
from PyQt5.QtCore import QTimer,QTime
from PyQt5.QtGui import QIcon
import time
from multiprocessing import Process, Queue, Value
app = QtWidgets.QApplication([])
dlg = uic.loadUi("Motor.ui")

def startMotor():
    try:
        while True:
            time.sleep(0.01)
            file = open("test.txt", "r") 
            a=file.read()
            file.close()
            if int(a) == 0:
                print("OFF")
                #motor is off
            else:
                #motor is ON
                print("ON, speed is:", a)
    except:
        print("Abort...")
def runProgram():
    dlg.show()
    app.exec()

def changeSpeed():
    dlg.label.setText(str(dlg.slider.value()))
    file = open("test.txt","w") 
    file.write(str(dlg.slider.value()))
    file.close() 
#when slider's value is changed
dlg.slider.valueChanged.connect(changeSpeed)

if __name__ == '__main__':
    #On Program load    
    p1 = Process(target=startMotor,args=())
    p2 = Process(target=runProgram,args=())
    p1.start()
    p2.start()
    p1.join()
    p2.join()

如果有人有兴趣学习 PyQt5 设计的基础知识,请查看我的 YouTube 频道,我在那里解释了基础知识:链接

最新更新