问题
I have a little project I'm working on, it's fairly simple so I'm hoping someone can help me.
I'm using a raspberry pi to dim a single LED with some very crude PWM.
my PWM code looks like this:
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(7, GPIO.OUT)
frequency = 0.005
dwell = 0.0001
while True:
time.sleep(frequency)
GPIO.output(7, 1)
time.sleep(dwell)
GPIO.output(7, 0)
Basically, in order for the LED to remain lit at the brightness determined by "dwell" I need that bit of code to continue looping forever.
What I would like to do is use something like
dwell=raw_input('brightness:')
so that while the PWM code is looping, I can drop in a new value for dwell to adjust the brightness of the LED.
all of my efforts so far result in one of the following:
a: the dimming loop executes once only and stops to await input b: the dimming loop will execute infinitely but not allow further input
can one of you fine people provide me with a code example that explains how I can achieve this?
for those interested, ultimately what I would like to do is set the value of dwell via sockets and use a better form of PWM output to drive LED downlights. Baby steps :)
回答1:
It looks like you need multithreading!
# import the module
import threading
# define a function to be called in the other thread
def get_input():
while True:
dwell=raw_input()
# create a Thread object
input_thread=threading.Thread(target=get_input)
# start the thread
input_thread.start()
# now enter the infinite loop
while True:
time.sleep(frequency)
GPIO.output(7, 1)
time.sleep(dwell)
GPIO.output(7, 0)
There's probably something about locks or semaphores or mutex...es (mutices?) missing here, but I don't know much about those. Simple things like this seem to work for me.
来源:https://stackoverflow.com/questions/28790570/performing-infinite-loop-while-awaiting-input