Example Code for Raspberry Pi – Mini Vibration Module

Last revision 2026/01/20

This article provides example code and a step-by-step guide to using a mini vibration module with Raspberry Pi, covering hardware setup, connections, and Python programming for creating a simple project.

We have already introduced the digital push button module. Now let's use the module and the miniature vibration module to control its vibration to make a simple project.

Introduction

The vibration module uses a vibration motor as the excitation source. The motor is equipped with a set of adjustable eccentric blocks at one end of the rotor shaft, and the excitation force is obtained by the centrifugal force generated by the high-speed rotation of the shaft and the eccentric block.

Hardware Preparation

Wiring Diagram

  • Connect the Raspberry Pi correctly to devices such as the screen, power, keyboard and mouse.

  • Connect the IO expansion board with the Raspberry Pi. Connect the push button module to digital port 18, the vibration module to digital port 8.

Schematic

Original Layout

Sample Code

  • Open Thonny Python IDE to copy the following program into it

import RPi.GPIO as GPIO                          # Import the python module provided by the Raspberry Pi
import time                                      #Import time package to control flicker



button = 12                                      #Define the pin number to which the button is connected
vibration = 8                                    #Define the pin number to which the vibration is connected

GPIO.setmode(GPIO.BCM)                    #Set GPIO mode, BCM mode is common to all Raspberry Pi
GPIO.setup(button,GPIO.IN)                       #Set GPIO12 to input mode
GPIO.setup(vibration,GPIO.OUT)                   # Set GPIO8 to output mode
while True:                                      # Set GPIO8 to input mode
    key = GPIO.input(button)
    if (key ):                                   #Judge whether the button is pressed
        GPIO.output(vibration,GPIO.HIGH)         #Button pressed, start the micro vibrator
        time.sleep(5)                            #Wait for 5 s
        GPIO.output(vibration,GPIO.LOW)          #Turn off the micro vibrator
    else :                                       #If GPIO8 is low(that is, the button is released), execute the following statement
        GPIO.output(vibration,GPIO.LOW)          #Not start the micro vibrator
time.sleep(0.1)                                  #Delay one second, here is to control the frequency of the query key

Was this article helpful?

TOP