Proportional integral differential PID controller in Lego Mindstorms robotics. Proportional controller. International Robot Contest - Rules - Sample Robots - LEGO EV3 Trajectory Robot Algorithm Example

One of the basic movements in legoconstruction is following the black line.

The general theory and specific examples of creating a program are described on the site wroboto.ru

I will describe how we implement this in the EV3 environment, as there are differences.

The first thing the robot needs to know is the value of the “ideal point” located on the border of black and white.

The location of the red dot in the figure just corresponds to this position.

The ideal calculation option is to measure the value of black and white and take the arithmetic mean.

You can do it manually. But the cons are immediately visible: during even a short time, the illumination can change, and the calculated value will turn out to be incorrect.

So you can make a robot do it.

In the course of experiments, we found that it is not necessary to measure both black and white. Only white can be measured. And the value of the ideal point is calculated as the value of white divided by 1.2 (1.15), depending on the width of the black line and the speed of the robot.

The calculated value must be written to a variable in order to access it later.

Calculation of the “ideal point”

The next parameter involved in the movement is the turn ratio. The larger it is, the more sharply the robot reacts to changes in illumination. But too high a value will cause the robot to wobble. The value is selected experimentally individually for each robot design.

The last parameter is the base power of the motors. It affects the speed of the robot. An increase in the speed of movement leads to an increase in the response time of the robot to a change in illumination, which can lead to a departure from the trajectory. The value is also selected experimentally.

For convenience, these parameters can also be written to variables.

Steering ratio and base power

The logic of moving along the black line is as follows: the deviation from the ideal point is measured. The larger it is, the stronger the robot should strive to return to it.

To do this, we calculate two numbers - the power value of each of the motors B and C separately.

In formula form, it looks like this:

Where Isens is the value of the light sensor readings.

Finally, the implementation in EV3. It is most convenient to issue in the form of a separate block.

Implementation of the algorithm

This is the algorithm that was implemented in the robot for the middle category WRO 2015

This task is classical, ideologically simple, it can be solved many times, and each time you will discover something new.

There are many approaches to solve the line following problem. The choice of one of them depends on the specific design of the robot, on the number of sensors, their location relative to the wheels and each other.

In our example, three robot examples will be disassembled based on the main Robot Educator tutorial model.

To begin with, we assemble the basic model of the Robot Educator, for this you can use the instructions in the MINDSTORMS EV3 software.

Also, for examples, we need EV3 light-color sensors. These light sensors, like no other, are best suited for our task, when working with them, we do not have to worry about the intensity of the ambient light. For this sensor, in the programs we will use the reflected light mode, in which the amount of reflected light of the sensor's red illumination is estimated. The limits of the sensor readings are 0 - 100 units, for "no reflection" and "total reflection", respectively.

For example, we will analyze 3 examples of programs for moving along a black path depicted on an even, light background:

· One sensor, with P regulator.

· One sensor, with PK regulator.

· Two sensors.

Example 1. One sensor, with P regulator.

Design

The light sensor is mounted on a beam conveniently located on the model.


Algorithm

The operation of the algorithm is based on the fact that, depending on the degree of overlap, the sensor illumination beam with a black line, the readings returned by the sensor vary in a gradient. The robot keeps the position of the light sensor on the border of the black line. By converting the input data from the light sensor, the control system generates the value of the robot's turning speed.


Since on a real trajectory the sensor generates values ​​in its entire operating range (0-100), the value to which the robot strives is 50. In this case, the values ​​transmitted to the rotation function are formed in the range -50 - 50, but these values ​​are not enough for a steep trajectory rotation. Therefore, the range should be expanded by one and a half times to -75 - 75.

Finally, in the program, the calculator function is a simple proportional controller. whose function ( (a-50)*1.5 ) in the operating range of the light sensor generates the rotation values ​​in accordance with the graph:

An example of the algorithm

Example 2. One sensor, with PK controller.

This example is compiled on the same design.

You probably noticed that in the previous example, the robot swayed too much, which did not allow it to accelerate enough. Now we will try to improve this situation a little.

To our proportional controller, we also add a simple cube controller, which will add a twist to the controller function. This will reduce the swinging of the robot near the desired boundary of the trajectory, as well as make stronger jerks at a great distance from it.

Proportional controller

Description

In automatic control, the control action u(t) is usually a function of the dynamic error - the deviation e(t) of the controlled variable x(t) from its set value x0(t) :

e(t) = x0(t) – x(t).

This is the Polzunov-Watt principle of regulation by deviation, or the feedback principle. The mathematical expression of the functional dependence of the desired control action u0(t) on the values ​​measured by the controller is called the law or control algorithm, which was discussed above.

A proportional controller is a device that exerts a control effect on an object in proportion to its deviation from a given state:

Here k is the gain of the controller.

The specified state x0 is usually called the setpoint, and the deviation from it e is the residual. Further, for definiteness, we will denote the discrepancy by the abbreviation err (from the English word "error" - an error).

motor control

An experienced warrior will not brandish a sword, as a robot on a relay controller does. We need to come up with an algorithm that will hold the motor holding the sword in a strictly fixed position (Fig. 7.1). The P-regulator will help with this.

Let e ​​1 - readings of the speed sensor 1 on motor A - be an adjustable value. The setting x0 = 45, and the discrepancy e = 45 - e 1. Then the control action on the motor is given by the formula

u \u003d k ∙ (45 - e 1).

Here k is a gain factor, for example 5, which will increase the response of the motor even with small deviations from the setpoint.

1 Do not confuse the mathematical notation e (from error) with the encoder value e 1 (from encoder), a predefined Robolab environment variable.

With a deviation in the positive direction, a negative control action will be applied to the motor, and vice versa. This control can be applied to the motor in a cycle with a small delay of 1-10 ms to unload the controller (Fig. 7.8).

Rice. 7.8. Algorithm for controlling the motor on a proportional regulator.

If the gain is increased from 5 to 100, our proportional controller will start to act like a relay controller, causing strong oscillations due to the overshoot effect.

The RobotC language does not have such a convenient notation for encoder readings as in Robolab, so the program looks a little longer:

int k=5, u; nMotorEncoder=0; while(true)

u=k*(45-nMotorEncoder); motor=u;

Further, in order to inflict a “sword strike”, it is enough, having a variable instead of the number 45, to change its value from the outside, for example, from a parallel task. This is covered in the section on robot drummers in Chapter 8.

And now we will build a controller that controls not only the static position of the motor, but also the speed of its movement. Following the logic of the algorithm, the setpoint, which until now has been constant and has not changed, should start moving in the direction of increasing or decreasing. Obeying the regulator, the motor will inevitably follow it. The simplest tool for constantly incrementing the setpoint is a timer.

The NXT controller has four built-in timers, each of which can measure time in tenths, hundredths, and thousandths of a second. Let's master the first timer, which makes 10 “ti-

kov". In Robolab it is designated T1 or Timer100ms1, and in RobotC it is timer100.

The angle alpha of the motor deflection, given in the previous example by the value 45, will depend on the timer readings with an accelerating factor k 2:

alpha = k2 ∙ T1.

The control action will remain the same with the amplifying factor k 1:

u \u003d k 1 ∙ (alpha - e 1).

Briefly, in the program in the Robolab language, we will apply the control action immediately to the motor, after initializing the timer

Rice. 7.9. The motor speed control is one revolution per second.

The coefficient k 2 = 36 determines that in a second the value of alpha runs up to 360, which corresponds to one full revolution of the engine:

int k1=2, k2=36, u, alpha; nMotorEncoder=0; ClearTimer(T1); while(true)

alpha=timer100*k2; u=k1*(alpha-nMotorEncoder); motor=u;

Using the integer division accepted in the C language (and in Robolab) for variables of an integer type, it is possible to achieve a discrete change in the angle, i.e. incrementing it once per second:

alpha \u003d T 1 / 10 ∙ k 2.

With the coefficient k 2 = 60, the displacements of the beams will correspond to the movement of the second hand on the clock face. But it's not enough

noticeably. For clarity, you can set k2 = 30, then the arrow will make a full turn in 12 "ticks" of 30 degrees each. Be careful with the sequence of integer division and multiplication operations, if you change their order or “reduce”, the result will certainly change (Fig. 7.10).

Rice. 7.10. Accelerated imitation of the movement of the clock hand.

And finally, an example of a mathematical drummer. Instead of constantly moving forward, the arrow will oscillate back and forth under the control of the P-controller. This will help the division operation with a remainder, which in the C language is denoted by the sign %. The remainder of a non-negative integer divided by 2 will always be 0 or 1:

alpha = T 1 % 2 ∙ k 2.

By increasing the deviation by k 2=15 times, we get an oscillating setpoint alpha , which will force the regulator to move the motor 5 times per second either 0º or 15 degrees. The changes in the program are small. Consider an example in RobotC:

int k1=3, k2=15, u, alpha; nMotorEncoder=0; ClearTimer(T1); while(true)

alpha=timer100%2*k2; u=k1*(alpha-nMotorEncoder); motor=u;

This prototype drummer strikes the table at regular intervals. The main thing is to start in the right position. Using integer mathematics, you can also set a more complex rhythmic pattern, for example (Table 7.1):

alpha = T 1 % 5 % 2 ∙ k 2.

center = S3.

The coefficient is determined in the loop:

k 1 \u003d c + (S 3 - center) / k 2.

Rice. 7.36. Movement along the line on a proportional regulator with a floating coefficient.

The obtained gain control law can be applied not only to the proportional component, but also to any other, as well as to the control action as a whole (Fig. 7.36).

PID controller

The Proportional-Integral-Derivative (PID) controller is one of the most popular and is used in a huge number of devices of various types that require responsiveness and positioning accuracy of the system. As the name implies, this controller consists of the sum of three components and is graphically depicted in Fig. 7.37.

Rice. 7.37. Scheme of the PID controller.

This is a simplified diagram. The value of the dynamic error e (t) is fed to the controller input, and the control action u (t) is generated at the output:

u (t) \u003d p + i + d \u003d k p ∙ e (t) + k i ∙ ò t

e (τ)d τ + k d ∙

de.

The proportional component, shown in the diagram as a triangle, is responsible for positioning the system in a given state. In some cases, it can cause overshoot with subsequent self-oscillations. That is, the P-regulator can “overdo it” and the robot will begin to skid from side to side.

The integral component accumulates negative experience (sums up errors) and develops a compensatory effect. With minimal deviations, the proportional component “weakens” and the integral component, due to its rapid increase by summation, helps to “reach out” the controlled value to the setpoint.

The differential term (D-term) monitors the rate of change of the state of the system and prevents possible overshoot. In some cases, the D-component is opposite in sign to the proportional one, and in some cases it coincides.

We are already familiar with the proportional component, the differential component is described in the previous chapter 6. Let's take the integral. This component is determined dynamically, summing up with the previous value:

i = i + ki × e(t) × dt .

The physical meaning of the quantity e (t) × dt is that it pro-

proportional to the duration of the system being in an error state. Since the coefficient k i is taken out of brackets, we can talk about the value of i as the sum of the error durations. Thus, we find the integral by summation.

Consider the use of a PID controller using the example of a robot balancing on two wheels. This classic problem can be solved with various sensors in a variety of ways. The proposed example uses a light sensor and the simplest form of a PID controller. However, more accurate sensor readings will be required to achieve robot stabilization.

RAW format

Sensor data is sent to the NXT controller in raw form. All sensors transmit to the operating system a digital value from 0 to 1023, which is then processed by the appropriate driver and converted to a more understandable form (distance 0...255, illumination 0...100, touch 0 or 1, etc.). But data can also be received, bypassing the driver, directly. This raw format is commonly referred to as RAW (from the English "raw"). In some cases, it can be used to obtain greater accuracy. So, for example, the value range of the light sensor can increase by about 10 times. This possibility is used below.

You can receive data in RAW format in both Robolab and RobotC. To do this, the sensor is initialized accordingly, and data is read from it using a special predefined variable.

balancing robot

The design of the segway robot is shown in Fig. 7.38: vertically mounted controller, closely spaced wheels and light sensor pointing down. The algorithm will be somewhat more complicated.

The principle of stabilization of the Segway in the equilibrium position is as follows. If the robot leans forward, the ambient light sensor will increase due to the reflected light. In response to this, a control action is generated, forcing the robot to move forward and thereby again assume a vertical position.

When deviating back, the sensor readings decrease and the robot starts moving backward. The proportional component is responsible for all this. The role of the integral and differential components is assigned to insurance against overshoot.

Rice. 7.38. Balancing segway robot.

On fig. 7.39 shows the algorithm in Robolab. Most of it is occupied by the initialization of variables. To improve accuracy, not only data from the sensor is read in RAW format, but most variables are declared in real float format. The PID algorithm itself is in a loop.

Rice. 7.39. The balancer algorithm is based on the PID controller.

Following the tradition of moving along the line, we use the gray variable as the setpoint - the average readings of the light sensor in the equilibrium position. The new scale parameter specifies the scaling of the control action. This is essentially a dampening factor because the value generated by the ESC is too high for NXT motors. It would be possible to bring it inside the existing coefficients, but for RobotC this parameter will be different, and the coefficients are the same.

With the given coefficients, the robot is well stabilized on plain light linoleum or a desk. That is, it does not require a white surface color. To start, you need to accurately set the Segway to the equilibrium position. If the robot starts with a certain tilt forward or backward, it will immediately start moving in the direction of the tilt.

A similar example in RobotC is somewhat different for a number of reasons. Firstly, the performance of NXT with the firmware of this environment is about 1.4 times faster than that of Robolab, so the scale factor should be increased. Secondly, the RAW values ​​are transferred in the correct order and you will need to set the motors to reverse or just apply a negative control action:

int grey=Sensor Raw; int err, errold=0;

float kp=25, ki=350, kd=0.3; floatscale=14;

floatdt=0.001; float p, i=0, d, u; while (true)

err=grey-SensorRaw; //Reverse deviation p=kp*err;

i=i+ki*err*dt; d=kd*(err-errold)/dt; errold=err; u=(p+i+d)/scale; motor=u; motor=u; wait1Msec(1);

Elements of the theory of automatic control in school1

An important and interesting methodological task is to “transfer a bridge” between the fields of knowledge of a specialist and a student, helping school students to see the prospect of a future specialty, i.e. to carry out career guidance, and students to see the practical applicability of their professional knowledge. To achieve this effect, methods for calculating regulators were developed, using a mathematical apparatus that does not go beyond the framework of school programs in mathematics and physics. In particular, instead of differential equations, difference equations are used, which correspond well to the discrete nature of the interaction between the object and the controller under computer control.

Consider, for example, the problem of constructing proportional (P) and proportional-differential (PD) controllers in the problem of controlling the movement of a mobile robot along a wall. Let us denote by x t the distance between the robot and the wall, by θt - the heading angle of the robot, and by u t - the control action at the moment with the ordinal number t, respectively, where t = 0, 1, 2, ... are the numbers of the moments of change

rhenium. It is believed that polling sensors and changing the magnitude of the control action is carried out at regular intervals h. For the tasks of controlling Lego NXT robots, it is natural to assume that the control action is the difference in the angular speeds of rotation of the wheels, which is proportional to the rate of change in the heading angle:

Considering the deviations of the course from the nominal θt =0 as small, and the average speed of the robot is constant: vt=v , the dynamics of changes in the state variables of the robot in the first approximation can be described by linear state equations:

where g = h2vr / b.

We set the desired distance to the wall x*> 0 and define the control goal (CC) by the ratio

xt → x* as t→∞.

Now, we naturally introduce the concept of asymptotic stability at the substantive level, as a property of solutions to system (4), which ensures the achievement of CC (5) under any initial conditions that differ little enough from the target ones. It is easy to see that at u t = 0 the solution to equation (4) is any constant value x t = x* . But since equation (4) corresponding to the double integrator (double adder) model does not have the property of asymptotic stability, CU (5) is not achieved under constant control. This is easily demonstrated as analytically - summation of the series

Robotics is a new interesting direction, which, apparently, will be further developed within the framework of school courses in computer science and technology. The boom of robotics is largely due to the fact that it allows you to answer the question: "Why do we actually learn programming?". In addition, in the course of robotics, you can get acquainted with the elementary concepts of the theory of automatic control.

This page presents the simulators for programming and Arduino boards developed by the author. They can help in cases where for some reason it is not possible to use real hardware.

The trainers use HTML5 features, so they will only work in modern browsers (it's best to use Google Chrome or Mozilla Firefox).

news now in the Telegram channel

November 27, 2015
The “germ” track has been added to the simulators ( M.V. Lazarev, Orekhovo-Zuevo).

October 13, 2015
Now in the simulators for the LEGO robot, you can upload your tracks (fields for the robot). How to do it? See.
Added new simulators - LEGO robots with two , three , four light sensors.

Robot control language

To control robots in simulators, a simple programming language is used, which received the working title SiRoP (Simple Robot Programming).

Robot control with light sensor

The light sensor allows the robot to navigate on the table surface, for example, to move along the border between the white and black areas (along the edge of the black line). The photodiode illuminates the surface, the photodetector "catches" the reflected rays and measures their intensity.

The most popular task of this type is moving along a line. With the help of the simulator, you can study various control laws - relay, proportional, and even PID control (proportional-integral-derivative).

Examples of programs for a robot with a light sensor

While 1 ( if sensor > 128 ( motor = 100 motor = 0 ) else ( motor = 0 motor = 100 ) wait(10) )

KP = 0.2 while 1 ( u = kP*(sensor-128) motor = 50 + u motor = 50 - u wait(20) )

Main ( while 1 ( while sensor > 128 ( motor = 100 motor = 100 wait(10) ) back() turn() ) ) back ( motor = -100 motor = -100 wait(260) ) turn ( motor = -50 motor = 50 wait(50) )

Robot control with two light sensors

Two light sensors allow the robot to better navigate and follow a thin line. They are brought forward a little and parted to the sides. As for tasks with a single sensor, using this simulator, you can study various control laws.

Example programs for a robot with three light sensors

Robot control with four light sensors

Four light sensors allow the robot to better detect sharp turns. Internal sensors are used for fine adjustment, proportional control is used for them. Two external sensors are placed a little forward and separated to the sides. They are used when there is a sharp turn. The gain factor for control according to the readings of the sensors of the outer pair is selected larger than for the inner pair (see Fig. L.Yu. Ovsyanitskaya et al., Algorithms and programs for the movement of the Lego Mindstorms EV3 robot along the line, M.: "Pero", 2015).

Example programs for a robot with four light sensors

While 1 ( d0 = encoder > 128 d1 = encoder > 128 d2 = encoder > 128 d3 = encoder > 128 if d1 & !d2 ( motor = 100 motor = 0 ) if! d1 & d2 ( motor = 0 motor = 100 ) if d1 == d2 ( motor = 100 motor = 100 ) if d0 & !d3 ( motor = 30 motor = 0 ) if! d0 & d3 ( motor = 0 motor = 30 ) wait(10) )

K1 = 0.2 k2 = 0.4 while 1 ( u1 = sensor - sensor u2 = sensor - sensor motor = 50+k1*u1+k2*u2 motor = 50-k1*u1-k2*u2 wait(10) )

Controlling a robot with a distance sensor (sonar)

The distance sensor (sonar) allows you to determine the distance to the nearest obstacle while the robot is moving. It emits an ultrasonic signal and receives the reflected signal. The longer the time between the transmitted and received signals, the greater the distance.

Using a distance sensor, a robot can be programmed to automatically navigate a maze of known shape but unknown size.

A proportional controller is a device that exerts a control action u(t) on an object in proportion to its linear deviation e(t) from a given state x0(t);

e(t)=x0(t)-x(t), where x(t) is the state at a given time;

u(t)=ke(t), where k is the amplifying factor.
That is, the further the robot deviates from the set course, the more actively the motors should work, leveling it.

Walking in a line with one light sensor using a P controller

Movement along the border of black and white can also be built on the P-regulator. Although outwardly the task seems to be solved only with the help of a relay controller, since there are only two states visible to the human eye in the system: black and white. But the robot sees everything differently, for it there is no sharp border between these colors. We can say that he is short-sighted and sees a gradient transition of shades of gray.

This is what will help to build a P-regulator.
Defining the state of work as the readings of the light sensor, we will learn how to provide a proportional control effect on the motors according to the following law:
e=s1-grey, where s1 is the current sensor reading and gray is the set value.

The coefficient k (equal to 2 in this example) must be sufficiently small (between 1 and 3). Such a controller works effectively only for small deflection angles, so the robot must be placed in the direction of movement so that the sensor is on the left side of the black line. It is easy to see that the movement along the line on the P-regulator is smooth. and in some areas of work it moves almost rectilinearly or exactly repeating the bends of the line.

Sensor calibration

Let's look at the number 48 used in the formula. This is the arithmetic average of the light sensor reading on black and white, for example (40+56)/2=48. However, the readings of the sensors often change for various reasons: a different surface, a change in the general illumination in the room, a slight modification of the structure, etc. Therefore, we will calibrate the robot manually by determining the readings of the light sensor on white and black.

Line tracking with two light sensors using a P controller
It is quite difficult to drive through an intersection correctly with one light sensor. If you want to do this at a fast enough speed, you need at least two sensors spaced at least two line widths apart (or wider).
There are four states of the sensor when moving:

  • both on white - straight ahead;
  • left (s1) not black, right (s2) on white - move to the left;
  • left on white, right on black - movement to the right;
  • both on black - go straight.
That. if the sensor readings are equal (both white or both black), the robot goes straight. Before starting the robot, we will auto-calibrate both sensors. Then the algorithm of movement along the line with the P-controller will look like:

The coefficient k can vary in a fairly wide range (from 1 to 20 or more) depending on the curvature of the line, the maneuverability of the robot and the difference between black and white on the field.
Important condition. Autocalibration should be carried out on a single-color surface and preferably at the illumination that will occupy the largest part of the path. For example, if the robot moves along the black line on a white field, then it is necessary to calibrate on a white one. Those. the position of the robot at the start should be like this:


And another note. There are sensors whose readings differ by 10-20%. It is advisable not to pair them with a controller with a large coefficient, since with a sharp change in the overall illumination, even on a uniform white field, the deviations may turn out to be different, which will lead to unexpected consequences.