注册 登录
编程论坛 嵌入式开发

这个应该怎么添加一个按键检测,该怎么搞,求助大佬

斯玥 发布于 2022-02-16 18:16, 947 次点击

import RPi.CPIO as GPIO
from time import sleep

in1 = 24
in2 = 23

en = 25  # 定义输出引脚
temp1 = 1

GPIO.setmode(GPIO.BCM)  # 定义树莓派gpio引脚以BCM方式编号
GPIO.setup(in1, GPIO.OUT)
GPIO.setup(in2, GPIO.OUT)
GPIO.setup(in3, GPIO.OUT)
GPIO.setup(in4, GPIO.OUT)
GPIO.setup(en, GPIO.OUT)  # 使能gpio输出
GPIO.output(in1, GPIO.LOW)
GPIO.output(in2, GPIO.LOW)
GPIO.output(in3, GPIO.LOW)
GPIO.output(in4, GPIO.LOW)
p = GPIO.PWM(en, 1000)  # 1000为输出频

p.start(25)

print("请输入相应指令控制车移动")
print("w是前进,s是后退,a是左转,d是右转,p是停止")
print("\n")
while (1):
    x = input()
    if x == 'w':

        GPIO.output(in1, GPIO.HIGH)
        GPIO.output(in2, GPIO.LOW)
        GPIO.output(in3, GPIO.HIGH)
        GPIO.output(in4, GPIO.LOW)
        print("前进")
        x = 'z'
    elif x == 's':
        GPIO.output(in1, GPIO.LOW)
        GPIO.output(in2, GPIO.HIGH)
        GPIO.output(in3, GPIO.LOW)
        GPIO.output(in4, GPIO.HIGH)
        print("后退")
        x = 'z'
    elif x == 'a':
        p.ChangeDutycle(5)
        GPIO.output(in1, GPIO.LOW)
        GPIO.output(in2, GPIO.HIGH)
        GPIO.output(in3, GPIO.HIGH)
        GPIO.output(in4, GPIO.LOW)
        print("左转")
        x = 'z'

    elif x == 'd':
        p.ChangeDutycle(5)
        GPIO.output(in1, GPIO.HIGH)
        GPIO.output(in2, GPIO.LOW)
        GPIO.output(in1, GPIO.LOW)
        GPIO.output(in2, GPIO.HIGH)
        print("右转")
        x = 'z'

    elif x == 'p':
        GPIO.output(in1, GPIO.LOW)
        GPIO.output(in2, GPIO.LOW)
        GPIO.output(in1, GPIO.LOW)
        GPIO.output(in2, GPIO.LOW)
        print("停")
        x = 'z'
    elif x == '1':
        print("低速")
        p.ChangeDutycle(25)
    elif x == '2':
        print("中速")
        p.ChangeDutycle(50)

    elif x == '3':
        print("高速")
        p.ChangeDutycle(75)

    elif x == 'e':
        GPIO.cleanup()
        print("清除")
        break

    else:
        print("<< 注意 >>")
        print("请输入数据继续")
0 回复
1