Closed TheExpertNoob closed 1 year ago
Hi! Why do you calling them rotary
but the title is about a DIP switch?
Using a Rotary Dip Switch
Ahh! I haven't seen those in a while. But I have one and tried out a couple of techniques. This may be the simplest:
import time
import board
import digitalio
dip_pins = (board.GP10, board.GP11, board.GP12, board.GP13)
dip = [] # make the pin objects, stick them in 'dip'
for p in dip_pins:
d = digitalio.DigitalInOut(p)
d.switch_to_input(digitalio.Pull.UP)
dip.append(d)
def get_dip_val(dip):
val = 0 # our return value
for i in range(len(dip)):
if dip[i].value == False:
val |= (1 << i) # set the bit in val if that dip switch is set
return val
while True:
val = get_dip_val(dip)
print("dip val: %X" % val)
time.sleep(0.1)
And if you want to turn the number val
into your payloadN.dd
, then you can do:
val = get_dip_val(dip)
payload = "payload%d" % val
AH! I was missing something when I tried something similar...
if dip[i].value == False:
..and syntax in various places. Ultimately, this got it working for me! thanks!
def selectPayload():
# Special thanks to todbot on simplifying this code for me! https://github.com/todbot/circuitpython-tricks/issues/8
# check switch status
# rotary pin1 = GPIO2
# rotary pin2 = GPIO3
# rotary pin4 = GPIO4
# rotary pin8 = GPIO5
payload = "payload.dd"
dip_pins = (GP2, GP3, GP4, GP5)
dip = [] # make the pin objects, stick them in 'dip'
for p in dip_pins:
d = digitalio.DigitalInOut(p)
d.switch_to_input(digitalio.Pull.UP)
dip.append(d)
def get_dip_val(dip):
val = 0 # our return value
for i in range(len(dip)):
if dip[i].value == False:
val |= (1 << i) # set the bit in val if that dip switch is set
return val
val = get_dip_val(dip)
payload = "payload%d.dd" % val
return payload
What I currently have and, to me, is ugly, but works. I would like to eventually read an array of pins as a byte (up from this sudo nibble) and append the value to the "payload{dec}.dd" then return it.