Lesson 27: Machine Learning & AI Integration

Implementing intelligent decision-making in robotics systems

🧠 From data to decisions: Building smart robots

📚 Learning Objectives

By the end of this lesson, you will:

  • Understand basic machine learning concepts and terminology
  • Implement simple decision trees for robot behavior
  • Create adaptive behavior systems using sensor feedback
  • Build pattern recognition systems for autonomous navigation

Key Concepts:

  • Supervised vs unsupervised learning
  • Decision trees and classification
  • Reinforcement learning basics
  • Neural network fundamentals

🤖 Section 1: What is Machine Learning?

Traditional Programming vs Machine Learning

In traditional programming, we write explicit rules for every situation. In machine learning, we provide examples and let the system learn patterns to make decisions on new, unseen data.

Traditional Programming

Input + Program → Output
We write specific rules for every scenario

Machine Learning

Input + Output → Program
System learns patterns from examples

Types of Machine Learning

1. Supervised Learning

Learning from labeled examples. Like teaching a robot to recognize objects by showing it thousands of labeled images.

Example: Training a robot to identify red vs blue objects using camera data

2. Unsupervised Learning

Finding hidden patterns in data without labels. Like discovering that certain sensor readings always occur together.

Example: Grouping similar driving patterns or obstacle types

3. Reinforcement Learning

Learning through trial and error with rewards and penalties. Like training a robot to navigate by rewarding successful paths.

Example: Robot learns optimal driving strategies through practice

🌳 Section 2: Decision Trees for Robot Behavior

What is a Decision Tree?

A decision tree is a flowchart-like structure that helps make decisions by asking a series of yes/no questions. Each internal node represents a test on a sensor reading, each branch represents the outcome of the test, and each leaf node represents a decision or action.

Example: Obstacle Avoidance Decision Tree

Distance Sensor Reading < 20cm?
├─ YES: Is object on the left?
│  ├─ YES: Turn right
│  └─ NO: Turn left
└─ NO: Is path clear ahead?
   ├─ YES: Move forward
   └─ NO: Scan for best path

Implementing Decision Trees in Arduino

Decision trees translate naturally into if-else statements in code. Here's how to implement intelligent obstacle avoidance:

// Intelligent Obstacle Avoidance with Decision Tree
int frontDistance, leftDistance, rightDistance;

void intelligentNavigation() {
  // Gather sensor data
  frontDistance = getUltrasonicDistance(FRONT_SENSOR);
  leftDistance = getUltrasonicDistance(LEFT_SENSOR);
  rightDistance = getUltrasonicDistance(RIGHT_SENSOR);
  
  // Decision tree implementation
  if (frontDistance < 20) {
    // Obstacle detected ahead
    if (leftDistance > rightDistance) {
      // More space on left
      if (leftDistance > 30) {
        turnLeft();
        Serial.println("Decision: Turn left (clear path)");
      } else {
        reverseAndTurn();
        Serial.println("Decision: Reverse and reassess");
      }
    } else {
      // More space on right or equal
      if (rightDistance > 30) {
        turnRight();
        Serial.println("Decision: Turn right (clear path)");
      } else {
        reverseAndTurn();
        Serial.println("Decision: Reverse and reassess");
      }
    }
  } else if (frontDistance < 50) {
    // Obstacle approaching - slow down
    moveForwardSlow();
    Serial.println("Decision: Proceed with caution");
  } else {
    // Clear path ahead
    moveForward();
    Serial.println("Decision: Full speed ahead");
  }
}

🔄 Section 3: Adaptive Behavior Systems

Learning from Experience

Adaptive behavior systems allow robots to modify their behavior based on past experiences. This is crucial for robots operating in changing environments.

Simple Learning Algorithm Example:

// Adaptive obstacle avoidance
int successfulMoves[4] = {0, 0, 0, 0}; // forward, left, right, back
int totalAttempts[4] = {0, 0, 0, 0};

void adaptiveMove() {
  int bestMove = 0;
  float bestSuccessRate = 0;
  
  // Find the move with highest success rate
  for (int i = 0; i < 4; i++) {
    if (totalAttempts[i] > 0) {
      float successRate = (float)successfulMoves[i] / totalAttempts[i];
      if (successRate > bestSuccessRate) {
        bestSuccessRate = successRate;
        bestMove = i;
      }
    }
  }
  
  executeMove(bestMove);
  updateLearning(bestMove);
}

🔍 Section 4: Pattern Recognition

Recognizing Patterns in Sensor Data

Pattern recognition helps robots identify recurring features in their environment, enabling better navigation and decision-making.

Simple Pattern Detection:

// Pattern recognition for navigation
int sensorHistory[10];
int historyIndex = 0;

bool detectWallPattern() {
  // Look for consistent wall detection pattern
  int wallCount = 0;
  for (int i = 0; i < 10; i++) {
    if (sensorHistory[i] < 20) { // Wall detected
      wallCount++;
    }
  }
  
  return wallCount > 7; // 70% of readings show wall
}

void updatePattern(int sensorReading) {
  sensorHistory[historyIndex] = sensorReading;
  historyIndex = (historyIndex + 1) % 10;
}

🧠 Section 5: Introduction to Neural Networks

How Neural Networks Work

Neural networks are inspired by how neurons work in the human brain. They consist of interconnected nodes that process information and learn patterns.

Biological Neuron

Receives signals from dendrites, processes in cell body, sends output through axon

Artificial Neuron

Receives inputs, applies weights and activation function, produces output

🛠️ Hands-On Project: AI-Powered Obstacle Avoidance

Project Goal

Create an adaptive obstacle avoidance system that learns from experience and improves its navigation over time.

Implementation Steps:

  1. Set up ultrasonic sensors for distance measurement
  2. Implement basic obstacle detection
  3. Add learning mechanism to track successful moves
  4. Create decision tree for movement choices
  5. Test and refine the adaptive behavior
// AI-Powered Obstacle Avoidance System
#include <NewPing.h>

#define TRIGGER_PIN 12
#define ECHO_PIN 11
#define MAX_DISTANCE 200

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

// Learning variables
float moveSuccess[4] = {0.5, 0.5, 0.5, 0.5}; // forward, left, right, back
int moveAttempts[4] = {1, 1, 1, 1};

void setup() {
  Serial.begin(9600);
  // Initialize motors and sensors
}

void loop() {
  int distance = sonar.ping_cm();
  
  if (distance < 20 && distance > 0) {
    // Obstacle detected - use AI to choose best move
    int bestMove = chooseBestMove();
    executeMove(bestMove);
    
    // Learn from the result
    delay(1000);
    updateLearning(bestMove, wasSuccessful());
  } else {
    moveForward();
  }
  
  delay(100);
}

int chooseBestMove() {
  int bestMove = 0;
  float bestScore = moveSuccess[0];
  
  for (int i = 1; i < 4; i++) {
    if (moveSuccess[i] > bestScore) {
      bestScore = moveSuccess[i];
      bestMove = i;
    }
  }
  
  return bestMove;
}

void updateLearning(int move, bool success) {
  moveAttempts[move]++;
  if (success) {
    moveSuccess[move] = (moveSuccess[move] * (moveAttempts[move] - 1) + 1.0) / moveAttempts[move];
  } else {
    moveSuccess[move] = (moveSuccess[move] * (moveAttempts[move] - 1) + 0.0) / moveAttempts[move];
  }
}

⚖️ AI Ethics and Real-World Applications

Ethical Considerations

  • Transparency: Understanding why AI makes certain decisions
  • Bias: Ensuring AI systems are fair and unbiased
  • Safety: Implementing fail-safes and human oversight
  • Privacy: Protecting user data and maintaining privacy

Real-World Applications

Autonomous Vehicles

Self-driving cars use ML for navigation, obstacle detection, and traffic analysis

Medical Robotics

Surgical robots learn from procedures to improve precision

Manufacturing

Industrial robots adapt to variations in products and processes

Home Automation

Smart home systems learn user preferences and optimize energy usage

📝 Assessment & Homework

Quick Check Questions

  1. What is the main difference between traditional programming and machine learning?
  2. Name the three main types of machine learning and give an example of each.
  3. How does a decision tree help a robot make choices?
  4. What is an adaptive behavior system and why is it useful?
  5. List three ethical considerations when implementing AI in robotics.

Homework Project

Design Your Own Learning Robot: Create a detailed plan for a robot that uses machine learning to improve its performance in a specific task.

  • Choose a specific task (cleaning, security patrol, plant care, etc.)
  • Identify what sensors the robot would need
  • Describe how the robot would learn and improve over time
  • Consider potential ethical issues and how to address them
  • Present your design in a 2-page report with diagrams

🧠 Ready to Test Your Knowledge?

Take the Lesson 27 quiz to assess your understanding of machine learning and AI integration concepts.

📝 Take Lesson 27 Quiz
← Previous: Lesson 26
📚 Semester Overview
Next: Lesson 28 →