@@ -22,7 +22,7 @@ is also "correct". The distinction in sign is simply whichever makes more sense
2222we would want to drive forward 10cm, so we would want a positive error to make our motors spin forward.
2323
2424**Control Output **: In this case, this is our motor effort. This is because we want to drive with a speed proportional
25- to the distance error. As a reminder for P control, this will be calculated as :code: `motor_effort = Kp * error `.
25+ to the distance error. As a reminder for P control, this will be calculated as :code: `motorEffort = Kp * error `.
2626
2727**Kp **: This is our proportional gain. Though we will need to tune this value, we can guess a somewhat reasonable value
2828by considering the range of values our error can take, and the domain of our control output. In this case, if we're 30cm away
@@ -52,3 +52,36 @@ Let's start by defining our proportional gain and our set point:
5252 :width: 300
5353
5454Next, we want to enter some sort of loop to continuously poll our rangefinder and update our motor effort from our controller output.
55+
56+ .. tab-set ::
57+
58+ .. tab-item :: Python
59+
60+ .. code-block :: python
61+
62+ Kp = 0.1
63+ desiredDistance = 20
64+ while True :
65+ error = rangefinder.distance() - desiredDistance
66+ motorEffort = Kp * error
67+ drivetrain.set_effort(motorEffort, motorEffort)
68+ time.sleep(0.05 )
69+
70+ .. tab-item :: Blockly
71+
72+ .. image :: media/pcode.png
73+ :width: 500
74+
75+ Each iteration of the loop consists of the following steps:
76+ #. Poll the rangefinder to get the current distance
77+ #. Calculate the error
78+ #. Calculate the control output through Kp * error
79+ #. Set the drivetrain motor efforts to the control output
80+ #. Wait for a short period of time
81+
82+ This code should give us a working solution to maintain a set distance from the object in front of the robot!
83+
84+ .. admonition :: Try it out
85+
86+ Try moving the object in front of the robot and watch the robot attempt to maintain the set distance! What
87+ happens when you increase Kp? Decrease it? What value of Kp works best for your robot?
0 commit comments