Note

Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.

Why Join?

  • Expert Support: Solve post-sale issues and technical challenges with help from our community and team.

  • Learn & Share: Exchange tips and tutorials to enhance your skills.

  • Exclusive Previews: Get early access to new product announcements and sneak peeks.

  • Special Discounts: Enjoy exclusive discounts on our newest products.

  • Festive Promotions and Giveaways: Take part in giveaways and holiday promotions.

👉 Ready to explore and create with us? Click [here] and join today!

1.6 Motor

Introduction

In this project, we will learn how to use the Fusion HAT+ to control a DC motor, making it rotate clockwise and counterclockwise.


What You’ll Need

To complete this project, you will need the following components:

COMPONENT

PURCHASE LINK

DC Motor

BUY

Fusion HAT+

-

Raspberry Pi

-


Circuit Diagram

The circuit diagram below shows the connections required to control the motor.

../_images/1.3.1_sch.png

Wiring Diagram

../_images/1.3.1_bb.png

Running the Example

All example code used in this tutorial is available in the ai-lab-kit directory. Follow these steps to run the example:

cd ~/ai-lab-kit/python/
sudo python3 1.6_Motor.py

After running the script, the motor connected to port M0 repeatedly starts and stops in a loop. It first stops for 0.5 seconds, then runs at −50% power for 1 second, stops again for 0.5 seconds, and finally runs at 75% power for 1 second. This sequence repeats continuously. When the program exits, the motor is safely stopped.


Code

The following Python code controls the motor’s rotation direction and timing:

#!/usr/bin/env python3
from time import sleep
from fusion_hat.motor import Motor

# Motor on port M0, reverse direction if needed
motor = Motor("M0", is_reversed=True)

try:
   while True:
      motor.power(0)
      sleep(0.5)

      motor.power(-50)
      sleep(1)

      motor.power(0)
      sleep(0.5)

      motor.power(75)
      sleep(1)

except KeyboardInterrupt:
   # Ctrl + C to stop
   print("\nStopped by user.")

finally:
   # Always stop the motor safely
   motor.stop()
   sleep(0.1)

Understanding the Code

  1. Library Import

    The fusion_hat library simplifies GPIO interactions, while the time library provides delay functions.

    from time import sleep
    from fusion_hat.motor import Motor
    
  2. Motor Initialization

    The Motor object is created using M0 pins.

    motor = Motor('M0', is_reversed=True)
    
  3. Motor Actions

    The motor speed is set to 0, -50, and 75, respectively. The sleep function pauses the program for a specified duration.

    try:
       # Loop forever
       while True:
          motor.power(0)       # Stop the motor
          sleep(0.5)           # Wait 0.5 seconds
    
          motor.power(-50)     # Run the motor at -50% power
          sleep(1)             # Run for 1 second
    
          motor.power(0)       # Stop again
          sleep(0.5)           # Wait 0.5 seconds
    
          motor.power(75)      # Run the motor at 75% power
          sleep(1)             # Run for 1 second
    

Troubleshooting

  1. Motor Does Not Move

    • Cause: Incorrect wiring or GPIO pin configuration.

    • Solution: Ensure the motor is receiving power and the enable pin is connected properly.

  2. Only One Direction Works

    • Cause: Faulty connection to the forward or backward pin.

    • Solution: Ensure the pins are securely connected to the Fusion HAT+.

  3. Motor Spins Continuously Without Stopping

    • Cause: The stop() function may not be executed properly.

    • Solution: Confirm that the motor.stop() method is called.


Extendable Ideas

  1. User-Controlled Actions

    Allow the user to control the motor in real-time via keyboard input:

    while True:
       num = int(input("The speed percentage (-100~100): "))
       if num >= -100 and num <= 100:
          motor.speed(num)
       else:
          print("Invalid action!")
    
  1. Timed Motor Control

    Add functionality to run the motor for a user-specified duration:

    duration = int(input("Enter duration (seconds): "))
    motor.speed(50)
    sleep(duration)
    motor.stop()
    

Conclusion

This project demonstrates how to control a DC motor using the Fusion HAT+. Understanding motor control is essential for building robotics and other motion-based electronic projects.