.. 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!

.. _2.1.2_py_pi5:

2.1.2 Micro Switch
======================

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

In this project, we will learn how to use Micro Switch. A Micro Switch is a small, very sensitive switch which requires minimum compression to activate. Because they are reliable and sensitive, micro switches are often used as a safety device. 

They are used to prevent doors from closing if something or someone is in the way and other applications similar.

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

In this project, we need the following components. 

.. image:: ../python_pi5/img/2.1.2_micro_switch_list.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_resistor`
        - |link_resistor_buy|
    *   - :ref:`cpn_led`
        - |link_led_buy|
    *   - :ref:`cpn_micro_switch`
        - \-
    *   - :ref:`cpn_capacitor`
        - |link_capacitor_buy|

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

Connect the left pin of the Micro Switch to GPIO17, and two LEDs to
pin GPIO22 and GPIO27 respectively. Then when you press and release the 
move arm of the Micro Switch, you can see the two LEDs light up alternately.

.. image:: ../python_pi5/img/2.1.2_micro_switch_schematic_1.png


.. image:: ../python_pi5/img/2.1.2_micro_switch_schematic_2.png


Experimental Procedures
-----------------------

**Step 1:** Build the circuit.

.. image:: ../python_pi5/img/2.1.2_micro_switch_circuit.png

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

.. raw:: html

   <run></run>

.. code-block::

    cd ~/raphael-kit/python-pi5

**Step 3**: Run.

.. raw:: html

   <run></run>

.. code-block::

    sudo python3 2.1.2_MicroSwitch_zero.py

While the code is running, press the moving arm, then the yellow LED lights up; release the moving arm, the red LED turns on.

.. warning::

    If there is an error prompt  ``RuntimeError: Cannot determine SOC peripheral base address``, please refer to :ref:`faq_soc` 

**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-pi5``. After modifying the code, you can run it directly to see the effect.


.. raw:: html

    <run></run>

.. code-block:: python

   #!/usr/bin/env python3
   from gpiozero import LED, Button  # Import LED and Button classes from gpiozero
   from time import sleep  # Import sleep function for delays

   # Initialize micro switch on GPIO pin 17 with the pull-up resistor disabled
   micro_switch = Button(17, pull_up=False)
   # Initialize LED1 connected to GPIO pin 22
   led1 = LED(22)
   # Initialize LED2 connected to GPIO pin 27
   led2 = LED(27)

   try:
       # Continuously check the state of the micro switch and control LEDs accordingly
       while True:
           if micro_switch.is_pressed:  # If the micro switch is pressed
               print('LED1 ON')  # Print a message to the console
               led1.on()       # Turn on LED1
               led2.off()      # Turn off LED2
           else:  # If the micro switch is not pressed
               print('    LED2 ON')  # Print a message to the console
               led1.off()      # Turn off LED1
               led2.on()       # Turn on LED2

           sleep(0.5)  # Pause for 0.5 seconds before checking the switch again

   except KeyboardInterrupt:
       # Handle KeyboardInterrupt (Ctrl+C) to exit the loop gracefully
       pass
	

**Code Explanation**

#. This line sets the script to run with Python 3. It imports ``LED`` and ``Button`` from ``gpiozero`` for controlling GPIO devices, and ``sleep`` from ``time`` for delays.

   .. code-block:: python

       #!/usr/bin/env python3
       from gpiozero import LED, Button  # Import LED and Button classes from gpiozero
       from time import sleep  # Import sleep function for delays

#. Initializes a micro switch connected to GPIO pin 17 with the pull-up resistor disabled, and two LEDs connected to GPIO pins 22 and 27.

   .. code-block:: python

       # Initialize micro switch on GPIO pin 17 with the pull-up resistor disabled
       micro_switch = Button(17, pull_up=False)
       # Initialize LED1 connected to GPIO pin 22
       led1 = LED(22)
       # Initialize LED2 connected to GPIO pin 27
       led2 = LED(27)

#. In the main loop, it checks the state of the micro switch. If pressed, LED1 turns on and LED2 off. If not pressed, LED1 turns off and LED2 on. The loop repeats every 0.5 seconds. Catches a KeyboardInterrupt (like Ctrl+C) to allow for graceful script termination.

   .. code-block:: python

       try:
           # Continuously check the state of the micro switch and control LEDs accordingly
           while True:
               if micro_switch.is_pressed:  # If the micro switch is pressed
                   print('LED1 ON')  # Print a message to the console
                   led1.on()       # Turn on LED1
                   led2.off()      # Turn off LED2
               else:  # If the micro switch is not pressed
                   print('    LED2 ON')  # Print a message to the console
                   led1.off()      # Turn off LED1
                   led2.on()       # Turn on LED2

               sleep(0.5)  # Pause for 0.5 seconds before checking the switch again

       except KeyboardInterrupt:
           # Handle KeyboardInterrupt (Ctrl+C) to exit the loop gracefully
           pass
