Line follower - a solution I do not understand


#1

image

I have found this code to follow line (black on white background) in a past post (which is now closed).
I am “recycling” the image 'cause there is something I do not understand:

  1. The last if has the same instruction “turn right” in both cases… Why?
  2. One reaches at the last if only if previouses if are not true (so l1r1 or l1 or r1 are not on the black line). That should mean that l1 and r1 are both on the background… In this case the mbot should stop and go back… why “go right”?

May be I didn t get the whole sense of the nested ifs


#2

@Mrb A link to the post would be helpful. :slight_smile:

The whole point of the nested if statements is to only allow one action to happen at a time (move forward, turn left, or turn right) since multiple conditions could be met at once otherwise.

Here is the logic of the code:

  • If the left and right of the sensor are over the line, move forward
  • If the right sensor stops detecting the line, we need to turn left to correct
  • If the left sensor stops detecting the line, we need to turn right to correct
  • If no sensors detect the line, the second turn right block (the one you were confused about) will cause the robot to turn right in search of the line (simply driving straight forward wouldn’t usually be the best way to find the line again, so we just turn until we find it).

Does that help?


#3

It helped. As usual. :wink:Thank You .
Am I wrong or?:
Since that last if statement Will do the same instruction (“turn right”) in both cases, one could delete the if and replace it with the “turn rigth” instruction.