0

Line Robot - Basic lessons - || and &&

We learned how to stop a robot when one transistor spots a black surface. Now suppose we want it to stop if any of the transistors senses black. There is a clumsy way to achieve the goal and here it is (don't do this!):
void RobotLine::loop() {
	if (setup())
		go(50, 50);	

	if (line(0))
		stop();
	else if (line(1))
		stop();
	else if (line(2))
		stop();
	else if (line(3))
		stop();
	else if (line(4))
		stop();	
	else if (line(5))
		stop();
	else if (line(6))
		stop();	
	else if (line(7))
		stop();	
	else if (line(8))
		stop();	
}
First 2 lines make sure that the motors are started only once, in the first run of "loop()" function. This stresses our intention to start them only once.

Yes, You can nest if-commands like above, but the point is that the code is long and difficult to understand. We are lucky that C++ (like other languages) has or logical operator. Its format is:
logicalExpression1 || logicalExpression2
The "||" is the or-operator. The meaning is: if any of the logical expressions logicalExpression1 or logicalExpression2 is true, the whole expression is true. That's natural. Look at the example:
if (6 < 2 || 6 < 9)
	print("Yes");
Will the code fragment print "Yes" or not? Of course it will. 6 < 2 is not true, but 6 < 9 is. Therefore, as at least one of the expressions is true, the whole expression is true. This logic is natural.
Besides "or", the other logical operator is "and", in C++ notation "&&". The whole expression takes this form:
logicalExpression1 && logicalExpression2
The result is "true" only if both logicalExpression1 and logicalExpression2 are "true". Otherwise is "false". A few expressions that evaluate as "true":
  • 1 < 2 && 2 < 3
  • 1 < 2 && 1 < 2
Now some that evaluate as "false":
  • 1 < 2 && 2 < 1
  • 2 < 1 && 2 < 1

Task: stop if any sensor detects a line.

Write a program that will stop the robot if any transistor encounters a line.