def setup():
if os.path.isdir(ImagePath) == False:
os.mkdir(ImagePath, 0777)
try:
GPIO.cleanup()
finally:
pass
GPIO.setmode(GPIO.BOARD)
GPIO.setup(BeepPin, GPIO.OUT)
GPIO.setup(LedPin, GPIO.OUT)
GPIO.setup(ButtonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
ledOn()
beepOn()
time.sleep(0.1)
ledOff()
beepOff()
# Loop, wait for button press
python类cleanup()的实例源码
def reverse(t=wheel_pulse/2):
gpio.output(reverse_left, gpio.HIGH)
gpio.output(reverse_right, gpio.HIGH)
sleep(t)
gpio.output(reverse_left, gpio.LOW)
gpio.output(reverse_right, gpio.LOW)
##########################################################################
# cleanup
##########################################################################
def tearDown(self):
GPIO.cleanup()
#def test_software_spi_initialize(self):
#'''Checks to see if the sensor can initialize on the software SPI interface.
#Will fail if it cannot find the MAX31856 library or any dependencies.
#Test only checks to see that the sensor can be initialized in Software, does not check the
#hardware connection.
#'''
#_logger.debug('test_software_SPI_initialize()')
## Raspberry Pi software SPI configuration.
#software_spi = {"clk": 25, "cs": 8, "do": 9, "di": 10}
#sensor = MAX31856(software_spi=software_spi)
#if sensor:
#self.assertTrue(True)
#else:
#self.assertTrue(False)
def quit(self):
""" Cleanup function """
log.debug("Quitting")
log.debug("Cleaning the photobooth")
self.queue.put("exit")
self.camera.close()
self.lamp.set_level(0)
self.count_display.switch_off()
GPIO.output(self.trigger_led_channel, 0)
GPIO.output(self.shutdown_led_channel, 0)
GPIO.cleanup()
sys.exit()
#################
### Functions ###
#################
def __init__(self, channel, invert=False):
from navio import adafruit_pwm_servo_driver as pwm
from navio import util
import RPi.GPIO as GPIO
util.check_apm()
#Navio+ requires the GPIO line 27 to be set to low
#before the PCA9685 is accesed
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(27, GPIO.OUT)
GPIO.output(27,GPIO.LOW)
#GPIO.cleanup()
self.frequency = 60
self.channel = channel
self.invert = invert
self.pwm = pwm.PWM()
self.pwm.setPWMFreq(self.frequency)
def main():
try:
while True:
for led in LEDS:
for idx, pin in enumerate(led):
if pin == O:
GPIO.setup(PINS[idx], GPIO.IN)
else:
GPIO.setup(PINS[idx], GPIO.OUT)
GPIO.output(PINS[idx], pin)
time.sleep(.1)
except KeyboardInterrupt:
pass
finally:
GPIO.cleanup()
def main():
import RPi.GPIO as GPIO
try:
print('UNKNOWN:%d' % GPIO.UNKNOWN)
print('SERIAL:%d' % GPIO.SERIAL)
print('SPI:%d' % GPIO.SPI)
print('I2C:%d' % GPIO.I2C)
print('HARD_PWM:%d' % GPIO.HARD_PWM)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(3, GPIO.OUT)
for pin in range(1, 41):
try:
print('%02d: %d' % (pin, GPIO.gpio_function(pin)))
except ValueError as ex:
print(ex)
finally:
GPIO.cleanup()
def main():
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(12, GPIO.OUT)
p = GPIO.PWM(12, 50)
try:
p.start(0)
for dc in range(0, 101, 5):
p.ChangeDutyCycle(dc)
time.sleep(0.1)
for dc in range(100, -1, -5):
p.ChangeDutyCycle(dc)
time.sleep(0.1)
finally:
p.stop()
GPIO.cleanup()
sample_custom_ui_launcher.py 文件源码
项目:raspberry-gpio-emulator
作者: nosix
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
def main():
import RPi.GPIO as GPIO
import time
try:
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18, GPIO.OUT)
GPIO.setup(27, GPIO.IN)
while True:
time.sleep(1)
finally:
GPIO.cleanup()
def main():
import RPi.GPIO as GPIO
import time
try:
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18, GPIO.OUT)
GPIO.setup(27, GPIO.IN)
while True:
time.sleep(1)
finally:
GPIO.cleanup()
def exit():
"""
Exit handler, which clears all custom chars and shuts down the display.
"""
try:
if not DISPLAY:
lcd = RPi_I2C_driver.lcd()
lcd.backlight(0)
if DEBUG:
print "exit()"
GPIO.cleanup()
except:
# avoids ugly KeyboardInterrupt trace on console...
pass
#####
#####
# MAIN HERE
controller_rpi.py 文件源码
项目:SX127x_driver_for_MicroPython_on_ESP8266
作者: Wei1234c
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
def get_spi(self):
spi = None
try:
spi = spidev.SpiDev()
bus = 0
device = 0
spi.open(bus, device)
spi.max_speed_hz = 10000000
spi.mode = 0b00
spi.lsbfirst = False
except Exception as e:
print(e)
GPIO.cleanup()
if spi:
spi.close()
spi = None
return spi
# https://www.raspberrypi.org/documentation/hardware/raspberrypi/spi/README.md
# https://www.raspberrypi.org/forums/viewtopic.php?f=44&t=19489
controller_rpi.py 文件源码
项目:SX127x_driver_for_MicroPython_on_ESP8266
作者: Wei1234c
项目源码
文件源码
阅读 20
收藏 0
点赞 0
评论 0
def get_spi(self):
spi = None
try:
spi = spidev.SpiDev()
bus = 0
device = 0
spi.open(bus, device)
spi.max_speed_hz = 10000000
spi.mode = 0b00
spi.lsbfirst = False
except Exception as e:
print(e)
GPIO.cleanup()
if spi:
spi.close()
spi = None
return spi
# https://www.raspberrypi.org/documentation/hardware/raspberrypi/spi/README.md
# https://www.raspberrypi.org/forums/viewtopic.php?f=44&t=19489
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 __enter__(self):
# Make sure to cleanup GPIO afterward
if not self.__signals_trapped:
self.__signals_trapped = True
for sig in [signal.SIGQUIT, signal.SIGTERM, signal.SIGTSTP]:
if hasattr(signal.getsignal(sig), '__call__'):
deleg = signal.getsignal(sig)
def delegate(signum, stack):
self.__exit__(None, None, None)
deleg(signum, stack)
signal.signal(sig, delegate)
else:
def delegate(signum, stack):
self.__exit__(None, None, None)
signal.signal(sig, delegate)
return self
def ResetIOT_HW(cls, bMode):
"""Set Raspberry pi GPIO pins and reset RF Explorer device
Parameters:
bMode -- True if the baudrate is set to 500000bps, False to 2400bps
"""
try:
import RPi.GPIO as GPIO
#print("RPi info: " + str(GPIO.RPI_INFO)) #information about your RPi:
#print("RPi.GPio version: " + GPIO.VERSION) #version of RPi.GPIO:
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD) #refer to the pin numbers on the P1 header of the Raspberry Pi board
GPIO.setup(12, GPIO.OUT) #set /reset (pin 12) to output
GPIO.output(12, False) #set /reset (pin 12) to LOW
GPIO.setup(21, GPIO.OUT) #set GPIO2 (pin 21) to output
GPIO.output(21, bMode) #set GPIO2 (pin 21) to HIGH (for 500Kbps)
time.sleep(0.1) #wait 100ms
GPIO.output(12, True) #set /reset to HIGH
time.sleep(2.5) #wait 2.5sec
GPIO.setup(21, GPIO.IN) #set GPIO2 to input
GPIO.cleanup() #clean up GPIO channels
except RuntimeError:
print("Error importing RPi.GPIO! This is probably because you need superuser privileges. You can achieve this by using 'sudo' to run your script")
def screen_on(retPage, backlightControl):
if os.environ["KPPIN"] != "1":
launch_bg=os.environ["MENUDIR"] + "launch-bg.sh"
process = subprocess.call(launch_bg, shell=True)
pygame.quit()
if backlightControl == "3.5r":
process = subprocess.call("echo '1' > /sys/class/backlight/soc\:backlight/brightness", shell=True)
elif backlightControl == "4dpi-24":
process = subprocess.call("echo '80' > /sys/class/backlight/24-hat-pwm/brightness", shell=True)
else:
backlight = GPIO.PWM(18, 1023)
backlight.start(100)
GPIO.cleanup()
if os.environ["KPPIN"] == "1":
page=os.environ["MENUDIR"] + "menu-pin.py"
args = [page, retPage]
else:
page=os.environ["MENUDIR"] + retPage
args = [page]
os.execvp("python", ["python"] + args)
# Turn screen off
def main():
#if the Low Battery LED is active when the program launches, handle it
if GPIO.input(batteryGPIO) is 0:
lowBattery(batteryGPIO)
#if the Power Switch is active when the program launches, handle it
if GPIO.input(powerGPIO) is 1:
powerSwitch(powerGPIO)
#Add threaded event listeners for the Low Battery and Power Switch
try:
GPIO.remove_event_detect(batteryGPIO)
GPIO.add_event_detect(batteryGPIO, GPIO.FALLING, callback=lowBattery, bouncetime=300)
GPIO.remove_event_detect(powerGPIO)
GPIO.add_event_detect(powerGPIO, GPIO.RISING, callback=powerSwitch, bouncetime=300)
except KeyboardInterrupt:
GPIO.cleanup()
def rotate_motor(duration,sleeptime):
import RPi.GPIO as GPIO
#import time
servoPIN = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(servoPIN, GPIO.OUT)
p = GPIO.PWM(servoPIN, 500) # GPIO 18 als PWM mit 50Hz
p.start(2.5) # Initialisierung
try:
while duration > 0:
p.ChangeDutyCycle(1)
print 'motor running'+str(duration)
time.sleep(sleeptime)
duration -= 1
p.stop()
GPIO.cleanup()
except KeyboardInterrupt:
p.stop()
GPIO.cleanup()
def rotate_motor(duration,sleeptime):
import RPi.GPIO as GPIO
#import time
servoPIN = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(servoPIN, GPIO.OUT)
p = GPIO.PWM(servoPIN, 500) # GPIO 18 als PWM mit 50Hz
p.start(2.5) # Initialisierung
try:
while duration > 0:
p.ChangeDutyCycle(1)
print 'motor running'+str(duration)
time.sleep(sleeptime)
duration -= 1
p.stop()
GPIO.cleanup()
except KeyboardInterrupt:
p.stop()
GPIO.cleanup()
def __initGPIOs(self):
#setup GPIO using Board numbering (pins, not GPIOs)
GPIO.setwarnings(False)
GPIO.cleanup()
GPIO.setmode(GPIO.BOARD)
#setup defined pins and event_detectors or outputs and initial states (initial is always 0, low)
for pin in pins_in_use:
if pins_in_use[pin][0] == GPIO.IN:
if pin == 5:
GPIO.setup(pin, pins_in_use[pin][0], pull_up_down=GPIO.PUD_UP)
else:
GPIO.setup(pin, pins_in_use[pin][0])
GPIO.add_event_detect(pin, pins_in_use[pin][1], callback=self.shoutItOut, bouncetime=100)
self.gpio_states.update({pin: 1})
elif pins_in_use[pin][0] == GPIO.OUT:
GPIO.setup(pin, pins_in_use[pin][0], initial=0)
def stop():
global _running
_running = False
cg.send("\nAlarm Cycles Finished\n")
cg.ifttt('PiAlarm_SendText', {'value1': 'PiAlarm Completed'})
# Cleanup tasks:
all_off.run()
GPIO.remove_event_detect(off_button)
#
# GPIO.cleanup() # Removed to avoid interference with clock
#
# release_PWM(pin_shaker)
# etc...
# # Then stop pi-blaster for good measure:
# stopPiB = "sudo kill $(ps aux | grep [b]laster | awk '{print $2}')"
# subprocess.call(stopPiB, shell=True)
def main():
try:
GPIO.setmode(GPIO.BCM)
GPIO.setup(START_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
root = tk.Tk()
root.overrideredirect(True)
width, height = root.winfo_screenwidth(), root.winfo_screenheight()
root.geometry('{0}x{1}+0+0'.format(width, height))
root.wm_title('Stoppuhr')
stopwatch = Stopwatch(LOG_FILENAME)
GPIO.add_event_detect(START_PIN, GPIO.FALLING, stopwatch.start)
stopwatch_ui = StopwatchUI(root, stopwatch)
stopwatch_ui.pack()
root.mainloop()
finally:
GPIO.cleanup()
def test_1(self):
motor_steps = 200
dir_pin = 8
step_pin = 5
enable_pin = 7
GPIO.cleanup()
stepper = StepDirDriver(dir_pin, step_pin, enable_pin)
stepper.enable()
async def run():
await stepper.rotate(360)
await stepper.move(-200)
loop = asyncio.get_event_loop()
# asyncio.ensure_future(stepper.run_forever())
# asyncio.ensure_future(quickChange())
try:
loop.run_until_complete(run())
finally:
# stepper.stop()
loop.close()
def main():
stepper = Adafruit350ma()
try:
stepper.enable()
while True:
cmd = raw_input("Command, f or r:")
direction = cmd[0]
if direction == "f":
while True:
stepper.forward()
else:
while True:
stepper.reverse()
except Exception as e:
print(e)
finally:
GPIO.cleanup()
serialMenu.py 文件源码
项目:Raspberry-Pi-for-Python-Programmers-Cookbook-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
def main():
try:
gpioSetup()
with SC.serPort(serName=SERNAME) as mySerialPort:
mySerialPort.send("\r\n")
mySerialPort.send(" GPIO Serial Control\r\n")
mySerialPort.send(" -------------------\r\n")
mySerialPort.send(" CMD PIN STATE "+
"[GPIO Pin# ON]\r\n")
while running==True:
print ("Waiting for command...")
mySerialPort.send(">>")
cmd = mySerialPort.receive(terminate="\r\n")
response=handleCmd(cmd)
mySerialPort.send(response)
mySerialPort.send(" Finished!\r\n")
except OSError:
print ("Check selected port is valid: %s" %serName)
except KeyboardInterrupt:
print ("Finished")
finally:
GPIO.cleanup()
def deinit(self):
GPIO.cleanup()
def shutdown():
GPIO.cleanup()
def shutdown(self): # shuts down pins
self.pwm.stop()
GPIO.cleanup()
def loop():
GPIO.add_event_detect(ButtonPin, GPIO.FALLING, callback=buttonPress)
while True:
pass
# When running directly, make sure to cleanup GPIO