For a project, i used a Raspberry Pi (running dexter industries modified raspbian) and Brick Pi to run lego motors. I wroted a program with python and it works great and all, but i need the entire program to run repeatedly if the pressure sensor was not pressed. I tried calling the function sensorValue() (which detects whether the pressure sensor was being pushed) under while True:. But once i did that stuff became weird. It would just continue to repeat indefinitely and even if i pushed the sensor, the recurring 0 would turn to 1 but it wouldn't call the next function i need it to run.
Please help, this is my first time actually using python to write anything and i am a massive beginner so any help is GREATLY APPRECIATED.
Thanks Again
from BrickPi import *
BrickPiSetup()
BrickPi.MotorEnable[PORT_A] = 1
BrickPi.SensorType[PORT_4] = TYPE_SENSOR_TOUCH
BrickPiSetupSensors()
def sensorValue():
result = BrickPiUpdateValues()
if not result :
print BrickPi.Sensor[PORT_4]
time.sleep(.01)
if BrickPi.Sensor[PORT_4] == 0:
def programBody():
print ("program rest/pause")
BrickPi.MotorSpeed[PORT_A] = 0
BrickPiUpdateValues()
time.sleep(3)
print ("reminder/alarm = 200 value")
BrickPi.MotorSpeed[PORT_A] = 200
ot = time.time()
while(time.time() - ot <3):
BrickPiUpdateValues()
time.sleep(.01)
print ("reminder/alarm = 125 value")
BrickPi.MotorSpeed[PORT_A] = 125
ot = time.time()
while(time.time() - ot <3):
BrickPiUpdateValues()
time.sleep(.01)
sensorValue() #I would put while True: here but...
if BrickPi.Sensor[PORT_4]:
print "program successfully initiatied"
programBody()
try this
import BrickPi,time
BrickPiSetup()
BrickPi.MotorEnable[PORT_A] = 1
BrickPi.SensorType[PORT_4] = TYPE_SENSOR_TOUCH
BrickPiSetupSensors()
z = 0
def mainprogram():
print ("running")
while x == 1:
z = z + 1
print ("the plate has been pressed for %s seconds" % z)
time.sleep(1)
while True:
time.sleep(.1)
if BrickPi.Sensor[PORT_4]:
print "program successfully initiatied"
mainprogram()
Related
I am a novice Python programmer, trying to write a Python script to run a barcode scanning station (Raspberry Pi 4, RPiOS, Python 3.7.3). I want to scan a certain number of items, and when complete I want to scan a different barcode to process the input. From there either it will send a GPIO signal if batch count is met, or terminate the program outright if the count is too high or low.
I have been successful with what I've written, with one exception: when a second barcode is scanned to process the input, it needs to be scanned TWICE to trigger the rest of the script. I'm stumped as to why this is, and am sure this is something simple I overlooked.
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
import time
good = 38
GPIO.setmode(GPIO.BOARD)
GPIO.setup(good,GPIO.OUT)
GPIO.output(good,GPIO.HIGH)
try:
def batch_order():
batch = input("Enter the number of parts on the order: ")
barcode1 = input("Scan MASTER barcode: ")
print("Begin scanning barcodes: ")
count = 0
while True:
if input() == barcode1:
count+= 1
print("Part count: %s"%(str(count)))
elif input() != barcode1:
time.sleep(0.2)
if batch == str(count):
print("Order complete! Now printing shipping label...")
time.sleep(0.2)
GPIO.output(good,False)
time.sleep(15)
GPIO.output(good,True)
break
else:
print("Order incorrect, %s of %s parts scanned."%(str(count), batch))
time.sleep(2)
break
batch_order()
except KeyboardInterrupt:
GPIO.cleanup()
print("QUIT")
GPIO.cleanup()
All I want to do is eliminate the double scan required to terminate the program at elif input() != barcode1:. Any help would be greatly appreciated, thank you!
Just get the input() once and assign it
value = input()
if value == barcode1:
...
else: # there is also no other case
...
I'm looking to move a motorised slider using a Raspberry Pi. However, while debugging the system I was wondering if it is possible to use:
target = int(raw_input(<message>))
In a way that message could dynamically change before the user inputs a value. For me, it would be great to see the current value that is read from the slider in this <message> for example.
And if that isn't possible, is it possible to have a line printed above or below the raw_input that remains changing while the system waits for the users' input?
You can find that as a non-blocking input.
Here is a solution from stack overflow, which uses threads
I did a little modified solution, it still needs some tweaking, but its more or less what you have to do.
python
import threading
import time
import random
userInput = ""
finished = False
sensorValue = 100
previousValue = 0
def Listener():
global userInput, finished, sensorValue
userInput = raw_input(sensorValue)
if len(userInput) > 0:
print(len(userInput))
finished = True
else:
finished = False
while True:
if sensorValue != previousValue:
print("Received new slider info. SliderValue is {}".format(sensorValue))
previousValue = sensorValue
else:
print("No new info from slider. Sleeping two seconds.")
if not finished:
listener = threading.Thread(target=Listener)
listener.start()
else:
break
if random.randint(0,1) == 1:
sensorValue += 10
time.sleep(2)
See if that answers your question! :)
I am trying to create a stopwatch that starts and stops through the user pressing the enter. Once to start and again to stop. The start works perfectly but the stopping section is not working. I've tried creating a variable called stop that is like so:
stop = input("stop?")
But it's still not working.
import time
def Watch():
a = 0
hours = 0
while a < 1:
for minutes in range(0, 60):
for seconds in range(0, 60):
time.sleep(1)
print(hours,":", minutes,":", seconds)
hours = hours + 1
def whiles():
if start == "":
Watch()
if start == "":
return Watch()
def whiltr():
while Watch == True:
stop = input("Stop?")
#Ask the user to start/stop stopwatch
print ("To calculate your speed, we must first find out the time that you have taken to drive from sensor a to sensor b, consequetively for six drivers.")
start = input("Start?")
start = input("Stop")
whiles()
Perhaps all you need is something simple like:
import time
input('Start')
start = time.time()
input('Stop')
end = time.time()
print('{} seconds elapsed'.format(end-start))
Should probably use the time function instead of
def Watch():
I'm new to Python and have been googling for a couple of days and read all I can find on this forum. Might be that I don't understand it all but I haven't found a solution to my problem yet. Ask for forgiveness already if there's an answer already to my problem, then I haven't understood it.
I want to make a Pause function for my program Tennismatch. The program will when it's being run print the score of a tennis match like this: "15-0, 15-15 etc ongoing till the match ends. It will print the score line by line.
I want the user to be able to pause after x number of balls, games, etc. So I don't know when the user wants to pause and after the user has paused I want the user to be able to resume the tennismatch where it was.
Have seen the time.sleep() but as I have understood it you must know when you want to pause to use this and it also ain't an indefinetie pause like I want. With input() it's the same.
Am going to make a GUI later on when the code is finished. Happy for anything that leads me to solving my problem.
I use Windows and Python 3.42 and run the program in Shell.
A piece of the code (haven't written it all yet, it's more of a general situation when something is being printed line after line for some time and want to be able do pause in the CIL:
#self.__points = [0,0]
def playGame(self):
if self.server == True: #self.server is either True or False when someone calls playGame()
server = self.player_1.get_win_serve() #self.player_1 = an object of a class Player():
else:
server = self.player_2.get_win_serve() #get_win_serve() method returns the probability to win his serv (1-0)
while (0 < self.__points[0] - self.__points[1] >= 2 or 0 < self.__points[1] - self.__points[0] >= 2) and (self.__points[1] >= 4 or self.__points[0] >= 4):
x = random.uniform(0,1)
if x > 0 and x < server:
self.__points[0] += 1
else:
self.__points[1] += 1
# print('The score, by calling a score() function that I haven't written yet')
For dealing with events in main loop you need to make a separated thread which capture input or any other event.
import sys
from sys import stdin
from time import sleep
from threading import Thread
from Queue import Queue, Empty
def do_something():
sleep(1)
print 42
def enqueue_output(queue):
while True:
# reading line from stdin and pushing to shared queue
input = stdin.readline()
print "got input ", input
queue.put(input)
queue = Queue()
t = Thread(target=enqueue_output, args=(queue,))
t.daemon = True
t.start()
pause = False
try:
while True:
try:
command = queue.get_nowait().strip()
print 'got from queue ', command
except Empty:
print "queue is empty"
command = None
if command:
if command == 'p':
pause = True
if command == 'u':
pause = False
if not pause:
print pause
do_something()
except KeyboardInterrupt:
sys.exit(0)
I came up with the following.
while True:
try:
## Keep doing something here
## your regular code
print '.',
except KeyboardInterrupt:
## write or call pause function which could be time.sleep()
print '\nPausing... (Hit ENTER to continue, type quit to exit.)'
try:
response = raw_input()
if response.lower() == 'quit':
break
print 'Quitting...'
except KeyboardInterrupt:
print 'Resuming...'
continue
The Event loop might as well be the code I wrote with.
I don't see any user input so I assume that x emulates it. To pause the game if x < 0.1 and to unpause(/resume) it if x > 0.9, you could:
while your_condition(self.__points):
x = random.random()
if x < 0.1: # pause
self.pause()
elif x > 0.9: # resume
self.resume()
if self.is_paused:
continue # do nothing else only wait for input (`x`)
# assume your_condition() has no side-effects
# here's what the resumed version does:
print("...")
# change self.__points, etc
where pause(), resume(), is_paused() methods could be implemented as:
def __init__(self):
self.is_paused = False
def pause(self):
self.is_paused = True
def resume(self):
self.is_paused = False
as you can see the implementation is very simple.
so i am trying to figure this out for school. Im trying to print x out every minute and every ten min it will print on a new line. so far i cant get the "printing x" every min down. can someone please help.
this is my code
import time;
inTime = float(input("type in how many second"))
oldTime = time.time()-inTime
print (time.time())
def tenMin(oldTime):
newTime = time.time()
if ((newTime - oldTime)>= 25):
return True
else:
False
while (True):
if (tenMin==True):
print ("x")
newTime = time.time()
oldtime = time.time()
else:
oldTime = time.time()
continue
Your first problem is in the line
if (tenMin==True):
You compare a function reference to a boolean, clearly the answer would be False. You have to pass a parameter
if (tenMIn(oldTime)):
...
First you have some issues with you code:
else:
False - This is not true syntax in python.
If you want timer, why are you asking the user for input?
You have a logic problem:
inTime = float(input("type in how many second"))
oldTime = time.time()-inTime
time.time is float yes, but can a user really know what to print in UnixTime?
I'll suggest a simple solution it's not the very best but it works.
It will print "x" every 1 Min and after 10 Min it will print "\n" (new line)
import time
def main():
#both timers are at the same start point
startTimerTen = time.time()
startTimerMin = startTimerTen
while True:
getCurrentTime = time.time()
if getCurrentTime - startTimerTen >= 600:
# restart both parameters
startTimerTen = getCurrentTime
startTimerMin = getCurrentTime
print "This in 10 min!\n"
if getCurrentTime - startTimerMin >= 60:
# restart only min parameter
startTimerMin = getCurrentTime
print "x"
#end of main
if __name__ == "__main__":
main()