A switch -- by itself -- doesn't provide power to anything. All it does is close and open a circuit. You can replace the switch with a wire and connect/disconnect the wire and accomplish the same thing.
If you had the middle pin of the switch connected to GPIO 2, and the two outer pins wire to Ground and Vcc, you could use the switch to switch the value of the GPIO between logic 0 and logic 1.
Reading the value would look something like this:
>>> from machine import Pin
>>> pin = Pin(2, Pin.IN)
>>> pin()
0
You can of course use the pin values in condition statements:
>>> if pin():
... print('Switch is in position 1')
... else:
... print('Switch is in position 2')
...
Switch is in position 1
>>>
I would suggest reading through some basic electronics tutorials (or watching some videos!) -- even if they're for Arduino or something rather than Micropython, many of the concepts are transferable.
For the configuration you've described in your comment...
GPIO2 ---o <--- the switch is connecting this input to Vcc
\
\
o--- Vcc
GPIO3 ---o <--- this input may have an unstable value
You're going to have the problem of "floating" inputs -- GPIO inputs that aren't connected to anything will tend to wobble between logic 0 and 1. You solve this by using pull up or pull down resistors, which connect your input to a specific logic level that will provide a stable value when the input is otherwise disconnected.
Pull-up/down resistors can be wired in manually, but many microcontrollers (the Pico included) provide built-in pull-up or pull-down resistors. The Pico appears to provide both, and you can activate them by providing the Pin.PULL_UP
or Pin.PULL_DOWN
flags when creating a new Pin
object.
That means you need to write something like:
>>> pinA = Pin(2, Pin.PULL_DOWN)
>>> pinB = Pin(3, Pin.PULL_DOWN)
>>> if PinA():
... print("Pin A is connected")
... elif PinB():
... print("Pin B is connected")
... else:
... print("Neither pin is connected")
...
We're using Pin.PULL_DOWN
here because we want a stable value of 0 when the pin is not connected.