🐰 Tutorial 7 - Micro Switch

A micro switch, also known as a miniature snap-action switch, is a type of electrical switch that is widely used in electronic circuits and devices. Micro switches are small in size and can be easily mounted on a circuit board or other surface.

Micro switches consist of a spring-loaded lever or actuator that is triggered by a small amount of force or pressure. When the lever is activated, it moves a set of electrical contacts inside the switch, causing the switch to open or close.

Micro switches are commonly used in a variety of applications where precise and reliable switching is required, such as in industrial machinery, home appliances, automotive electronics, and gaming peripherals. They are also used in safety devices such as door interlocks, emergency stop buttons, and limit switches.

Components Needed

Component
Raspberry Pi Pico W1
Micro USB Cable1
Breadboard1
WiresSeveral
Resistor1 - 10KΩ
Micro Switch1

Fritzing Diagram

Code

import machine
import utime
button = machine.Pin(14, machine.Pin.IN)
while True:
    if button.value() == 1:
        print("The switch works!")
        utime.sleep(1)

Code Explanation

  1. Importing necessary modules:
import machine
import utime

The code imports the machine module, which is typically used for interacting with hardware on microcontrollers, and the utime module, which is used for time-related operations.

  1. Setting up the button pin:
button = machine.Pin(14, machine.Pin.IN)

The code defines a button variable and assigns it to the Pin object with the pin number 14 and the mode set to machine.Pin.IN, which means the pin is configured as an input pin to read the state of the micro switch.

  1. Looping indefinitely for button state checking:
while True:

The code starts an infinite loop that will continuously check the state of the button.

  1. Checking button state and printing message:
if button.value() == 1:
    print("The switch works!")
    utime.sleep(1)

Inside the loop, the code checks the value of the button using the button.value() method. If the button is not pressed (i.e., its value is 1), it prints the message “The switch works!” to the console using the print() function. It then pauses the code execution for 1 second using utime.sleep(1) to avoid multiple prints in a short duration.

The code will continue to loop indefinitely, checking the state of the micro switch and printing the message whenever the switch is not pressed, allowing for a simple micro switch functionality.