Skip to content

Lesson10: Vibration Motor Control

1. Objectives

In this lesson, you will use GPIO to control the vibration motor circuit and make the motor operate in a fixed pattern. The program switches the motor on and off using non-blocking timing, making it easy to extend the project with message notifications, alarms, or interactive feedback.

2. Prerequisites

  • Complete the ESP32-S3 environment setup in Lesson01.
  • This lesson uses only the built-in Arduino-ESP32 GPIO API. No additional third-party libraries are required.

How to add the library files:

  • No additional third-party libraries are required for this lesson. Use the GPIO API included with the ESP32 3.3.3 board package.

3. Arduino IDE Instructions

  1. Open Lesson10_Vibration_Motor.ino in the Arduino IDE. lesson_1

  2. Confirm that the board settings match those used in Lesson01. lesson_2

  3. Click Verify to compile the sketch. lesson_3

  4. Click Upload to flash the sketch, then open the Serial Monitor and set the baud rate to 115200. lesson_4

4. Hardware Instructions

  1. Connect the development board to the computer using a USB data cable and ensure that the device remains properly powered.

lesson_5

  1. After flashing the sketch, hold the device or lightly place a finger on the back of it to feel the vibration motor pattern.

  2. Observe the MOTOR ON/OFF status in the Serial Monitor and compare it with the actual vibration pattern.

  3. If you cannot feel any vibration, confirm that the device has sufficient power and check whether the GPIO47 peripheral power supply is enabled.

5. Key Code Explained

constexpr uint8_t kMotorEnablePin = 45;
constexpr uint8_t kPeripheralPowerPin = 47;

GPIO45 controls the vibration motor enable signal, while GPIO47 controls the main peripheral power supply. The peripheral power supply controlled by GPIO47 must be enabled before the motor can operate. Otherwise, the motor circuit may not receive power even if the GPIO45 state changes.

const MotorStep kPattern[] = {
    {true, 200}, {false, 200}, {true, 200}, {false, 1000},
    {true, 500}, {false, 2000},
};

The MotorStep structure contains two pieces of information: whether the motor is on and how long that state lasts. This array defines the vibration pattern. You can change the vibration pattern by modifying the array without changing the control logic.

if (millis() - stepStartedMs >= currentStep.durationMs) {
  patternIndex = (patternIndex + 1) % (sizeof(kPattern) / sizeof(kPattern[0]));
  applyStep(kPattern[patternIndex]);
}

This code does not block the program with a long delay(). Instead, it uses millis() to determine whether the current step has finished. When the time expires, the program switches to the next step. At the end of the array, the modulo operation returns the index to the beginning. This approach is better suited for handling buttons, displays, or communication tasks simultaneously in future extensions.

Download the Lesson 10 code