def __GPIOInit(self):
"""
Initialises the GPIO pins for the pi
(tested on the Pi3 Model B+)
"""
# Set mode PIN numbering to BCM, and define GPIO pin functions
GPIO.setmode(GPIO.BCM)
# Setup Function for input Pins
inputBNTs = (self.__soundBNTs + self.__stepBNTs)
inputBNTs.append(self.__playBNT)
inputBNTs.append(self.__recBNT)
for b in inputBNTs:
GPIO.setup(b, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# Func for ouput Pins
GPIO.setup(self.__LED, GPIO.OUT)
python类input()的实例源码
def send_gpio_order(param):
"""
GPIO????
type in(GPIO.IN) out(GPIO.OUT)
value 1 GPIO.HIGH 0 GPIO.LOW
:param param:
:return:
"""
print param
channel, type, value = param
try:
import RPi.GPIO as GPIO
except RuntimeError:
print("????")
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
if type == 'in':
GPIO.setup(channel, GPIO.IN)
GPIO.input(channel, value)
else:
GPIO.setup(channel, GPIO.OUT)
GPIO.output(channel, value)
def start():
last = GPIO.input(button)
while True:
val = GPIO.input(button)
GPIO.wait_for_edge(button, GPIO.FALLING) # we wait for the button to be pressed
GPIO.output(lights[1], GPIO.HIGH)
inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, device)
inp.setchannels(1)
inp.setrate(16000)
inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
inp.setperiodsize(500)
audio = ""
while(GPIO.input(button)==0): # we keep recording while the button is pressed
l, data = inp.read()
if l:
audio += data
rf = open(path+'recording.wav', 'w')
rf.write(audio)
rf.close()
inp = None
alexa()
def ReadAck(self):
GPIO.setup(self.SDA, GPIO.IN)
readbuffer =0
for i in range(8):
GPIO.output(self.SCL, GPIO.HIGH)
self.tick(2)
readbuffer |= (GPIO.input(self.SDA)<< 7) >> i
GPIO.output(self.SCL, GPIO.LOW)
self.tick(2)
GPIO.setup(self.SDA, GPIO.OUT)
GPIO.output(self.SDA, GPIO.LOW)
GPIO.output(self.SCL, GPIO.HIGH)
self.tick(2)
GPIO.output(self.SCL, GPIO.LOW)
GPIO.output(self.SDA, GPIO.LOW)
self.tick(2)
return readbuffer
def ReadNack(self):
GPIO.setup(self.SDA, GPIO.IN)
readbuffer =0
for i in range(8):
GPIO.output(self.SCL, GPIO.HIGH)
self.tick(2)
readbuffer |= (GPIO.input(self.SDA)<< 7) >> i
GPIO.output(self.SCL, GPIO.LOW)
self.tick(2)
GPIO.setup(self.SDA, GPIO.OUT)
GPIO.output(self.SDA, GPIO.HIGH)
GPIO.output(self.SCL, GPIO.HIGH)
self.tick(2)
GPIO.output(self.SCL, GPIO.LOW)
GPIO.output(self.SDA, GPIO.LOW)
self.tick(2)
return readbuffer
def start():
last = GPIO.input(button)
while True:
val = GPIO.input(button)
GPIO.wait_for_edge(button, GPIO.FALLING) # we wait for the button to be pressed
GPIO.output(lights[1], GPIO.HIGH)
inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, device)
inp.setchannels(1)
inp.setrate(16000)
inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
inp.setperiodsize(500)
audio = ""
while(GPIO.input(button)==0): # we keep recording while the button is pressed
l, data = inp.read()
if l:
audio += data
rf = open(path+'recording.wav', 'w')
rf.write(audio)
rf.close()
inp = None
alexa()
def signalDoorBell():
global doorBell
global belli
global bellSum
global previousDoorBell
global GPIO_doorBell
global GPIO_bell
if belli != 15:
GPIO.setmode(GPIO.BOARD)
GPIO.setup(GPIO_doorBell, GPIO.IN)
bellSum = bellSum + GPIO.input(GPIO_doorBell)
belli += 1
else:
belli = 0
if bellSum >= 15:
doorBell = 1
else:
doorBell = 0
if doorBell != previousDoorBell:
previousDoorBell = doorBell
DeviceControl.doorBell(doorBell)
print("Dang qian doorBell %s" % doorBell)
bellSum = 0
def signalshock():
global shocki
global shockSum
global shock
global GPIO_shock
if shocki != 5:
GPIO.setmode(GPIO.BOARD)
GPIO.setup(GPIO_shock, GPIO.IN)
shockSum = shockSum+GPIO.input(GPIO_shock)
shocki += 1
else:
shocki = 0
if shockSum >=2:
shock = 1
else:
shock = 0
global previousShock
if shock != previousShock:
previousShock = shock
print("Dang qian shock %s" % shock)
shockSum = 0
def signaliR():
global iRi
global iRSum
global iR
global GPIO_iR
if iRi != 5:
GPIO.setmode(GPIO.BOARD)
GPIO.setup(GPIO_iR, GPIO.IN)
iRSum = iRSum+GPIO.input(GPIO_iR)
iRi += 1
else:
iRi = 0
if iRSum >= 2:
iR = 1
else:
iR = 0
global previousIR
if iR != previousIR:
previousIR = iR
print("Dang qian IR %s"%iR)
iRSum = 0
IRStateMachine.stateJudge(iR)
# ??????
def checkbutton(self):
"""
debounced button
:return:
"""
ret = 0
ts = time.time()
if ts - self._last_check <= 0.05:
ret = 0
else:
state = GPIO.input(self._button) # Read button state
if (not self._last_state) and state:
print("got it")
ret = 1
self._last_state = state
self._last_check = time.time()
return ret
def record():
""" Record voice
"""
inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, DEVICE)
inp.setchannels(1)
inp.setrate(16000)
inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
inp.setperiodsize(500)
audio = ""
# we keep recording while the button is pressed
while GPIO.input(BUTTON) == 0:
valid, data = inp.read()
if valid:
audio += data
save_audio = open(AUDIBLE_PATH + RecordVoice.RECORD_FILE, 'w')
save_audio.write(audio)
save_audio.close()
def cameraSettings() :
global cam
global camset
cp = "Camera> "
camMode = True
while camMode :
key = input(cp + "Enter command, H lists camera commands")
if key.upper() == "H" :
print ("A toset Auto White Balance mode, currently at : " + str(cam.awb_mode))
print(" B to set brightness, currently at: " + str(cam.brightness))
print(" C to set contrast,currently at: " + str(cam.contrast))
print(" E to set effects, currently at: " + str(cam.image_effect))
print(" X to set exposure, ")
print(" T to Take test image ")
print(" Q to quit back to main mode ")
elif key.upper() == "E" :
print(" Available image effects are:"+str(cam.IMAGE_EFFECTS))
elif key.upper() =="Q" :
camMode = False
def loop():
"""
The main loop in which we mow the lawn.
"""
print 'GPIO daemon started'
while True:
for PIN in PINS:
index = [y[0] for y in PINS].index(PIN[0])
pin = PINS[index][0]
oldstate = PINS[index][1]
newstate = GPIO.input(pin)
if newstate != oldstate:
mqttc.publish(MQTT_TOPIC_OUT % pin, payload=newstate, qos=MQTT_QOS, retain=MQTT_RETAIN)
PINS[index][1] = newstate
time.sleep(.8)
# Use the signal module to handle signals
def read(self):
'''Reads 32 bits of the SPI bus & stores as an integer in self.data.'''
bytesin = 0
# Select the chip
GPIO.output(self.cs_pin, GPIO.LOW)
# Read in 32 bits
for i in range(32):
GPIO.output(self.clock_pin, GPIO.LOW)
bytesin = bytesin << 1
if (GPIO.input(self.data_pin)):
bytesin = bytesin | 1
GPIO.output(self.clock_pin, GPIO.HIGH)
# Unselect the chip
GPIO.output(self.cs_pin, GPIO.HIGH)
# Save data
self.data = bytesin
def read(self):
'''Reads 16 bits of the SPI bus & stores as an integer in self.data.'''
bytesin = 0
# Select the chip
GPIO.output(self.cs_pin, GPIO.LOW)
# Read in 16 bits
for i in range(16):
GPIO.output(self.clock_pin, GPIO.LOW)
time.sleep(0.001)
bytesin = bytesin << 1
if (GPIO.input(self.data_pin)):
bytesin = bytesin | 1
GPIO.output(self.clock_pin, GPIO.HIGH)
time.sleep(0.001)
# Unselect the chip
GPIO.output(self.cs_pin, GPIO.HIGH)
# Save data
self.data = bytesin
def wait_pir(DEBUG=False):
""" Loops till PIR doesn't detect something"""
# setting GPIO PINs
with open(SETTINGS) as file:
settings = json.load(file)
logging.info('Setting GPIO PINS')
GPIO.setmode(GPIO.BOARD)
GPIO.setup(settings['pir_pin_board'], GPIO.IN)
#####################
# PIR cycle
logging.info('Starting PIR waiting cycle...')
if DEBUG:
while input('insert 1 to start...') != '1':
time.sleep(0.1)
else:
while GPIO.input(settings['pir_pin_board']) is not 1:
time.sleep(0.1)
logging.info('PIR detection')
return
def switch_kalliope_mute_led(self, event):
"""
Switch the state of the MUTE LED
:param event: not used
"""
logger.debug("[RpiUtils] Event button caught. Switching mute led")
# get led status
led_mute_kalliope = GPIO.input(self.rpi_settings.pin_led_muted)
# switch state
if led_mute_kalliope == GPIO.HIGH:
logger.debug("[RpiUtils] Switching pin_led_muted to OFF")
self.switch_pin_to_off(self.rpi_settings.pin_led_muted)
self.callback(muted=False)
else:
logger.debug("[RpiUtils] Switching pin_led_muted to ON")
self.switch_pin_to_on(self.rpi_settings.pin_led_muted)
self.callback(muted=True)
def init_gpio(self, rpi_settings):
"""
Initialize GPIO pin to a default value. Leds are off by default
Mute button is set as an input
:param rpi_settings: RpiSettings object
"""
# All led are off by default
if self.rpi_settings.pin_led_muted:
GPIO.setup(rpi_settings.pin_led_muted, GPIO.OUT, initial=GPIO.LOW)
if self.rpi_settings.pin_led_started:
GPIO.setup(rpi_settings.pin_led_started, GPIO.OUT, initial=GPIO.LOW)
if self.rpi_settings.pin_led_listening:
GPIO.setup(rpi_settings.pin_led_listening, GPIO.OUT, initial=GPIO.LOW)
if self.rpi_settings.pin_led_talking:
GPIO.setup(rpi_settings.pin_led_talking, GPIO.OUT, initial=GPIO.LOW)
# MUTE button
if self.rpi_settings.pin_mute_button:
GPIO.setup(rpi_settings.pin_mute_button, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(rpi_settings.pin_mute_button, GPIO.FALLING,
callback=self.switch_kalliope_mute_led,
bouncetime=500)
def _r_byte(self):
"""
Read byte from the chip.
:return: byte value
:rtype: int
"""
# data pin is now input (pull-down resistor embedded in chip)
GPIO.setup(self._data_pin, GPIO.IN)
# clock the byte from chip
byte = 0
for i in range(8):
# make a high pulse on CLK pin
GPIO.output(self._clk_pin, GPIO.HIGH)
time.sleep(self.CLK_DELAY)
GPIO.output(self._clk_pin, GPIO.LOW)
time.sleep(self.CLK_DELAY)
# chip out data on clk falling edge: store current bit into byte
bit = GPIO.input(self._data_pin)
byte |= ((2 ** i) * bit)
# return byte value
return byte
def stopwatch(hexUID, name):
start = time.time()
time.clock()
elapsed = 0
while elapsed < maxRaceTime and GPIO.input(laserPin) != GPIO.LOW:
elapsed = time.time() - start
millis = int(round(elapsed * 1000))
hours, millis = divmod(millis, 3600000)
minutes, millis = divmod(millis, 60000)
seconds, millis = divmod(millis, 1000)
s = "%02i:%02i:%03i" % (minutes, seconds, millis)
with canvas(disp) as draw:
draw.text((0, 0), "Timer:", font=defaultFont, fill=255)
draw.text((0, 20), s, font=timerFont, fill=255)
color(100, 0, 0, 0)
publishRaceTimes(hexUID, name, elapsed)
# Function to plubish the race times for the current user.
# It takes the hexUID, name and completionTime
# and publishes them to the AWS IoT topic.
def measure():
# Send a 10us pulse to trigger
GPIO.output(GPIO_TRIGGER, True)
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
start = time.time()
while GPIO.input(GPIO_ECHO) == 0:
start = time.time()
while GPIO.output(GPIO_ECHO) == 1:
stop = time.time()
elapsed = stop - start
distance = (elapsed * 34300) / 2
return distance
def read_soil_moist_digital(gpio_pin):
reading = False
soil_value = None
count = 0
while reading == False:
GPIO.setup(gpio_pin, GPIO.IN)
try:
soil_value = GPIO.input(gpio_pin)
except Exception as e:
print("!!! couldn't read sensor, error " + str(e))
time.sleep(1)
if not soil_value == None:
print(" The sensor " + str(gpio_pin) + " returned a value of; " + str(soil_value))
return soil_value
count = count + 1
if count >= 10:
print("Sensor failed to read ten times, giving up...")
return 'none'
def door_check(self, channel):
time.sleep(3)
status = GPIO.input(button_pin)
db = get_db()
# logging.getLogger('garage').info('status = %s, last status = %s' % (status, self.last_status))
if status == 1:
if status != self.last_status:
db.record_door_closed()
logging.getLogger('garage').info('Door closed')
self.notify.notify()
else:
pass
# logging.getLogger('garage').info('Door closed again')
else:
if status != self.last_status:
db.record_door_opened()
logging.getLogger('garage').info('Door opened')
self.notify.notify()
self.camera.take_picture()
else:
pass
# logging.getLogger('garage').info('Door opened again')
db.shutdown()
self.last_status = status
def button_press_switch(channel):
global button_status
GPIO.remove_event_detect(channel)
logging.info('Button pressed')
pressed_time = datetime.datetime.now()
while not GPIO.input(channel):
time.sleep(.5)
dif = datetime.datetime.now() - pressed_time
pressed_time = dif.seconds
if pressed_time > 6:
shutdown()
button_status = BUTTON_SHUTDOWN
elif pressed_time > 2:
button_status = BUTTON_MONITOR_SWITCH
else:
button_status = BUTTON_SENSOR_SWITCH
logging.info("Button status = %s", button_status)
GPIO.add_event_detect(channel, GPIO.FALLING, callback=button_press_switch, bouncetime=200)
# Run cleanup routines
def shutdown(channel):
"""
Calls system shutdown after a button press of more than 2 seconds
"""
GPIO.remove_event_detect(channel)
pressed_timestamp = datetime.datetime.now()
while not GPIO.input(channel):
time.sleep(.5)
dif = datetime.datetime.now() - pressed_timestamp
pressed_time = dif.seconds
logging.debug('Pressed time = %s', pressed_time)
if pressed_time > 2:
logging.info('Button initiated shutdown')
os.system("sudo shutdown -h now")
GPIO.add_event_detect(channel, GPIO.FALLING, callback=shutdown, bouncetime=200)
# Add button pressed event detects
def shutdown(channel): # Change to lowercase function name
# Modify function to require the shutdown button to be pressed and held
# for at least 2 seconds before shutting down.
GPIO.remove_event_detect(channel)
pressed_time = datetime.datetime.now()
while not GPIO.input(channel):
time.sleep(.5)
dif = datetime.datetime.now() - pressed_time
pressed_time = dif.seconds
logging.debug('Pressed time = %s', pressed_time)
if pressed_time > 2:
pass
#os.system("sudo shutdown -h now")
GPIO.add_event_detect(channel, GPIO.FALLING, callback=shutdown, bouncetime=200)
##
##
def button_press_switch(channel):
GPIO. remove_event_detect(channel)
print('Button pressed')
pressed_time = datetime.datetime.now()
while not GPIO.input(channel):
time.sleep(.5)
dif = datetime.datetime.now() - pressed_time
pressed_time = dif.seconds
if pressed_time < 2:
button_status = 1
elif pressed_time < 6:
button_status = 2
else:
button_status = 4
print(button_status)
GPIO.add_event_detect(channel, GPIO.FALLING, callback=button_press_switch, bouncetime=200)
##
##
def RCtime (PiPin):
measurement = 0
# Discharge capacitor
GPIO.setup(PiPin, GPIO.OUT)
GPIO.output(PiPin, GPIO.LOW)
time.sleep(0.1)
GPIO.setup(PiPin, GPIO.IN)
# Count loops until voltage across
# capacitor reads high on GPIO
start = time.time()
while (GPIO.input(PiPin) == GPIO.LOW):
measurement += 1
end = time.time()
# print end - start
# return measurement
return str(end - start)
# Connects the socket
def RCtime (PiPin):
measurement = 0
# Discharge capacitor
GPIO.setup(PiPin, GPIO.OUT)
GPIO.output(PiPin, GPIO.LOW)
time.sleep(0.1)
GPIO.setup(PiPin, GPIO.IN)
# Count loops until voltage across
# capacitor reads high on GPIO
start = time.time()
while (GPIO.input(PiPin) == GPIO.LOW):
measurement += 1
end = time.time()
# print end - start
# return measurement
return str(end - start)
# Main program loop
def light_sense():
count = 0
#Output on the pin for
GPIO.setup(pin_to_circuit, GPIO.OUT)
GPIO.output(pin_to_circuit, GPIO.LOW)
time.sleep(0.1)
#Change the pin back to input
GPIO.setup(pin_to_circuit, GPIO.IN)
#Count until the pin goes high
while (GPIO.input(pin_to_circuit) == GPIO.LOW):
count += 1
if (count > 3000):
led5_on()
return count
else:
led5_off()
return count