[Python] PI control signal

Discussão em 'Python' iniciado por Stack, Julho 2, 2025.

  1. Stack

    Stack Membro Participativo

    i am trying to translate my PI control signal 'u[k]' into a duty cycle ouput with error e[k] governing directional output....but i think it could be better.

    So I am using if statements to concentrate the value of u between 0 to 100 since that is the dc range. (I cant seem to add an "abs" statement to u or u[k] anywhere to keep it in the postiive realm, so if there is another way please let me know.)

    Then the value of u[k] will become the dc cycle throughtout the script. if error e[k] is positive than to rotate CW, if error is negative then to rotate CCW. At the same time, u[k] will contorl the speed of the motor allowing it to slow down or speed up as it reaches the desired angle. let me know

    I am still having the error

    "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"

    Below is the snippet of code I am struggling with. Any help is appreciated

    def MotorClockwise():
    GPIo_Output(Motor1, GPIO.LOW) # Motor will move in clockwise direction.
    GPIo_Output(Motor2, GPIO.HIGH)


    def MotorAntiClockwise():
    GPIo_Output(Motor1, GPIO.HIGH) # Motor will move in anti-clockwise direction.
    GPIo_Output(Motor2, GPIO.LOW)

    def MotorStop():
    GPIo_Output(Motor1, GPIO.LOW) # Motor will stop.
    GPIo_Output(Motor2, GPIO.LOW)
    GPIo_Output(PWMPin, GPIO.LOW)


    #PI controller settings
    Kp = 12
    Ki = 8 #integral Time

    r = 4.5 #setpoint angle to be achieved
    #intialization
    e = np.zeros(N+2)
    u = np.zeros(N+2)

    for k in range(N+1):

    e[k] = r - encoder_angle #calucalted error
    #print (f"{e[k]} Error Detected")
    #time.sleep(.5)

    # PI Controller - produces new contrl signal
    u[k] = u[k-1] + Kp*(e[k] - e[k-1]) + (Kp/Ki)*e[k] # discrete version of PI controller
    # y[k+1] = (1+Ts*a)*y[k] + Ts*b*u[k] #discrete deff equ of process


    ########################BELOW IS WHERE I AM STRUGGELING

    while True:
    if (u > 100):
    u = 100;
    if (e[k] > 0) :
    PwmValue.ChangeDutyCycle(u)
    MotorClockwise()
    if (u < -100):
    u = -100;
    if (e[k] < 0):
    PwmValue.ChangeDutyCycle(u)
    MotorAntiClockwise()

    if (e[k] == 0) and (r == encoder_angle):
    MotorStop()
    print(f"Motor Stopped & Holding at {encoder_angle} Degrees")
    break

    Continue reading...

Compartilhe esta Página