Smart IoT Motor Control System Using ESP32 Dev Board and L298N Motor Driver Module

 

 Smart IoT Motor Control System Using ESP32 & L298N

This project demonstrates a powerful wireless motor automation system built using the ESP32 and the L298N.

It integrates:

  • Dual DC motors

  • OLED display

  • PS3 wireless controller

  • Relay module

  • Laser shooting system

  • Buzzer alerts

  • Battery-powered portability

This makes it ideal for robotics, IoT automation, and smart vehicle development.


Project Overview

The ESP32 handles:

  • Wireless communication (Bluetooth via PS3 controller)

  • Motor speed & direction control using PWM

  • OLED display updates

  • Laser shooting logic

  • Game score tracking

  • External device switching via relay

The L298N driver controls:

  • Motor A (left wheel)

  • Motor B (right wheel)

  • Forward / reverse motion

  • Turning left / right


Key Components Used

ComponentFunction
ESP32 Dev BoardMain controller with WiFi & Bluetooth
L298N Motor DriverControls 2 DC motors
Dual DC Geared MotorsRobot movement
0.96” OLED (I2C)Score & system display
PS3 ControllerWireless control
Relay ModuleExternal appliance control
Laser ModuleShooting mechanism
LM393 Photo SensorsLaser detection
BuzzerAudio alerts
Rechargeable BatteryPortable power

System Working Explanation

1️⃣ Wireless Motor Control (Bluetooth)

Using the PlayStation 3 Controller, the ESP32 reads D-pad inputs:

  • 🔼 Up → Move Forward

  • 🔽 Down → Move Backward

  • ◀ Left → Turn Left

  • ▶ Right → Turn Right

  • ⭕ Circle → Activate Laser

ESP32 receives controller signals via Bluetooth and triggers motor PWM signals.


2️⃣ Motor Control Logic

The L298N uses:

  • AIN1 / AIN2 → Motor A direction

  • BIN1 / BIN2 → Motor B direction

  • PWMA / PWMB → Speed control (PWM)

Forward Movement:

digitalWrite(AIN1_PIN, LOW);
digitalWrite(AIN2_PIN, HIGH);

Speed controlled using:

ledcWrite(motorAChannel, moveSpeed);

PWM Frequency: 1000 Hz
Resolution: 8-bit


3️⃣ Laser Shooting System

When the ⭕ button is pressed:

  • Laser goes FULL power for 2 seconds

  • Returns to idle mode automatically

if (Ps3.data.button.circle && !laserOn)

This creates a shooting game mechanism.


4️⃣ Photoresistor Detection (Scoring System)

Two LM393 sensor modules detect laser hits.

If laser beam hits sensor:

if (val1 == 0 || val2 == 0)

Score increases.

Untouchable delay: 2 seconds
Game Over: Score > 50


5️⃣ OLED Display System

Using SSD1306 controller with I2C.

Displays:

  • Game title

  • Current score

  • "YOU LOSE" message

Large 6x text used for score display.


6️⃣ Relay Module Control

The relay allows switching:

  • Bulb

  • Pump

  • Motor

  • External load

Makes system expandable for home automation or industrial control.


 Power Management

Battery-powered system includes:

  • Voltage regulator for stable 5V

  • Protection circuitry

  • Portable robotics use


Core Technologies Used

  • Bluetooth communication

  • PWM motor speed control

  • H-Bridge direction control

  • I2C display communication

  • Real-time event handling

  • Wireless robotics control

  • Embedded game logic


Applications

 Smart robotic vehicles
 Smart agriculture robots
 Autonomous delivery bots
 Industrial automation prototypes
 Interactive robotics games
 IoT-based mobile systems
 Smart automation carts

 Project Advantages

✅ Wireless control (No wires required)
✅ Dual motor precision control
✅ Real-time OLED feedback
✅ Expandable IoT architecture
✅ Energy efficient
✅ Portable & scalable
✅ Suitable for competitions & exhibitions


 Possible Upgrades

You can enhance this project by adding:

  •  WiFi web dashboard control

  •  Cloud data logging (Firebase / MQTT)

  •  Camera module (ESP32-CAM)

  •  GPS tracking

  •  Autonomous obstacle avoidance

  •  AI object tracking

  •  Ultrasonic obstacle detection

  •  Voice control integration

  •  Mobile app control

  •  Line follower functionality


 Educational Concepts Covered

Electronics

  • H-Bridge motor drivers

  • PWM motor control

  • Laser sensing

  • Sensor interfacing

  • Power regulation

Programming

  • Event-driven coding

  • Interrupt-like callbacks

  • State management

  • Bluetooth stack integration

  • Embedded game development

IoT & Robotics

  • Wireless embedded control

  • Real-time monitoring

  • Automation logic

  • Smart device integration

Coding:
#include <Wire.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_GFX.h>
#include <Ps3Controller.h>
// Define OLED display width and height
#define OLED_WIDTH 128
#define OLED_HEIGHT 64

// Define the I2C address for the OLED display
#define OLED_ADDR 0x3C

// Create display object
Adafruit_SSD1306 display(OLED_WIDTH, OLED_HEIGHT, &Wire, -1);  // -1 for no reset pin

// Pin definitions
#define PHOTORESISTOR_1_PIN 14  // Pin for first LM393 module
#define PHOTORESISTOR_2_PIN 16  // Pin for second LM393 module
#define LASER_PIN 18            // Define GPIO pin for laser control

// Define motor driver pins
#define PWMA_PIN 23
#define AIN2_PIN 19
#define AIN1_PIN 5
#define PWMB_PIN 15
#define BIN2_PIN 2
#define BIN1_PIN 4
// Define PWM Parameters
const int motorFreq = 1000;
const int motorResolution = 8;

// Define channels for each motor
const int motorAChannel = 3;
const int motorBChannel = 4;

// Fixed speed for movement and turning
const int moveSpeed = 200;  // Adjust this value for desired movement speed
const int turnSpeed = 180;  // Adjust this value for desired turning speed
// Variables for game state
int val1;
int val2;
int score = 0;
unsigned long lastScoreTime = 0;             // Tracks the last time the score was incremented
const unsigned long untouchableTime = 2000;  // 2 seconds of untouchable time

// Variables for laser control
bool laserOn = false; // Laser state (idle by default)
unsigned long laserOffTime = 0; // Tracks the time to return to idle state
const unsigned long laserFullPowerTime = 2000; // Laser stays at full power for 2 seconds

// Motor movement function
void moveMotors(int mtrAspeed, int mtrBspeed, bool mtrdir) {
  // Set direction pins
  if (!mtrdir) {
    // Move in reverse
    digitalWrite(AIN1_PIN, HIGH);
    digitalWrite(AIN2_PIN, LOW);
    digitalWrite(BIN1_PIN, HIGH);
    digitalWrite(BIN2_PIN, LOW);
  } else {
    // Move forward
    digitalWrite(AIN1_PIN, LOW);
    digitalWrite(AIN2_PIN, HIGH);
    digitalWrite(BIN1_PIN, LOW);
    digitalWrite(BIN2_PIN, HIGH);
  }

  // Drive motors with PWM
  ledcWrite(motorAChannel, mtrAspeed);
  ledcWrite(motorBChannel, mtrBspeed);
}

// PS3 controller callback function to handle D-pad inputs and shooting
void notify() {
  // Detect D-pad inputs for movement
  if (Ps3.data.button.up) {
    // Move forward
    moveMotors(moveSpeed, moveSpeed, true);
    Serial.println("Moving forward");

  } else if (Ps3.data.button.down) {
    // Move backward
    moveMotors(moveSpeed, moveSpeed, false);
    Serial.println("Moving backward");

  } else if (Ps3.data.button.left) {
    // Turn left (motor B runs faster, motor A runs slower/reverse)
    moveMotors(0, moveSpeed, true);
    Serial.println("Turning left");

  } else if (Ps3.data.button.right) {
    // Turn right (motor A runs faster, motor B runs slower/reverse)
    moveMotors(moveSpeed, 0, true);
    Serial.println("Turning right");

  } else {
    // Stop motors if no D-pad button is pressed
    moveMotors(0, 0, true);
    Serial.println("Stopping");
  }

  // Detect 'O' button press for shooting
  if (Ps3.data.button.circle && !laserOn) {
    // Laser goes to full power for 2 seconds
    laserOn = true;
    analogWrite(LASER_PIN, 230); // Full power (3.2V, ~33% duty cycle)
    Serial.println("Laser at full power");
    laserOffTime = millis() + laserFullPowerTime; // Set time to return to idle
  }
}

// On Connection function
void onConnect() {
  // Print to Serial Monitor
  Serial.println("Connected.");
}

void setupPS3Controller() {
  // Define Callback Function
  Ps3.attach(notify);
  // Define On Connection Function
  Ps3.attachOnConnect(onConnect);
  // Emulate console as specific MAC address (change as required)
  Ps3.begin("98:43:FA:59:56:AE");

  // Set motor controller pins as outputs
  pinMode(PWMA_PIN, OUTPUT);
  pinMode(PWMB_PIN, OUTPUT);
  pinMode(AIN1_PIN, OUTPUT);
  pinMode(AIN2_PIN, OUTPUT);
  pinMode(BIN1_PIN, OUTPUT);
  pinMode(BIN2_PIN, OUTPUT);

  // Set channel Parameters for each motor
  ledcSetup(motorAChannel, motorFreq, motorResolution);
  ledcSetup(motorBChannel, motorFreq, motorResolution);

  // Attach Motor PWM pins to corresponding channels
  ledcAttachPin(PWMA_PIN, motorAChannel);
  ledcAttachPin(PWMB_PIN, motorBChannel);

  // Print to Serial Monitor
  Serial.println("PS3 Controller Ready.");
}

// Function to initialize the OLED display
void initDisplay() {
  // Initialize the OLED display
  if (!display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR)) {
    Serial.println(F("SSD1306 allocation failed"));
    for (;;)
      ;  // Stay here if OLED initialization fails
  }

  // Clear the display buffer
  display.clearDisplay();

  // Display initial game message on OLED
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(15, 2);
  display.println("Shooting Game");
  display.display();  // Show on screen
  delay(2000);        // Wait for 2 seconds before starting the game
}

// Function to read photoresistor values
void readPhotoresistors() {
  val1 = digitalRead(PHOTORESISTOR_1_PIN);
  val2 = digitalRead(PHOTORESISTOR_2_PIN);
}

// Function to update the game state
void updateGameState() {
  unsigned long currentTime = millis();

  // Check if enough time has passed since the last score increment
  if (currentTime - lastScoreTime > untouchableTime) {
    // Check if either photoresistor detects the laser (active low, so value is 0)
    if (val1 == 0 || val2 == 0) {
      score++;                      // Increment score
      lastScoreTime = currentTime;  // Reset untouchable timer
    }
  }
}

// Function to update the display
void updateDisplay() {
  if (score > 50) {
    // Display game over message if score exceeds 50
    display.clearDisplay();
    display.setTextSize(2);
    display.setCursor(0, 18);
    display.println("YOU LOSE");
    display.display();  // Show "YOU LOSE" on screen
  } else {
    // Clear the display and show the current score
    display.clearDisplay();
    display.setTextSize(6);
    display.setCursor(28, 13);
    display.println(score);
    display.display();  // Show score on screen
  }
}

// Function to control the laser shooting
void controlLaser() {
  unsigned long currentTime = millis();
 
  if (laserOn && currentTime >= laserOffTime) {
    // Return laser to idle state after 2 seconds
    laserOn = false;
    analogWrite(LASER_PIN, 30); // Idle mode (2.3V, 25% duty cycle)
    Serial.println("Laser returned to idle state");
  }
}

// Setup function for initializing components
void setup() {
  // Set pin modes
  pinMode(PHOTORESISTOR_1_PIN, INPUT);
  pinMode(PHOTORESISTOR_2_PIN, INPUT);
  pinMode(LASER_PIN, OUTPUT);

  // Start serial communication for debugging
  Serial.begin(115200);

  // Initialize the OLED display
  initDisplay();
  setupPS3Controller();  // PS3 controller setup with D-pad functionality

  // Set laser to idle mode initially
  analogWrite(LASER_PIN, 30); // Idle mode (2.3V, 25% duty cycle)
}

// Main loop function
void loop() {
  if (!Ps3.isConnected())
    return;

  // Read inputs
  readPhotoresistors();

  // Update game state
  updateGameState();

  // Update the display
  updateDisplay();

  // Control the laser shooting state
  controlLaser();

  // Small delay to reduce CPU load (not for debouncing)
  delay(10);
}



Applications

  • Smart robotic vehicles

  • IoT-based automation systems

  • Remote-controlled carts

  • Smart agriculture robots

  • Industrial automation prototypes

  • Autonomous delivery systems

  • Educational embedded systems projects


 Project Advantages

This ESP32 motor control system is scalable, energy-efficient, and suitable for modern IoT applications. With built-in wireless connectivity and dual motor control capability, it is perfect for developing smart robotics and automation solutions.

 

IOT & SMART SYSTEM PROJECTS

  1. IoT Weather Monitoring System (NodeMCU ESP8266 + DHT11 + Rain Sensor)
  2. ESP8266 NodeMCU Smart Health & Environment Monitoring System with Pulse, Temperature and Motion Sensors
  3. ESP32 Wi-Fi Weight Sensor with HX711
  4. Smart RFID Access Control System Using ESP32 Dev Board and UHF RFID Reader Module
  5. Smart IoT Motor Control System Using ESP32 Dev Board and L298N Motor Driver Module
  6. Smart Waste Management System Using Arduino Nano, Ultrasonic Sensor & GSM Module – Solar Powered IoT Solution
  7. Raspberry Pi Zero W and GSM SIM900 Based Ultrasonic Distance Measurement System
  8. Arduino UNO Smart Surveillance System with ESP8266 WiFi, PIR Motion Sensor & Camera Module
  9. Arduino UNO Environmental Monitoring System with OLED & 16x2 I2C LCD Display
  10. Arduino UNO-Based Smart Home Automation System with Flame and IR Sensors 
  11. Arduino Nano-Based Landslide Detection System with GSM Alerts – Smart Disaster Monitoring Project
  12. Arduino Nano Rain-Sensing Stepper Motor System
  13. Arduino Based Automatic Tire Inflator Using Pressure Sensor, Relay Module and LCD Display
  14. Arduino-Based Automatic Cooker Using Servo Motors, DC Stirrer Motor, Temperature Sensor and Relay-Controlled Heater
  15. Arduino Sketch for Plastic Bottle and Can Reverse Vending Machine

 TRAFFIC & SMART CITY PROJECTS
  1. RFID-Based Smart Traffic Control System (Arduino Mega)
  2. Arduino UNO Traffic Light Control System – Smart LED Signal Project
  3.  Arduino UNO Controlled Traffic Light System with Joystick Interface

ROBOTICS PROJECTS
  1. Arduino UNO Smart Obstacle Avoiding Robot (Ultrasonic + IR + GSM)
  2. Arduino-Powered Autonomous Obstacle Avoidance Robot with Servo Control
  3. Arduino Nano Bluetooth Controlled Line Follower Robot Using L298N Motor Driver
  4. Arduino UNO Bluetooth Controlled 4WD Robot Car Using L298N Motor Driver
  5. Arduino UNO Multi-Sensor Obstacle Avoidance & Bluetooth Controlled Robot Car Using L298N
  6. Raspberry Pi Motor Control Robot (L298N + Li-ion)
  7. RC Car Simulation with L298N Motor Driver and Joystick Control using Arduino (CirkitDesign Simulation)
  8. Raspberry Pi Robotic Arm Control System with Camera Module and Motor Driver – Smart Automation & Vision-Based Robotics Project
  9. ESP32-Based 4WD Robot Car Using Dual L298N Motor Drivers – Circuit Diagram and IoT Control Project

LORA & WIRELESS COMMUNICATION PROJECTS
  1. Arduino LoRa Communication Project Using Adafruit RFM95W LoRa RadioArduino Nano with RFM95 SX1276 LoRa
  2. Arduino Nano with RFM95 LoRa SX1276 Module – Long Range Wireless Communication Project
  3. Arduino Nano Digital Clock Using DS3231 RTC and TM1637 4-Digit Display – Circuit Diagram and Project Guide

 LED, LIGHTING & DISPLAY PROJECTS
  1. Arduino UNO Controlled NeoPixel Ring Light Show
  2. Wi-Fi Controlled NeoPixel Ring (ESP8266)
  3. Chained NeoPixel Rings with Arduino – Addressable RGB LED Control Project
  4. Arduino Nano-Controlled Lighting System with Gesture and Sound Interaction
  5. Raspberry Pi GPIO Multi-LED Control System – Beginner-Friendly Embedded Electronics Project
  6. 4 Channel Relay Module with Arduino UNO

 SENSOR & DETECTION PROJECTS
  1. Arduino UNO Color Sensor + Proximity System (TCS3200 + Inductive)
  2. Arduino Color Detection Project Using Adafruit TCS34725 RGB Color Sensor
  3. Arduino Gas Leakage Detection and Safety Alert System Using MQ-2 Gas Sensor
  4. MQ-135 Air Quality Detector Using Arduino | Cirkit Designer Simulation Project
  5. Pulse Sensor Using Arduino – Complete Guide with Simulation 
  6. HX711 Load Sensor Demo Using Arduino | Digital Weight Measurement Project
  7. Track Time with DS1307 RTC and Display on Arduino Uno with 16x2 LCD | Cirkit Designer Project
  8. Parking Sensor Simulator using Arduino Uno and HC-SR04 Ultrasonic Sensor

 FUN & INTERACTIVE PROJECTS
  1. Pong Game with Arduino UNO and OLED Display – Project Explanation
  2.   Arduino UNO Bluetooth-Controlled Servo Motor System
  3. Arduino UNO-Based Interactive Touch and Distance Sensing System with LED Indicators and Servo Control

 INDUSTRIAL / AUTOMATION PROJECTS

  1. Arduino UNO Smart Waste Sorting System Using Ultrasonic Sensor, Moisture Sensor, Servo, Stepper Motor and LCD
  2. Arduino-Based Smart Waste Segregation System Using Metal, Plastic and Moisture Sensors with Stepper and Servo Control
  3. ESP32-Based Digital Weighing Scale Using 50kg Load Cell, HX711 Module and 16x2 LCD Display
  4. Arduino-Based Smart Toll Gate Automation System with RFID, GSM, Ultrasonic Sensor and LCD Display

  5. Arduino-Based Automatic Pill Dispenser Machine with LCD Display, Servo Motor and Buzzer Reminder

  6. Arduino UNO Smart Water Quality Monitoring System with pH Sensor, Turbidity Sensor and LCD Display

  7. Arduino-Based Ocean Cleaning Boat Robot with Dual IBT-2 Motor Drivers and Conveyor Belt System

  8. IoT-Based Accident Detection and Health Monitoring System Using Raspberry Pi with GSM, GPS and Camera Integration

  9. Raspberry Pi RFID and Keypad Based Smart Door Lock System with LCD Display and L298N Motor Driver

  10. Smart Shopping Trolley Using Arduino UNO & RFID | Automatic Billing System

  11. Arduino UNO Based Automatic Liquid Hand Sanitizer & Soap Dispenser System

  12. Arduino Based Robotic Weeding Machine with Ultrasonic Obstacle Detection and L298N Motor Driver

  13. Arduino UNO Based Biometric Electronic Voting System with LCD Display and Fingerprint Authentication

  14. Arduino UNO Based Electronic Voting System with ILI9341 TFT Display

Comments