9 Lego Mindstorms Corrected Exercises

This series of corrected exercises on Lego Mindstorms allows you to become familiar with programming and robotics software.

Lego Mindstorms

Exercise 1

In this exercise, you will learn how to program the robot to perform simple movements. Understanding how to make your robot perform its movements is essential because it will constantly need to perform them in the following exercises.

Using the programming guide provided to you, please program your robot
so that it performs the following actions:

move forward for a period of 3 seconds,

go back for a period of 3 seconds,

turn to the left then to the right.

This exercise aims to simply explain how to program the robot using LEGO software. There are two ways to approach these problems:

either by using the Move block (which allows you to control both motors at once), or by using two Motor blocks (one for each motor, which allows you to control each motor independently).

The second way uses loops so it is best to approach it if students are comfortable with this notion (which will be seen in the second exercise).

– move forward for a duration of 3 seconds, Place a Move block, check motors B and C and enter 3 seconds as the duration.

– go backwards for a duration of 3 seconds, Same as for the previous exercise except that you must select the “Backward” direction.

– turn on angles to the left then to the right. Place the “Direct” cursor either all the way to the right or all the way to the left.

Exercise 2

and in programming, a loop is a control structure that allows a series of instructions to be repeated as long as a condition is true or is not met (depending on the type of loop used). There are several types such as for example While (condition) do. A loop can also be infinite, that is to say that its instruction block will be repeated indefinitely (more concretely: until stopped manual  from the program).

The robot is equipped with a number of sensors (a more precise description of each is given in the guide provided). These sensors make it possible to measure different parameters of the environment in which the robot operates. It is possible to use these measurements as a condition for stopping the loops and this is what will interest us later.

An infinite loop therefore allows us to have the robot perform an action (or a sequence of actions) without any particular stopping condition.

  1. Make your robot perform an unlimited circle-shaped trajectory
  2. Move forward and backward (only a short distance) unlimitedly
  3. Loop with stop condition

Une  boucle  s’utilise  le  plus  généralement  avec  une  condition  d’arrêt,  c’est-à-dire  que  l’ensemble  des instructions  du  corps  de  boucle  ne  s’exécuteront  que  tant  que  la  condition  précisée  serait  vraie  (d’un point de vue logique). En pseudo-code, une boucle s’écrit de la manière suivante :

As long as (condition) TO DO

     instructions

End While

You will then be asked to think about the algorithms of your programs and write them in the form of pseudo-code. The pseudocode is a language  close to natural, that is, when writing the algorithm you do not need to think about the implementation (how to translate it into the programming language).

In the case of our robot, we can put logical operations, a counter or sensors as conditions and this is what we will see here. For example, let's admit that our robot has a noise detection sensor (this is not the case in reality) and that we want it to move forward until it detects a noise, a pseudo-algorithm. code would be: algorithm en pseudo-code serait :

As long as (undetected noise)

      Move forward()

End While

When it detects the noise, it will stop repeating its block of instructions.

For each of the following actions and using a separate sensor, write a small algorithm in pseudo-code then program it:

  1. Move the robot forward then stop 20 cm from an obstacle,
  2. Make the robot move forward then stop when it comes into contact with an obstacle,
  3. Make the robot move forward then stop when it sees a color on the ground.

Infinite loop

  1. Make your robot perform an unlimited circle-shaped trajectory 

To do this, you must use two blocks Engines  and place them in an “unlimited” loop. To make the trajectory in a circle, one motor must rotate faster than the other (play on the “Power” parameter) such as B at 75 and C at 40.

  1. Move forward and backward (only a short distance) unlimitedly

You must put two motor units to move forward (same power, same direction, same duration) in an infinite loop, then put two motor units back to move backward (the direction must be reversed in relation to the action of moving forward).

Please note, for the two motors to be active in parallel, the duration must be in degrees (for example 500) or rotations and the first of the two motor blocks (for each action), must have the “Wait for end” option unchecked.

lego mindstorms

Loops with stopping conditions

  1. Move the robot forward then stop 5 cm from an obstacle,

While (distance() 5)

     move forward()

End While

The loops used by the LEGO programming software are not While, that is, the condition of the loop is the condition of exit loop and not the validity condition.

Here, the loop must therefore have the ultrasonic sensor as a “Control” parameter and as a “Until” condition. < 5 cm”. This loop must contain two blocks Engines for motors B and C with the same power and the same direction and whose duration is “unlimited”.

lego mindstorms

  1. Make the robot move forward then stop when it comes into contact with an obstacle,

While (TouchSensor not pressed) do

     Move forward()

End While

The loop must contain two blocks Engines  for motors B and C (same power, same direction, unlimited duration) and have one of the touch sensors as control with the condition “Action: pressed”.

lego mindstorms

Please note: this version is simple but the robot only stops when it comes into contact with a single sensor. It is nevertheless possible to use a logical equation to bring the two sensors into play (the robot stops with the contact of one of the two sensors). To do this, you must use two “Touch Sensor” blocks and construct the following logic equation (which you enter as a condition in a loop with “Logic” as a control):

E = 1 + 2

lego mindstorms

  1. Make the robot move forward then stop when it sees a color on the ground.

The color chosen doesn't really matter, but black is a practical choice because it can be measured with the color or brightness sensor.

While (color() /= black) do

     Move forward()

End While

The loop must contain two blocks Engines  for motors B and C (same power, same direction, unlimited duration) and have as control the color sensor in “Color” mode with the condition “Up to the range” and the cursors framing black.

lego mindstorms

The color sensor can be used in “Photosensitive” mode for this exercise if the stopping color is black. To do this, in the “Photosensitive” mode set the condition “Until < X" Or  X is an upper limit of black to be determined by measurement on the support used as a test track.

Exercise 3

You will have to program your robot so that it counts the colors. He must be able to advance along an area comprising a succession of colored areas, although the end of this area is marked by a black band. He must therefore count the number of times a colored strip appears while moving his screen forward. At the end of the course, it will display the number of color zones on the screen.

  1. Write an algorithm corresponding to this problem in pseudo-code
  2. Implement your algorithm in your robot

The goal of this exercise is to reuse what has been seen so far (loops, sensor) while introducing the notion of variable (from an algorithmic point of view and at the level of the robot programming software).

  1. Write an algorithm corresponding to this problem in pseudo-code

ColorPrevious color() NbRed 0

NbYellow 0

NbBlue 0

While (ReadColor() =/    BLACK) do

     While (color() = PreviousColor)

          Move forward()

     End While

     If (color() = RED) then NbRed = NbRed + 1

     If (color() = YELLOW) then NbYellow = NbYellow + 1

     If (color() = BLUE) then NbBlue = NbBlue + 1

     End if

     ColorPrevious color()

End While

color() is a function that returns the numerical value of the color read by the color sensor.

This algorithm works as follows: the robot advances as long as it is still in the same color zone then as soon as it has changed zone, it then increments the variable associated with this color. It ends up updating the PreviousColor variable to detect the change of zone on the next loop. The whole thing is in a black detection loop which will stop the robot as soon as it reads black.

  1. Implement your algorithm in your robot

To program it, we must first create the variables that will be used later (Previous Color, Red, Blue, Yellow); they are of digital type and initialized from the start of the program.

Then we place a main loop with the control “Color sensor” and the action “Up to the black range”. Within this loop we put back a loop containing two motor blocks to move the robot forward (duration set to “Unlimited”). The control of this loop must be placed on “Logic” with as input a comparison operation between the “Previous Color” variable and the color sensor:

lego mindstorm

After this loop, we place three switch blocks (one for each color) in which we execute the operation of incrementing the associated color variable. Here for example is the red one:

lego mindstorms

Then, after these three switches, we do not forget to update the “Previous Color” variable with the color sensor (as during initialization).

After the loop  main, we display the content of the color variables on the screen or with sounds.

Exercise 4

The robot must follow a black path on the ground, the ground being white.

  1. Write an algorithm corresponding to this problem in pseudo-code
  2. Implement your algorithm in your robot.

Bonus question: can your program follow all types of routes?

  1. Write in pseudo-code an algorithm corresponding to this problem

As long as (true) do

     While (color() = BLACK) do

          ShiftLeft()

     End While

     While (color() = WHITE) do

          DeviateRight()

     End While

End While    

color() is a function that returns the numerical value of the color read by the color sensor.

DeviateLeft() and DeviateRight() are functions that move the robot forward by deviating to the left or to the right.

A line follower actually follows not the line but the edge of the line (the boundary between white and black). The algorithm presented here is very simple. Within an infinite loop, we place two loops: one for black and one for white. The black loop deviates the robot to the left as long as it reads black, and the white loop deviates the robot to the right as long as it reads white. Thus, the robot alternates movements to the left and to the right.

Note: this algorithm corresponds to a “left follower”, that is to say in the case where white is to the left of black. We can make a “right follower” by reversing the direction of deviation.

  1. Implement your algorithm in your robot

To implement it in the robot, we first place a “loop” block with “Forever” as a control.

In this block, we then place another loop but this time with the control “Color sensor” in “Photosensitive” mode and with the action “Until < 35” (35 is a value of the upper limit of black brightness, this value must be determined by measurement during the session because it can vary depending on the lighting or the test track used).

Inside this loop, place two “Motor” blocks for each of the two motors, one of which has a lower power than the other (to deviate to the left, motor C must go slower than B ). Make a similar loop for the white with this time action positioned on “Until  > 35” and the motor powers reversed.

The difference between the respective powers of the motors will affect both the overall speed of the robot (the time it will take to make a complete turn) and its ability to follow a path more or less twisted. To do this, do not hesitate to do several tests with different values to find a good compromise (correct values are for example 75 and 10).

lego mindstorms

Bonus question: can your program follow all types of routes?

Normally this program does not allow you to follow all types of tracks. Indeed, as soon as the route becomes too complex, the robot should no longer be able to follow (unless one of the two motors is almost stopped, which will then make it very slow). It cannot follow an inside or too tight turn, nor a right angle turn. To be convinced, don't hesitate to perform it on the bonus circuits.

Exercise 5

When carrying out certain tasks, your robot often has to repeat standard actions several times, such as turning 90° to the right or moving forward 10 cm. For'alleviate  your program, it is possible to create personalized blocks which are subsequently used like the default blocks (in this way, instead of having several times the different blocks which manage the angle calculations and the activation of the motors, we only use one several times). This principle is similar to functions (or procedures) in algorithmics.

As a reminder, in algorithmics, a function is a sequence of instructions relatively independent of the main program and which is repeated several times. This sequence of instructions is then grouped into a single instruction block which is the function.

Using the programming guide (and more particularly the block creation section) as well as the appendix on distance and rotation calculations, create the following personalized blocks:

  • Move forward: moves the robot forward according to the distance given as input (this distance will be in centimeters),
  • Back up: moves the robot back according to the distance given in input (this distance will be in centimeters),
  • TurnRight: turns the robot at a given input angle to the right,
  • TurnLeft: turns the robot at a given input angle to the left,
  • RotateRight: rotates the robot at a given input angle to the right,
  • RotateLeft: rotates the robot at a given input angle to the left

Now, using the blocks you just created, please create a program that allows your robot to perform this trajectory:

lego mindstorms

You must therefore use the programming guide as well as the appendix on distances and rotations to create the blocks and implement the formulas using the operation blocks.

– Move forward: moves the robot forward according to the distance given as input (this distance will be in centimeters),

It is therefore necessary to code the formula distance*360/13.5 using constants for 360 and 13.5 and a variable in reading mode for the distance; then give the result as the input value of a block Move set to a duration in “Degrees”. To create the block, simply select all these blocks except the variable block for the distance, then go to To modify → Create new block My block :

lego mindstorms

  • Back up: moves the robot back according to the distance given in input (this distance will be in centimeters),

You must code the same formula as for the block Move forward but this time the block Move must be set to rotate the motors in the other direction.

  • TurnRight: turns the robot at a given input angle to the right,

This time, it's the formula angle*2pi*15.5/13.5 and put the result at the input of motor C (motor B must be deactivated).

lego mindstorms

  • TurnLeft: turns the robot at a given input angle to the left,

The formula remains the same as before but this time it is motor B which is activated and motor C which is deactivated.

  • RotateRight: rotates the robot at a given input angle to the right,

The formula is almost the same as before except that we remove the coefficient 2 (the circle described being half as large). Furthermore, the result of the calculation is given as input to engines B and C this time; the C motor going forward and the B motor going backwards.

lego mindstorms

  • RotateLeft: rotates the robot at a given input angle to the left. Same formula as for the previous block except that the directions of the motors are reversed

The files are to be placed in the Blocks/My blocks folder of the profile folder: Forward.rbt, Backward.rbt, RotateLeft.rbt, RotateRight.rbt, PivoterLeft.rbt, PivoterDroite.rbt

The trajectory to then be made by the robot is rather simple with the blocks. It is therefore necessary to place the blocks successively Move forward, RotateRight, Move forward, RotateLeft, Move forward, RotateRight, Move forward, SwingRIGHT, Move forward, RotateRight with associated distances and angles. Be careful, however, to take the correct angle value for the pivots (you must take the value of the additional angle).

lego mindstorms

Exercise 6

A l’aide d’un graphe d’état (automate à état fini), donnez le programme au actions suivantes.

  1. Stop at the right place

The initial state considers the robot in white, this allows you to start the robot from anywhere (i.e. white or black). Each time it changes color (black or white), it will move to the next state. Each state has the associated action of moving forward except the state following the third transition black (which therefore corresponds to the third time that the robot encounters a black zone) where the robot stops.

lego mindstorms

 2. Détection d’obstacle, le robot avance tout droit puis recule s’il heurte un obstacle

lego mindstorms

3. The robot goes straight ahead then turns right (resp. left) if it encounters an obstacle on the left (resp. right) or turns around if the obstacle is in front of it.

lego mindstorms

1.

To program this state graph, you must first create a numeric type variable state which will contain the current state. It will be initialized to 0 at the start of the program. We add within a loop so the condition is until state = 5, a first switch on the value of the variable state which will allow the value of the current state to be changed according to the actions detected (reading white or black) followed by a second switch also on the value of the variable state which will determine the actions to be performed in each state:

lego mindstorms

2.

You must proceed in the same way as for the previous program: two switches; one for transitions and one for actions. However, in the file provided as a correction we grouped these two switches into one to show that this was also possible. Changing the variable state is therefore done at the end of the action loop. This way is more compact but a little less clear and organized but remains possible and functional.

lego mindstorms

3.

We therefore use the same program structure as before but this time clearly differentiating the contact on the left or on the right.

lego mindstorms

Exercise 7

We will try to program the robot so that it searches for an object in a space delimited by a black line and takes it out of this space. Your program must therefore include two distinct phases: a first of searching for the object and a second of removing the object from this space (it will remove the object by pushing it outwards).

 Your program must be  clever  : you do not have to program the robot so that it goes directly to the object (the latter can be located anywhere in space). In addition, the robot will have to start in a very distinct position. Here is an example of object placement:

  1. Describe a simple algorithm to perform this task,
  2. Create a program that performs these actions based on the algorithm.

lego mindstorms

1.

lego mindstorms

First, the robot advances until it either encounters darkness or touches an object. If it encounters black, it backs up and then rotates at a random angle (between 0 and 180 degrees) then leaves again. If it comes into contact with an object, it then continues to advance until it encounters black; he will then have taken the object out of the frame.

2.

To program this, we start by placing a loop with the logical condition that one of the tactile sensors is pressed (so use the blocks for these sensors with a logic block OR ). We then place inside this loop a loop with the logical condition Black OR (Touch1 OR Touch2), we stop the motors at the exit of this loop so that the robot does not leave the frame if the loop stopped because it saw black:

lego mindstorms

We then place a switch to see if the loop was interrupted because the robot saw black. In this case, we place a block To move back – created in the previous exercise – followed by a block Random which takes a number between 0 and 180 and gives it as input to a block RotateLeft.

lego mindstorms

After the main loop, we place a loop making the robot move forward until it sees black.

Exercise 8

As in the previous exercise, we will program our robot so that it searches for an object in a space. Except that in this version we will use the ultrasonic sensor. It is therefore a question of programming the robot so that it first searches in which direction the object is located, then it moves towards it and stops 5 cm away.

  1. Write an algorithm corresponding to this problem in pseudo-code
  2. Implement your algorithm in your robot

1.

lego mindstorms

Here, rather than blindly searching for the object, the robot will search in which direction it is located. To do this, the sensor will scan the entire space in front of the robot (the sensor will rotate through an angle of 180˚) and look for the shortest distance to an obstacle (on the same principle as a minimum search algorithm in a painting) ; it will memorize the angle to deduce the direction in which the robot will go.

2.

First, we rotate motor A 90˚ to the left to orient the ultrasonic sensor, then we place a sensor block just after Rotation to reset the value returned by the latter. We then store in a variable distanceMin the value returned by the ultrasound sensor and we initialize another variable corner to 0. And finally, we start a slow rotation of A towards the right:

lego mindstorms

We now place a loop in which we will carry out the comparisons to find the angle of the minimum distance. This loop controls the rotation sensor of motor A and as a condition until > 180˚. At the start of the loop, we store in Number 1 the distance measured by the ultrasonic sensor and in corner the value returned by the rotation sensor of A. Comparisons and possible assignments are then made with these variables.

lego mindstorms

Finally, after the loop, motor A is stopped and then rotated 90˚towards the left to refocus the ultrasonic sensor. We then rotate the robot according to the value of corner then we advance it up to 5 cm from the object:

lego mindstorms

ANOTHER APPROACH:

We slowly rotate the ultrasonic sensor until there is an obstacle and at this moment we make the robot move towards it. This approach therefore assumes that the space in front of the robot (therefore over a given distance, for example 40 cm) only contains the desired object, it therefore remains less good than the previous one but simpler to understand, which is why it is presented here:

lego mindstorms

The program therefore closely resembles the initial version, except that the rotation of motor A stops as soon as it detects an object.

lego mindstorms

Exercise 9

We will now program the robot so that it is able to escape from a maze simple. Be careful, finding a path to cross a maze is a difficult problem from a computer point of view (we speak of a problem NP-Complete ), this is why all the proposed mazes are simple because you are not asked for an efficient algorithm for all the mazes.

A- Basic maze

The first type of maze is made up only of high walls (25 cm). Here is his plan:

lego mindstorms

You will therefore have to program your robot so that it crosses it. To do this, you will need to use the ultrasonic sensor to determine which way to go at each intersection.

  1. Rédigez en pseudo-code un algorithme naïf permettant au robot de traverser un tel labyrinthe
  2. Implement your algorithm in your robot

B- Advanced maze

We now modify the maze by replacing a high wall with a low obstacle (10 cm).

How can I make the robot always go through the maze?

  1. Modify the previous algorithm to take this change into account
  2. Implement your modified algorithm into your robot

C- Impasse

We will now take this labyrinth layout:

lego mindstorms

As you can see, this maze has a dead end. What to do if your robot ends up in it?

  1. Modify the previous algorithm to take into account deadlocks
  2. Implement your modified algorithm into your robot
  3. Bonus question: can he get through all the mazes?

HAS-

Ce premier type de labyrinthe ne comporte qu’un chemin qui mène directement à la sortie. Le but est de comprendre le comportement du robot au sein de ce labyrinthe ; c’est-à-dire avancer jusqu’à un mur puis chercher de quel côté tourner. 

Pour savoir de quel côté tourner, on peut avoir plusieurs approches, comme par exemple regarder arbitrairement à gauche pour voir s’il y a un obstacle et le cas échéant tourner à gauche sinon à droite. Dans l’algorithme (et donc le programme proposé) suivant, à chaque intersection le robot tourne du côté où l’obstacle est le plus loin. Voici l’algorithme :

lego mindstorms

The robot advances up to 15 cm from the wall then stops. He then measures the distance separating him from the wall on the left then from the wall on the right. it then turns to the side where this distance is greatest and then begins to move forward again. He stops as soon as he sees red.

We start by placing blocks Variable in fashion To write to initialize variables distanceLeft and distanceRight to 0. Then, we place a loop with the color sensor as control and the stopping condition All the way to the red beach (this loop will end the program when the robot is at the end of the maze).

We then place a loop to move the robot forward to an obstacle. It must therefore contain two blocks Engine for B and C with a as duration Unlimited

. Be careful, the robot must stop (and therefore exit this loop) either 15 cm from an obstacle, or when it sees red; the control must therefore not be the ultrasonic sensor but a logical equation constructed with two sensor blocks (ultrasonic sensor set to distance less than 15 cm and color sensor set to dans la plage rouge) :

lego mindstorms

La suite du programme est l’ensemble des instructions correspondant à choisir de quel côté le robot va tourner. Cette partie prend place au sein d’un commutateur avec comme contrôle le capteur de couleur et réglé sur Hors de la plage rouge ; en effet, cela permet de ne pas effectuer la recherche d’obstacle si le robot s’est arrêté. 

La première étape consiste donc à faire tourner le moteur A vers la gauche puis d’enregistrer la valeur retournée par le capteur ultrason dans distanceLeft, puis de faire tourner le moteur A vers la droite et d’enregistrer la valeur retournée par le capteur ultrason dans distanceRight. On compare ensuite les deux variables et dans un commutateur logique qui prend en entrée le résultat de la comparaison, on utilise les blocs RotateRight Where RotateLeft créés dans un exercice précédent (avec 90 comme valeur d’angle en entrée) pour tourner du bon côté :

lego mindstorms

B-

We now modify the maze by replacing a high wall with a low obstacle (10 cm).

Pour prendre en compte ce changement, il faut ajouter l’utilisation du capteur tactile. On va donc faire s’arrêter le robot s’il touche un obstacle qu’il n’aurait puˆ voir avec le capteur ultrason.

lego mindstorms

L’algorithme est quasiment le même que pour la question précédente. Seule la condition de la boucle pour faire avancer le robot a changé : le robot arrête d’avancer s’il est à 15 cm d’un obstacle OU s’il touche un obstacle. Après cette boucle, on ajoute une condition pour vérifier si c’est le second cas (capteurs tactiles) qui a fait s’arrêter le robot, et si c’est le cas, on le fait reculer de 15 cm. La suite de l’algorithme est inchangée.

Il suffit donc de reprendre le programme précédent et d’y apporter quelques modifications et ajouts. Il faut modifier l’équation logique de contrôle de la boucle qui fait avancer le robot jusqu’à un obstacle. Le robot doit maintenant en effet s’arrêter s’il est à 15 cm d’un obstacle ou s’il voit du rouge ou s’il rentre en contact avec un obstacle. On doit donc ajouter les blocs correspondants aux capteurs tactiles 1 et 2 avec un bloc logique (type OR ) :

lego mindstorms

Après cette boucle, on place un commutateur pour vérifier si on est sorti de la boucle à cause des capteurs tactiles et faire reculer le robot de 15 cm le cas échéant (pour cela, on peut utiliser le bloc créé pour reculer) :

lego mindstorms

C-

Le robot est dans une impasse si, lorsqu’il est arrêté (donc bloqué par une paroi face à lui), les parois à gauche et à droite sont trop rapprochées de lui (la distance mesurée à gauche est inférieure à une certaine distance – ici on a choisi 20 cm –, idem pour la distance mesurée à droite). Il faut donc modifier la condition pour décider de quel côté tourner :

lego mindstorms

L’algorithme est donc très similaire au précédent. On a ajouté la condition Si (distanceGauche < 20 ET distanceDroite < 20) qui permet de détecter une impasse et donc fait faire demi-tour au robot si c’est le cas. Sinon la décision du côté duquel tourner reste la même.

Pour détecter les impasses, on reprend le programme du labyrinthe avancé et on place les blocs servant à déterminer de quel côté le robot va tourner dans un commutateur ayant comme contrôle une valeur logique : la valeur sera le résultat de l’équation distanceLeft < 20 ET distanceDroite <20 :

lego mindstorms

To share