Specifying variables within for loop - Raspberry Pi Forums


hello,

i'm working on short bit of code in python, it's repetitive. feel should possible loop, can't figure out how script run , appropriately understand variables being numbered. currently, have 3 combinations of led/switch, have associated input_state, state variables. expanded 16 sets, how can implemented loop?

i've tried couple of methods after googling, haven't had luck

code: select all

for x in range(1,16):     gpio.setup(switch%d, gpio.in, pull_up_down=gpio.pud_up) % (x)     gpio.setup(led%d, gpio.out) % (x)     gpio.output(led%d,false) % (x)
or

code: select all

for x in range(1,16):     gpio.setup(switch[x], gpio.in, pull_up_down=gpio.pud_up)     gpio.setup(led[x], gpio.out)     gpio.output(led[x],false)
i'm not having luck getting values recognized switch1, led1, etc.; instead, i'm getting errors involving switch, or led. how can numbers tacked on end loop?

here's non-looped code:

code: select all

import rpi.gpio gpio import time gpio.setmode(gpio.board) gpio.setwarnings(false)  led1 = 40 switch1 = 38 led2 = 36 switch2 = 32 led3 = 22 switch3 = 18  gpio.setup(switch1, gpio.in, pull_up_down=gpio.pud_up) gpio.setup(led1, gpio.out) gpio.output(led1,false) gpio.setup(switch2, gpio.in, pull_up_down=gpio.pud_up) gpio.setup(led2, gpio.out) gpio.output(led2,false) gpio.setup(switch3, gpio.in, pull_up_down=gpio.pud_up) gpio.setup(led3, gpio.out) gpio.output(led3,false)  state1 = 0 state2 = 0 state3 = 0  while true:     input_state1 = gpio.input(switch1)     if input_state1 == false:         print('button 1 pressed')         if state1 == 0:             gpio.output(led1,true)             state1 = 1             print('led 1 on')         else:             gpio.output(led1,false)             state1 = 0             print ('led 1 off')         time.sleep(0.2)      input_state2 = gpio.input(switch2)     if input_state2 == false:         print('button 2 pressed')         if state2 == 0:             gpio.output(led2,true)             state2 = 1             print('led 2 on')         else:             gpio.output(led2,false)             state2 = 0             print ('led 2 off')         time.sleep(0.2)      input_state3 = gpio.input(switch3)     if input_state3 == false:         print('button 3 pressed')         if state3 == 0:             gpio.output(led3,true)             state3 = 1             print('led 3 on')         else:             gpio.output(led3,false)             state3 = 0             print ('led 3 off')         time.sleep(0.2) 

you can setup , output list of channels, rather having in loop. see:
https://sourceforge.net/p/raspberry-gpi ... asicusage/


raspberrypi



Comments

Popular posts from this blog

VIDIOC_S_FMT error 16, Device or resource busy - Raspberry Pi Forums

using a laptop skeleton to build a pi laptop - Raspberry Pi Forums

Forum for Joomla? - Joomla! Forum - community, help and support