control_loops

# Control Loops

The QuimDC has four control modes, one is an open loop and the others are closed loops. Default mode is PWM Open Loop control mode.

## PWM Open Loop (loop_function 0)

In open loop, ref_speed is used to control the motors, here is an example :

With ref_speed set to 0, the pwm value is 128.

With ref_speed set to 62, the pwm value is 190.

With ref_speed set to -18, the pwm value is 110.

## Current Closed Loop (loop_function 1)

The current control period is 1 ms.

This loop needs the current amount that passes through the motor. The QuimDC has a 12 bits ADC but has no clue about the current sign. We need to estimate the current sign using this formula :

```Vbemf = ((60 * speed) / (ticks_per_turn_motor * 0.001)) / kv_motor
Voltage = nominal_power_voltage * ( pwmDuty - 128 ) / 128      with pwmDuty [0;255]
itemp = (Voltage - Vbemf) / resistance_motor```

We use the itemp sign to estimate the current sign. By default we have the following value :

```resistance_motor = 1.0
kv_motor = Inf
ticks_per_turn_motor = 1
nominal_power_voltage = 1.0```

With this value, the current sign is estimated with the pwm sign. Resistance_motor, kv_motor, ticks_per_turn_motor and nominal_power_voltage are only used in this formula.

## Speed Current Closed Loop (loop_function 2)

In this loop, we have two PID in cascade. The output of the speed PID is used as a reference for the second current PID. To ensure that the current doesn't exceed the ref_current, the first PID output is saturated by ref_current.

The speed is obtained by doing the difference between the encoder value at period n and period n-1 and then convert it into tick per second. We can change the period of the speed loop by setting the position_speed_period parameter.

If the quadrature encoder channel are swap, you can use the polarity to make them work (the polarity must be set to 1 or -1, any other value will not send error but will lead to unexpected results).

## Position Speed Current Closed Loop (loop_function 3)

There are three PID in cascade, position, speed and current. 