.. 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 [|link_sf_facebook|] and join today!

.. _1.3.1_py:

1.3.1 Motor
=============

Introduction
-----------------

In this project, we will learn to how to use L293D to drive a DC motor
and make it rotate clockwise and counterclockwise. Since the DC Motor
needs a larger current, for safety purpose, here we use the Power Supply
Module to supply motors.

Required Components
------------------------------

In this project, we need the following components. 

.. image:: ../img/list_1.3.1.png

It's definitely convenient to buy a whole kit, here's the link: 

.. list-table::
    :widths: 20 20 20
    :header-rows: 1

    *   - Name	
        - ITEMS IN THIS KIT
        - LINK
    *   - Raphael Kit
        - 337
        - |link_Raphael_kit|

You can also buy them separately from the links below.

.. list-table::
    :widths: 30 20
    :header-rows: 1

    *   - COMPONENT INTRODUCTION
        - PURCHASE LINK

    *   - :ref:`cpn_gpio_extension_board`
        - |link_gpio_board_buy|
    *   - :ref:`cpn_breadboard`
        - |link_breadboard_buy|
    *   - :ref:`cpn_wires`
        - |link_wires_buy|
    *   - :ref:`cpn_power_module`
        - \-
    *   - :ref:`cpn_l293d`
        - \-
    *   - :ref:`cpn_motor`
        - |link_motor_buy|


Schematic Diagram
------------------

Plug the power supply module in breadboard, and insert the jumper cap to
pin of 5V, then it will output voltage of 5V. Connect pin 1 of L293D to
GPIO22, and set it as high level. Connect pin2 to GPIO27, and pin7 to
GPIO17, then set one pin high, while the other low. Thus you can change
the motor’s rotation direction.

.. image:: ../img/image336.png


**Experimental Procedures**

**Step 1:** Build the circuit.

.. image:: ../img/image117.png

.. note::
    The power module can apply a 9V battery with the 9V Battery
    Buckle in the kit. Insert the jumper cap of the power module into the 5V
    bus strips of the breadboard.

.. image:: ../img/image118.jpeg

**Step 2**: Get into the folder of the code.

.. raw:: html

   <run></run>

.. code-block::

    cd ~/raphael-kit/python

**Step 3**: Run.

.. raw:: html

   <run></run>

.. code-block::

    sudo python3 1.3.1_Motor.py

As the code runs, the motor first rotates clockwise for 5s then stops for 5s,
after that, it rotates anticlockwise for 5s; subsequently, the motor stops 
for 5s. This series of actions will be executed repeatedly.  

**Code**

.. note::

    You can **Modify/Reset/Copy/Run/Stop** the code below. But before that, you need to go to  source code path like ``raphael-kit/python``. After modifying the code, you can run it directly to see the effect.


.. raw:: html

    <run></run>

.. code-block:: python

    import RPi.GPIO as GPIO
    import time

    # Set up pins
    MotorPin1   = 17
    MotorPin2   = 27
    MotorEnable = 22

    def setup():
        # Set the GPIO modes to BCM Numbering
        GPIO.setmode(GPIO.BCM)
        # Set pins to output
        GPIO.setup(MotorPin1, GPIO.OUT)
        GPIO.setup(MotorPin2, GPIO.OUT)
        GPIO.setup(MotorEnable, GPIO.OUT, initial=GPIO.LOW)

    # Define a motor function to spin the motor
    # direction should be
    # 1(clockwise), 0(stop), -1(counterclockwise)
    def motor(direction):
        # Clockwise
        if direction == 1:
            # Set direction
            GPIO.output(MotorPin1, GPIO.HIGH)
            GPIO.output(MotorPin2, GPIO.LOW)
            # Enable the motor
            GPIO.output(MotorEnable, GPIO.HIGH)
            print ("Clockwise")
        # Counterclockwise
        if direction == -1:
            # Set direction
            GPIO.output(MotorPin1, GPIO.LOW)
            GPIO.output(MotorPin2, GPIO.HIGH)
            # Enable the motor
            GPIO.output(MotorEnable, GPIO.HIGH)
            print ("Counterclockwise")
        # Stop
        if direction == 0:
            # Disable the motor
            GPIO.output(MotorEnable, GPIO.LOW)
            print ("Stop")

    def main():
        # Define a dictionary to make the script more readable
        # CW as clockwise, CCW as counterclockwise, STOP as stop
        directions = {'CW': 1, 'CCW': -1, 'STOP': 0}
        while True:
            # Clockwise
            motor(directions['CW'])
            time.sleep(5)
            # Stop
            motor(directions['STOP'])
            time.sleep(5)
            # Anticlockwise
            motor(directions['CCW'])
            time.sleep(5)
            # Stop
            motor(directions['STOP'])
            time.sleep(5)

    def destroy():
        # Stop the motor
        GPIO.output(MotorEnable, GPIO.LOW)
        # Release resource
        GPIO.cleanup()   

    # If run this script directly, do:
    if __name__ == '__main__':
        setup()
        try:
            main()
        # When 'Ctrl+C' is pressed, the program
        # destroy() will be executed.
        except KeyboardInterrupt:
            destroy()

**Code Explanation**

.. code-block:: python

    def motor(direction):
        # Clockwise
        if direction == 1:
            # Set direction
            GPIO.output(MotorPin1, GPIO.HIGH)
            GPIO.output(MotorPin2, GPIO.LOW)
            # Enable the motor
            GPIO.output(MotorEnable, GPIO.HIGH)
            print ("Clockwise")
    ...

Create a function, ``motor()`` whose variable is direction. As the
condition that direction=1 is met, the motor rotates clockwise; when
direction=-1, the motor rotates anticlockwise; and under the condition
that direction=0, it stops rotating.

.. code-block:: python

    def main():
        # Define a dictionary to make the script more readable
        # CW as clockwise, CCW as counterclockwise, STOP as stop
        directions = {'CW': 1, 'CCW': -1, 'STOP': 0}
        while True:
            # Clockwise
            motor(directions['CW'])
            time.sleep(5)
            # Stop
            motor(directions['STOP'])
            time.sleep(5)
            # Anticlockwise
            motor(directions['CCW'])
            time.sleep(5)
            # Stop
            motor(directions['STOP'])
            time.sleep(5)
        
In the main() function, create an array, directions[], in which CW is
equal to 1, the value of CCW is -1, and the number 0 refers to Stop.

As the code runs, the motor first rotates clockwise for 5s then stop for
5s, after that, it rotates anticlockwise for 5s; subsequently, the motor
stops for 5s. This series of actions will be executed repeatedly.

Now, you should see the motor blade rotating.

Phenomenon Picture
------------------

.. image:: ../img/image119.jpeg