猿问

按下键盘输入时PYTHON程序运行(执行)

您好,我有一个使用Slushengine电机驱动程序运行几个电机的简单python项目。我已经制作了示例程序(如下面的代码所示),但是现在我想让我在按下键盘(输入)上的键(例如ENTER键)时使电动机运行。然后,当我按下另一个键时,我希望程序停止。


from inputs import get_key

import RPi.GPIO as GPIO

import Slush

import math

import time


from time import sleep


b = Slush.sBoard()

m = [Slush.Motor(0), Slush.Motor(1), Slush.Motor(2), Slush.Motor(3)]


m[0].setMaxSpeed(150)

m[1].setMaxSpeed(150)

m[2].setMaxSpeed(250)

m[3].setMaxSpeed(150)


m[0].setCurrent(150, 150, 150, 150)

m[1].setCurrent(100, 100, 100, 100)

m[2].setCurrent(150, 150, 150, 150)

m[3].setCurrent(100, 100, 100, 100)



GPIO.setmode(GPIO.BCM)

GPIO.setup(18, GPIO.OUT)

pwm = GPIO.PWM(18, 100)

pwm.start(0)

GPIO.output(18, True)


pwm.ChangeDutyCycle(1)

sleep(0.5)

m[1].goTo(750)

time.sleep(3)

m[0].goTo(750)

time.sleep(3)

pwm.ChangeDutyCycle(99)

sleep(1)

当检测到按键时,我需要执行此代码。


pwm.ChangeDutyCycle(1)

sleep(0.5)

m[1].goTo(750)

time.sleep(3)

m[0].goTo(750)

time.sleep(3)

pwm.ChangeDutyCycle(99)

sleep(1)


蛊毒传说
浏览 453回答 2
2回答

有只小跳蛙

它不是已经显示在PyPI中了吗?from inputs import get_keydef key_input():    while 1:        events = get_key()        for event in events:            print(event.ev_type, event.code, event.state)if __name__ == '__main__':    key_input()

斯蒂芬大帝

这样对吗??对不起,我还不清楚from inputs import get_keyimport RPi.GPIO as GPIOimport Slushimport mathimport timefrom time import sleepb = Slush.sBoard()m = [Slush.Motor(0), Slush.Motor(1), Slush.Motor(2), Slush.Motor(3)]m[0].setMaxSpeed(150)m[1].setMaxSpeed(150)m[2].setMaxSpeed(250)m[3].setMaxSpeed(150)m[0].setCurrent(150, 150, 150, 150)m[1].setCurrent(100, 100, 100, 100)m[2].setCurrent(150, 150, 150, 150)m[3].setCurrent(100, 100, 100, 100)GPIO.setmode(GPIO.BCM)GPIO.setup(18, GPIO.OUT)pwm = GPIO.PWM(18, 100)pwm.start(0)GPIO.output(18, 1)while 1:    events = get_key()    for event in events:        if event.code == 'KEY_ENTER':            pwm.ChangeDutyCycle(1)            time.sleep(1)            m[1].goTo(750)            time.sleep(3)            m[0].goTo(750)            time.sleep(3)            pwm.ChangeDutyCycle(99)            time.sleep(1)
随时随地看视频慕课网APP

相关分类

Python
我要回答