[RL83] Grade 8 - Session 3

Session 3: Obstacle Detection with Variables and Expressions

Duration: 60 minutes


Equipment Required:

  • M3D Robotics kit with distance sensor
  • Laptops with Arduino IDE
  • USB/OTG cables to connect the robot to the laptop
  • Projector for live coding demonstration
  • Paper and pencils for students to document their observations

Learning Objectives:

  • Introduce variables as memory storage for the robot to hold and manipulate values.
  • Explore basic variable types: int, float, string, and bool.
  • Program the robot to detect obstacles, count occurrences, and display messages.
  • Use variables in real-time obstacle detection and add expressive responses to robot states

1. Introduction to Variables as Robot Memory (10 minutes)

Activity:
Begin with a relatable discussion on memory and its role in everyday life. Explain that variables serve as a “memory” for the robot, allowing it to remember important details, just as we do.

Discussion Examples:
You may say:

“Imagine you’re at the grocery store keeping track of items as you shop. You remember you need eggs, milk, and bread. Your memory helps you remember the items even as you move around the store. And as you get the items and put them in your basket, you start to take those items off your mental list.”

“In a similar way, a robot can remember things it encounters using ‘variables.’ A variable acts as the robot’s memory. And just like how our memories can change — we might forget an item or add something new — the robot’s memory can also change while it works!”

Introduce the different types of variables with simple examples:

  • int: Holds whole numbers, like the count of obstacles encountered.
  • float: Holds decimal numbers, such as the exact distance to an obstacle.
  • string: Holds text, like a message saying “Moving” or “Obstacle Detected.”
  • bool: Represents a “true” or “false” condition, often used to check whether something is happening or not.

You may say:

“For example, a bool variable can be like a simple yes-or-no answer. It can remember if something is true or false. Imagine asking yourself, ‘Is there an obstacle ahead?’ If yes, that’s true, and if no, that’s false. This can help the robot make quick yes-or-no decisions during its tasks.”

Teacher’s Role:
Explain how different types of variables help the robot “remember” various information, such as numbers, decimal values, text, or simple conditions (true/false).

Write down four types of variables on the projector:

int obstacleCount = 0;           // Count of obstacles encountered
float distance = 0.0;            // Distance to an obstacle
string message = "Moving";       // Status message
bool obstacleDetected = false;   // Condition: Is an obstacle detected?

Encourage students to think of other examples where variables help keep track of simple yes-or-no conditions, such as “Is the robot moving?” or “Is it at the starting point?”


2. Creating and Modifying Variables (10 minutes)

Activity:
Demonstrate how to create variables in the code and change their values based on the robot’s actions.

Example Code for Setting Variables:

int obstacleCount = 0;           // Holds the count of obstacles detected
float distance = range.get_cm(); // Holds distance from an obstacle in cm
string message = "Moving";       // Message to display on the screen
bool obstacleDetected = false;   // Flag to check if an obstacle is detected

Explain that as the robot moves, it can change these values to “remember” its surroundings. Show how the obstacleCount can increase each time it encounters an obstacle and how distance updates whenever the distance sensor reads a new value.

You may say:

“Just like how we can change our plans if we remember something new, our robot can update its memory. For example, each time it sees an obstacle, it can increase the count by 1. Or, if it moves away from an obstacle, it can update the distance in real-time!”

Teacher’s Role:
Encourage students to think of ways the robot could use these memory updates to make decisions. For instance, discuss how obstacleDetected could help the robot decide whether to stop or keep moving.


3. Coding Obstacle Detection with Variables (20 minutes)

Part 1: Creating Variables

Activity:
Introduce variables as the robot’s memory, helping it keep track of important information. Explain each variable:

  • bool obstacleDetected to store whether the robot has detected an obstacle.
  • int obstacleCount to store the number of obstacles detected.

Example Code (Part 1):

#include <M3DGo.h>

bool obstacleDetected = false;  // True if obstacle is detected, otherwise false
int obstacleCount = 0;          // Counts the number of obstacles detected

void setup() {
    go.begin();                  // Initialize the robot
    display.text("Starting..."); // Display starting message
}

Teacher’s Role:
Explain how obstacleDetected acts as a “flag” for tracking obstacles and obstacleCount as a memory that increases each time an obstacle is detected.


Part 2: Checking Distance

Activity:
Guide students in programming the robot to move forward and measure the distance to any obstacles in its path.

Instructions:

  1. Program the robot to move forward at a set speed.
  2. Use the distance sensor to store the distance reading in a temporary variable distance.

Example Code (Part 2):

void loop() {
    go.forward(50);  // Move forward at 50% speed
    float distance = range.get_cm();  // Get distance from the distance sensor
}

Teacher’s Role:
Explain how distance helps the robot understand its environment by measuring how close objects are. Ask students to observe how this value changes based on proximity.


Part 3: Adjusting the Variables`

Activity:
Help students add a condition to detect obstacles based on the distance. If an obstacle is closer than a specified threshold (e.g., 15 cm), the robot will update its memory by setting obstacleDetected to true and incrementing obstacleCount.

Example Code (Part 3):

    if (distance < 15) {         // If obstacle detected within 15 cm
        
        obstacleDetected = true;  // Set flag for obstacle
        obstacleCount += 1;       // Increase obstacle count by 1

    }

Teacher’s Role:
Help students understand the importance of updating obstacleDetected and obstacleCount when an obstacle is detected, making the robot “aware” of its surroundings.


Part 4: Using Variables to Perform Actions

Activity:
Use the obstacleDetected state to control the robot’s response. If obstacleDetected is true, the robot will pause for a set time before resetting the state and moving forward again.

Example Code (Part 4):


if(obstacleDetected) {
        go.stop();                // Stop the robot
        go.spin(45);
        display.text("Obstacle Detected!");
        Serial.println("Obstacle Detected!");   // Print on the terminal
}

        go.forward(50);           // Resume moving forward

    }
}

Teacher’s Role:
Guide students through this final part, explaining how resetting obstacleDetected to false lets the robot resume its behavior as if it has “forgotten” the previous obstacle.


Full Code for Obstacle Detection

#include <M3DGo.h>

bool obstacleDetected = false;  // True if obstacle is detected, otherwise false
int obstacleCount = 0;          // Counts the number of obstacles detected

void setup() {
    go.begin();                  // Initialize the robot
    display.text("Starting..."); // Display starting message
}

void loop() {
    go.forward(50);  // Move forward at 50% speed

    float distance = range.get_cm();  // Get distance from the distance sensor
    
    if (distance < 15) {         // If obstacle detected within 15 cm

        obstacleDetected = true;  // Set flag for obstacle
        obstacleCount += 1;       // Increase obstacle count by 1
}

        go.stop();                // Stop the robot
        go.spin(45);
        go.stop();
        display.text("Obstacle Detected!");
        Serial.println("Obstacle Detected!");   // Print on the terminal
        
        go.delay(2000);           // Wait for 2 seconds before resuming
        obstacleDetected = false; // Reset obstacle detection
        go.forward(50);           // Resume moving forward
    }
}

Teacher’s Role:
Review the entire code with students, reinforcing how each part works together to allow the robot to detect obstacles, remember encounters, and respond accordingly.

4. Adding Expressions to Display Robot Emotions (10 minutes)

Activity:
Now that students have programmed basic obstacle detection, introduce the robot’s emoji commands for expressing its “feelings” during different stages of operation.

Instructions for Adding Emoji Expressions:

  1. Show the robot displaying a happy or “joyful” emoji while moving.
  2. Switch to a “confused” or “frustrated” emoji if it detects an obstacle.

Example Code for Emoji Expressions:

void loop() {
    go.forward(50);  // Move forward at 50% speed
    display.emoji("Smile");   // Display a smile emoji

    float distance = range.get_cm();  // Get distance from the distance sensor
    
   if (distance < 15) {         // If obstacle detected within 15 cm

        obstacleDetected = true;  // Set flag for obstacle
        obstacleCount += 1;       // Increase obstacle count by 1
}

        go.stop();                // Stop the robot
        go.spin(45);
        go.stop();
        display.emoji("Confused");  // Display confused emoji
        display.text("Obstacle Detected!");
        Serial.println("Obstacle Detected!");   // Print on the terminal
        
        go.delay(2000);           // Wait for 2 seconds before resuming
        obstacleDetected = false; // Reset obstacle detection
        go.forward(50);           // Resume moving forward
        display.emoji("Smile");     // Back to smile emoji when moving
 
    }
}

Teacher’s Role:
Explain that emojis are a fun way to add “feelings” to the robot. Engage students in deciding which emoji could be used for different scenarios, such as frustration when stuck or joy when moving smoothly.

You may ask:

“When do you think the robot should feel frustrated? What about happy or confused? How does adding these expressions make the robot’s movements more relatable?”

Encourage students to get creative and experiment with different emojis for each state.


5. Reflection and Wrap-Up (5 minutes)

Reflection Questions:

  • “How did the robot ‘remember’ how many obstacles it encountered?”
  • “How do variables help the robot keep track of its environment?”
  • “What are some other situations where using variables would be helpful for a robot?”

Teacher’s Role:
Summarize the lesson by emphasizing the role of variables in helping the robot track and respond to its surroundings. Discuss how combining memory, sensor input, and expressions allows the robot to interact with the world in more engaging ways.


Learning Outcome:

By the end of this session, students will understand how to create and use variables to store information and change robot behavior. They’ll also learn how to use expressions to add a relatable, interactive aspect to the robot’s actions, enhancing their understanding of responsive programming.