Why my loop breaks when I start looping inside first loop? - python

I try to loop inside loop and when starts second loop, first stops instantly. I need to check endless if RELE1 is True and I need to print for example 'alarm' only once, because of that I loop second time to check is alarm 0 or 1. Here is my code:
while True:
if (GPIO.input(RELE1) == True):
print('3.3')
GPIO.setup(RELE360, GPIO.OUT)
alarm = 0
while 1:
if (GPIO.input(RELE0) == True):
alarm += 1
if(alarm == 1 ):
print('alarm')
else:
alarm = 0
else:
print('0')
GPIO.setup(RELE360, GPIO.IN)
sleep(1);

You have an infinite loop. This will never terminate:
while True:
if (GPIO.input(RELE1) == True):
print('3.3')
GPIO.setup(RELE360, GPIO.OUT)
alarm = 0
while 1:
if (GPIO.input(RELE0) == True):
alarm += 1
if(alarm == 1 ):
print('alarm')
else:
alarm = 0
# -- you will never escape this loop! --
else:
print('0')
GPIO.setup(RELE360, GPIO.IN)
sleep(1);
You can either just remove the loop, or break to escape it.
while True:
if some_condition:
break # this will exit the loop
Alternatively, you can just roll your second loop into the first; from looking at your code, it seems like you could do this:
alarm = 0
while True:
if (GPIO.input(RELE1) == True):
print('3.3')
GPIO.setup(RELE360, GPIO.OUT)
if (GPIO.input(RELE0) == True):
alarm += 1
if(alarm == 1 ):
print('alarm')
else:
print('0')
GPIO.setup(RELE360, GPIO.IN)
sleep(1);

Related

How to nest a function that responds to outside of function call?

I'm trying to figure out how I can solve this issue. I have a Raspberry Pi that is set up with a breadboard that consists of:
1 RGB light
2 buttons (left and right)
1 OLED screen
Each component works and I can run each one. What I'm trying to do is write a script that will allow me to select the "mode" with the left button (everything off vs lights vs screen on).
When a mode is selected, the right button then allows me to select between options within that mode. Below is the code as I have it:
def off():
lights = [red,green,blue]
for light in lights:
light.off()
def lightSelector():
off()
number = 0
while number < 5:
if rightButton.is_pressed:
if number == 0:
off()
red.on()
sleep(1)
number += 1
elif number == 1:
off()
green.on()
sleep(1)
number += 1
elif number == 2:
off()
blue.on()
sleep(1)
number += 1
elif number == 3:
off()
row()
sleep(1)
number+= 1
else:
number = 0
def picture():
image = Image.open('grant.jpeg')
image_r = image.resize((width,height), Image.BICUBIC)
image_bw = image_r.convert("1")
for x in range(width):
for y in range(height):
oled.pixel(x,y,bool(int(image_bw.getpixel((x,y)))))
oled.show()
def oledOff():
oled.fill(0)
oled.show()
def buttons():
x = 0
y = 0
while y is 0:
print('x = ' , x)
print('y = ' , y)
if leftButton.is_pressed:
if x == 0 :
oledOff()
off()
sleep(0.5)
x += 1
elif x == 1:
oledOff()
off()
lightSelector()
sleep(0.5)
x += 1
elif x == 2:
oledOff()
off()
picture()
sleep(0.5)
x += 1
else:
x = 0
oledOff()
off()
buttons()
The idea is that the buttons() function is the main overall function and will call the others as needed. My issue is that once I get to y == 1, or the lightSelector() function, it no longer registers that the leftButton is being pressed and won't switch to the next mode and I'm stuck in the lightSelector() function.
I know at baseline I can spell out lightSelector within the buttons function instead of calling another function but I'm trying to not be as verbose. I don't have any experience with threading or multprocessing and looked into it but couldn't see how that would help.

how can i make my script continuously run

I have made the connections in my board where I read the state of a reed switch. When the magnet nearby it shows "0" and I store the data at the "x" variable.
I'm using this to read the state of a fridge door so I can control some relays when the door is open (0) and then turn it off when closed (1).
When I use a while loop, I get the script running but it keeps counting when the variable is 1. I need this script to count when the door opens, (one) closes, and opens again (two).
Here is the code so far with the while loop.
import RPi.GPIO as GPIO
from time import sleep
GPIO.setmode(GPIO.BOARD)
inPin=15
outPin=12
GPIO.setup(inPin,GPIO.IN)
GPIO.setup(outPin,GPIO.OUT)
counter = 0
while True:
x = GPIO.input(inPin)
previousValue = 0
print(x)
if x==1:
GPIO.output(outPin,GPIO.LOW)
if x==0:
GPIO.output(outPin,GPIO.HIGH)
if x == 1 and previousValue == 0:
counter += 1
print(counter)
You could change the previous value
if x == 1 and previousValue == 0:
counter += 1
print(counter)
previousValue == 1
elif x == 0 and previousValue == 1:
previousValue == 0

Detecting when a key is pressed and break when another key is pressed[Python]

So I'm making a game without PyGame, and I want to add a section where you try to press the correct keyboard letters given the "number" of the letter, which would mean A - 1, B - 2, C - 3, etc. I want to make it so you can't mash every key, so I added a counter. However - the counter doesn't work. Help!
def keyboardpart(l,x,num):
for i in range(num):
keypress = False
c = 0
dn = random.randint(0,25)
var = l[dn]
print(dn+1)
flag1 = False
start = time.time()
while time.time()-start < x:
if keypress and not keyboard.is_pressed(var):
if c > 3:
break
c+=1
elif keyboard.is_pressed(var) and not keypress:
keypress = True
print(keypress,c)
if not keypress:
print("Sorry, you missed that key.")
flag1 = True
break
if flag1:
keyboardpart(l,x,num)
Check if any keys are pressed then check if the target key is pressed. Also wait until all keys are released before retry.
Try this code:
import random, keyboard, time
l = [chr(65+i) for i in range(26)] # A-Z
def keyboardpart(l,x,num):
for i in range(num):
keyboard.is_pressed(65) # process OS events
while len(keyboard._physically_pressed_keys): pass # wait until keys released
keypress = False
c = 0
dn = random.randint(0,25)
var = l[dn]
print(dn+1, l[dn])
flag1 = False
start = time.time()
while time.time()-start < x:
if len(keyboard._physically_pressed_keys): # any key down
if keyboard.is_pressed(var): # check target key
keypress = True
break
else: # wrong key
c+=1
if c >= 3: break # allow 3 tries
while len(keyboard._physically_pressed_keys): pass # wait until keys released
print(keypress, c)
print(keypress,c)
if not keypress:
print("Sorry, you missed that key.")
flag1 = True
break
if flag1:
keyboardpart(l,x,num)
keyboardpart(l,100,4)

Pyboard: Changing LED colour on USR button press

I got these this board Pyboard D-series which has internal LED diode with three different colours.
My goal is to make it change the LED colour on button press so basically if u press for the first time, red goes red, second time led goes green, third time led goes blue and at the fourth time I would love it to ("reset") and go back to red.
I tried making this fucntion based on stuff I found online, but it doest seem to be working.
I am new to IoT and micropython so I might be missing something important, but have no clue what.
Thanks for any advice
from pyb import Switch
from pyb import LED
led_R = LED(1)
led_G = LED(2)
led_B = LED(3)
# 1=red, 2=green, 3=blue
sw = pyb.Switch()
def cycle():
counter = 0
buttonState = ''
buttonState = sw.value()
print(buttonState)
if buttonState == True:
counter = counter + 1
print(counter)
elif counter == 0:
led_R.off()
led_G.off()
led_B.off()
elif counter == 1:
led_R.on()
led_G.off()
led_B.off()
elif counter == 2:
led_R.off()
led_G.on()
led_B.off()
elif counter == 3:
led_R.off()
led_G.off()
led_B.on()
else:
counter = 0
sw.callback(cycle())
Your callback cycle is called when button state transitions from off to on
In the callback sw.value() will always evalluate into true so it does not make sense to check it.
your counter should be initialized outside of callback
from pyb import Switch
from pyb import LED
led_R = LED(1)
led_G = LED(2)
led_B = LED(3)
# 1=red, 2=green, 3=blue
sw = pyb.Switch()
counter = 0
def cycle():
counter = counter + 1
if counter == 4:
counter = 0
print(counter)
if counter == 0:
led_R.off()
led_G.off()
led_B.off()
elif counter == 1:
led_R.on()
led_G.off()
led_B.off()
elif counter == 2:
led_R.off()
led_G.on()
led_B.off()
elif counter == 3:
led_R.off()
led_G.off()
led_B.on()
sw.callback(cycle())

Getting the rate of change of a variable

I'm fairly new to Python.
My goal is to press a button and a counter (counta) goes up by 1 every time I press 'a'.
Now I want - for example print out - how many times I've pressed the 'a' button within 10 seconds (for example).
The code is working fine like this. Now i only want to add this feature to print the chagne rate. Any ideas?
Until now my code looks like this:
from pynput.keyboard import Listener
import sched, time
s = sched.scheduler(time.time, time.sleep)
counta = 0
Timer = 0
On = True
def on_press(key):
if key.char == 'a':
#print("")
global counta
counta += 1
#print("Aktuell" + str(counta))
elif key.char == 'p':
print(int(counta/3))
else:
print("wrong button")
print("a = counta")
listener = Listener(on_press=on_press)
listener.start()
while On:
print(int(counta//3))
print(counta)
time.sleep(1)
listener.join()
Is that what you are looking for? And what do you mean by change rate?
from pynput.keyboard import Listener
import time
counta = 0
end = time.time() + 10
def on_press(key):
global counta
if key.char == 'a':
counta += 1
elif key.char == 'p':
print(int(counta/3))
else:
print("Falsche Taste!")
print("a = counta")
listener = Listener(on_press=on_press)
listener.start()
while True:
if end - time.time() >= 0:
pass
# print(end - time.time())
else:
print(counta)
counta = 0
end = time.time() + 10
listener.join()

Categories

Resources