🦉 Tutorial 6 - Toggle Switch

A toggle switch is a type of electrical switch that is commonly used to control the power supply to a circuit. It is called a “toggle” switch because it has a lever or handle that can be flipped or toggled back and forth to turn the switch on or off.

Toggle switches are simple in design and easy to use, and they come in a variety of sizes, shapes, and configurations. They can be used in a wide range of applications, from controlling lights and fans in a room to switching the power supply to an electronic device on or off.

Toggle switches are available in different types, including single-pole single-throw (SPST), single-pole double-throw (SPDT), and double-pole double-throw (DPDT). These different types of switches have different configurations of contacts that allow them to be used in specific applications.

Overall, toggle switches are a reliable and widely used type of switch in the field of electronics and electrical engineering. They are easy to install and operate, and can be a valuable component in a wide range of electronic projects and applications.

Components Needed

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

Fritzing Diagram

Code

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

Code Explanation

  1. Importing necessary modules:
from machine import Pin
import utime

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

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

The code defines a button variable and assigns it to the Pin object with the pin number 15 and the mode set to machine.Pin.IN, which means the pin is configured as an input pin to read the state of the toggle 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() == 0:
    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 pressed (i.e., its value is 0), 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 button and printing the message whenever the button is pressed, allowing for a simple toggle switch functionality.