Как использовать потоки, чтобы time.sleep () не останавливал весь скрипт? - PullRequest
0 голосов
/ 05 августа 2020

Я начал изучать python 3 месяца go, и я хотел начать с создания робота, сегодня я управлял серводвигателем, используя библиотеку, созданную компанией-роботом для его спецификации c Motor Hat, моя проблема в когда серводвигатель плавно поворачивается от середины вправо или влево, используя a для l oop (это для управления роботом), я использую time.sleep(), однако, когда я сплю, все другие функции робота временно останавливаются.

Я искал эту проблему и обнаружил, что мне нужно использовать что-то, что называется потоковой передачей, я очень-очень хорошо научился c многопоточности, но до сих пор не знаю, как реализовать ее в этом коде.

# Importing libraries
from pyPS4Controller.controller import Controller,Event
import Adafruit_PCA9685
import threading
import RPi.GPIO as GPIO
import time


# Defining a function to set up the servo motors to a frequency of 50Hz
def setup_servos(frequency):
    global head_right_left,head_up_down,steering

    head_right_left=Adafruit_PCA9685.PCA9685()
    head_up_down=Adafruit_PCA9685.PCA9685()
    steering=Adafruit_PCA9685.PCA9685()


    head_right_left.set_pwm_freq(frequency)
    head_up_down.set_pwm_freq(frequency)
    steering.set_pwm_freq(frequency)


# Defining functions for turning the head
def head_right():
    head_right_left.set_pwm(1,0,170)
def head_left():
    head_right_left.set_pwm(1,0,450)
def head_up():
    head_up_down.set_pwm(0,0,470)
def head_down():
    head_up_down.set_pwm(0,0,260)
def head_neutral():
    head_right_left.set_pwm(1,0,320)
    head_up_down.set_pwm(0,0,320)


# Defining functions to steer the wheels
def turn_right():
    for x in range(320,220,-1):
            steering.set_pwm(2,0,x)
            time.sleep(0.008)


def turn_left():
    for x in range(320,420):
        steering.set_pwm(2,0,x)
        time.sleep(0.008)


# Defining a function to setup the GPIO pins for the dc motor
def setup_dc_motor():
    GPIO.setup(17,GPIO.OUT)
    GPIO.setup(27,GPIO.OUT)
    GPIO.setup(18,GPIO.OUT)


# Defining a function that will stop the motors -------> OUTPUT=0
def stop_motor():
    GPIO.output(17,0)
    GPIO.output(27,0)
    GPIO.output(18,0)


# Defining a function that will drive the robot forwards
def drive_forwards():
    GPIO.output(27,0)
    GPIO.output(18,1)
    dc_motor_pwm.start(100)


# Defining a function that will drive the robot backwards
def drive_backwards():
    GPIO.output(27,1)
    GPIO.output(18,0)
    dc_motor_pwm.start(100)


# Defining a function that will stop the robot -----> PWM=0
def stop_robot():
    dc_motor_pwm.ChangeDutyCycle(0)


# This class is used for fixing the button mapping on the PS4 controller
class MyEventDefinition(Event):

    def x_pressed(self):
        return self.button_id == 0 and self.button_type == 1 and self.value == 1
    def x_released(self):
        return self.button_id == 0 and self.button_type == 1 and self.value == 0


    def circle_pressed(self):
        return self.button_id == 1 and self.button_type == 1 and self.value == 1
    def circle_released(self):
        return self.button_id == 1 and self.button_type == 1 and self.value == 0


    def square_pressed(self):
        return self.button_id == 3 and self.button_type == 1 and self.value == 1
    def square_released(self):
        return self.button_id == 3 and self.button_type == 1 and self.value == 0


    def triangle_pressed(self):
        return self.button_id == 2 and self.button_type == 1 and self.value == 1
    def triangle_released(self):
        return self.button_id == 2 and self.button_type == 1 and self.value == 0


# This class provides methods when a button is pressed
class MyController(Controller):
    """"""

    def on_R3_right(self,value=30000):
        head_right()


    def on_R3_left(self,value=-30000):
        head_left()


    def on_R3_up(self,value=-30000):
        head_up()


    def on_R3_down(self,value=30000):
        head_down()


    def on_R3_at_rest(self):
        head_neutral()


    def on_R2_press(self,value=25000):
        drive_forwards()


    def on_L2_press(self,value=25000):
        drive_backwards()


    def on_R2_release(self):
        stop_robot()


    def on_L2_release(self):
        stop_robot()

#--------------------------------------------------------------------------
    def on_left_arrow_press(self):
        turn_left()


    def on_right_arrow_press(self):  #-------------------> RIGHT HERE I NEED HELP
        turn_right()





    def on_left_right_arrow_release(self):
        steering.set_pwm(2,0,320)

#-----------------------------------------------------------------------



# The actual code

setup_servos(50)


GPIO.setmode(GPIO.BCM)

setup_dc_motor()

stop_motor()

dc_motor_pwm=GPIO.PWM(17,1000)
dc_motor_pwm.start(0)



controller = MyController(interface="/dev/input/js0", connecting_using_ds4drv=False, event_definition=MyEventDefinition)
controller.listen(timeout=60)

1 Ответ

0 голосов
/ 05 августа 2020

Могу я спросить, зачем вам вообще нужен сон? Почему вам нужно задерживать своего робота? Вы можете вызвать засыпание в потоке (что в большинстве реализаций python не является фактическим потоком [см. GIL Python]), но вам нужно будет переместить другие части вашего кода в поток, чтобы сон фактически сделай что-нибудь полезное.

...