def set_value(value): for i in range(8): bitwise=0x80>>i val = gpio.HIGH if bitwise&value else gpio.LOW gpio.output(ds, val) tick(clock) tick(latch)
def mainFunction(): """ This is the mainfunction. Here we chose wich other function we want to run using a keypad that is connected to the raspberry pi. """ global keypad print("Voer een getal in door middel van de keypad.") try: functions = [login, adUser, treadmill, device2, device3, device4, device5]#create a list of functions while True: if keypad.getKey() and 0 < int(keypad.getKey()) < 7: print("key pressed") keypadCharacter = int(keypad.getKey())#store the pressed key in the keypadCharacter variable keypadCharacter-=1 functions[keypadCharacter]() elif keypad.getKey() and not 0 < int(keypad.getKey()) < 7: print("Het getal dat u ingevoerd heeft is te hoog of te laag") #needed to be split in to high or low? sleep(2) sleep(0.1) # except ValueError: # print("Dit is geen getal voer altublieft een getal in.") # mainFunction() # except: # sleep(1) # sys.exit() finally: print("exiting") GPIO.cleanup()
def cleanup(): GPIO.cleanup() print "GPIO CLEANED" hotconn.close() histconn.close() print "DATABASE CONNECTION CLOSED" print "PROGRAM TERMINATED SUCCESSFULLY"
def alertN(self): for i in range (2): GPIO.output(self.buz,1) time.sleep(0.5) GPIO.output(self.buz,0) time.sleep(0.5) return
def setup(): global A global B global C global D global total_illumination_time GPIO.setmode(GPIO.BCM) # choose the correct GPIO pins depending on model revision = getrevision() #print "** revision: ", revision if ((revision == "0010") or (revision == "0012")): #print "Model B+ or A+" A, B, C, D = 21, 19, 26, 20 else: #print "Other model, probably Model A or Model B" A, B, C, D = 7, 9, 11, 8 if (bicolour_fitted): total_illumination_time = 6 * illumination_time_default total_illumination_time += illumination_time_bicolour_green total_illumination_time += illumination_time_bicolour_red else: total_illumination_time = 8 * illumination_time_default
def cleanup(): #Stop all the PWM objects RED.stop() GREEN.stop() BLUE.stop() #Tidy up and remaining connections. GPIO.cleanup()
def __new__(cls, port, consigne = 0): #Initialisation du nouveau moteur if port in cls._MOTEURS: #Si le port est déjà pris raise MoteurExistErreur if port not in Moteur._PORTS: #Si le port est dispo raise MoteurPortErreur if consigne < -100 or consigne > 100: #Si la vitesse est comprise dans [-100;100] raise MoteurConsigneError self = object.__new__(cls) self._port = port self._isRuning = False self._consigne = consigne cls._MOTEURS[port] = self if port == 'A': pinA = 33 pinB = 35 self._pinTacho1 = 7 self._pinTAcho2 = 11 elif port == 'B': pinA = 37 pinB = 40 else: pinA = 38 pinB = 36 GPIO.setup(pinA, GPIO.OUT) #On initialise les pins en sortie GPIO.setup(pinB, GPIO.OUT) self._pwm1 = GPIO.PWM(pinA, 1000) #On les mets en tant que sortie PWMs self._pwm2 = GPIO.PWM(pinB, 1000) #GPIO.setup(self._pinTacho1, GPIO.IN) #On initialise les entrée pour récupéré signal tacho #GPIO.setup(self._pinTacho2, GPIO.IN) return self
def main(): salir=1 #init. startLog() GPIO.setmode(GPIO.BCM) rele=ClassRele() led=ClassLed() DHT_Temp = temperature.ClassTemp() horarios = TiemposCalendar.classHorrarios() ReportTemp = report.calssReport() sys.stderr.write('%s Started bucle.\n' ) while (salir): #loop. ValueTemp = DHT_Temp.SucesoTemp() ahora = horarios.suceso() if (ValueTemp[1] < ahora): encendido = 1 else: encendido = 0 led.suceso(encendido) rele.suceso(encendido) ReportTemp.suceso([ValueTemp[1], ValueTemp[2],ahora,encendido ]) sleep(0.3)
def switchWLAN(tmp): #kedipkan lampu WLAN for i in range(0, 29): GPIO.output(4, True) time.sleep(0.2) GPIO.output(4, False) time.sleep(0.2)
def changesong(channel2): global songthis songthis=songthis+1 if songthis>7: songthis=0 GPIO.output(lightList[0:8],0) GPIO.output(lightList[songthis],1)
def right_stop_at_black(): cap = cv2.VideoCapture(0) time.sleep(2) GPIO.setmode (GPIO.BCM) GPIO.setwarnings (False) GPIO.setup (23, GPIO.OUT) GPIO.setup (22, GPIO.OUT) PWML = GPIO.PWM (22,1) PWMR1 = GPIO.PWM (23,1) PWMR1.start(0) PWML.start(0) counter =0 while(1): ret, img = cap.read() PWMR1.ChangeDutyCycle(100) PWML.ChangeDutyCycle(100) ret,thresh = cv2.threshold(img,100,255,cv2.THRESH_BINARY) b1,g1,r1 = thresh[240,500] if b1==255: counter+=1 continue if counter>0: PWMR1.stop() PWML.stop() break GPIO.cleanup() cap.release() return
def cleanup (self): self.__off() if Heating.__instances == 1: io.cleanup() else: with Heating.__instances_lock: Heating.__instances -= 1
def Setup(self, authService): self.authService = authService io.setmode(io.BCM) self.lcd.begin(16, 2) self.LCDRefresh = True self.currentstate = "IDLE" self.lcd.backlight(0)
def __init__(self): threading.Thread.__init__(self) #threading-class initialisieren self.daemon = True self.port = rc.config.get('monitor','arduino_port') self.sensor_threshold_min = rc.config.getint('monitor','sensor_threshold_min') self.pir = rc.config.getboolean('monitor','pir') if(self.pir): import RPi.GPIO as GPIO self.pirGPIO = rc.config.getint('monitor','pirGPIO') GPIO.setmode(GPIO.BOARD) GPIO.setup(self.pirGPIO,GPIO.IN) self.pirFunc = rc.config.getint('monitor','pirFunc') #pir works as sensor or filter if (self.pirFunc == 2): self.pirStarttime = 0 #try: # import pigpio #except ImportError: # self.pigpio = None #else: # self.pigpio = pigpio # self.pirGPIO = rc.config.getint('monitor','pirGPIO') # self.pirFunc = rc.config.getint('monitor','pirFunc') # self.pigpio.start() # self.pigpio.set_mode(self.pirGPIO, self.pigpio.INPUT) # if (self.pirFunc == 2): # self.pirStarttime = 0 self.starttime = 0 #read absence self.absence = absence.Absence()
def lcd_toggle_enable(): # Toggle enable time.sleep(E_DELAY) GPIO.output(LCD_E, True) time.sleep(E_PULSE) GPIO.output(LCD_E, False) time.sleep(E_DELAY)
def on(self): ''' Set the led on ''' if not self.__is_pulse: GPIO.output(self.__pin, self.__real_true) self.__is_on = True
def safety_callback(channel): try: code="" type="" if(GPIO.input(2) == GPIO.LOW): #todo type="emergency" serial.flushInput() serial.write("M730\r\n") reply=serial.readline() try: code=float(reply.split("ERROR : ")[1].rstrip()) except: code=100 if(GPIO.input(2) == GPIO.HIGH): #to do type="" code="" message = {'type': str(type), 'code': str(code)} ws.send(json.dumps(message)) write_emergency(json.dumps(message)) except Exception, e: logging.info(str(e))
def __init__(self, channel, led_pin, f): self.channel = channel self.f = f self.led_pin = led_pin self.p = Process(target=self.target_f) GPIO.setup(self.channel, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(self.led_pin, GPIO.OUT, initial=GPIO.LOW)
def __init__(self): GPIO.setmode(GPIO.BCM) GPIO.setup(4,GPIO.IN,pull_up_down = GPIO.PUD_DOWN) ''' Constructor ''' #config=dict() #with open('apiconfigs.txt', 'rb') as fp: #config = json.load(fp) #self.twitter=Twitter(config["twitter"]) #self.facebook=Facebook(config["facebook"]) #self.printer=Printer() #self.uploader=UploadServer() self.cameraToRasterQueue = Queue.Queue() self.rasterToPrinterQueue = Queue.Queue() self.cameraToSocialPreprocessorQueue = Queue.Queue() self.quitEvent = threading.Event() print "made events and queues" print "init imageprocessor and social preprocessor" self.imageProcessor=ImageProcessor( self.quitEvent, self.cameraToRasterQueue, self.rasterToPrinterQueue, self.cameraToSocialPreprocessorQueue) print "init picamera" #GPIO.setup(18,GPIO.OUT) #pwmLed=GPIO.PWM(18,2000) ledDriver=LedDriver() self.picamera=Picamera( self.quitEvent, self.cameraToRasterQueue,self.cameraToSocialPreprocessorQueue,ledDriver) print "init printer" self.printer=SimpleThermalPrinter( self.quitEvent, self.rasterToPrinterQueue) '''state thread'''
def leftTurn(t): gpio.output(7,True) gpio.output(11,False) gpio.output(13,True) gpio.output(15,False) time.sleep(t) gpio.cleanup()
def set(pin, status): GPIO.setup(pin, GPIO.OUT) if status == True: status=GPIO.LOW else: status=GPIO.HIGH GPIO.output(pin, status)
def reverse(t): gpio.output(7, True) gpio.output(11, False) gpio.output(13, False) gpio.output(15, True) time.sleep(t) gpio.cleanup()
def init(): gpio.setmode(gpio.BOARD) gpio.setup(7, gpio.OUT) gpio.setup(11, gpio.OUT) gpio.setup(13, gpio.OUT) gpio.setup(15, gpio.OUT)
def main(): a=random.randint(1,10) preguntas() res=respuestas() while True: if(GPIO.input(7)): if(res==1): print "\nCorrecto! :)" if(res!=1): print "\nError :o" main() if(GPIO.input(8)): if(res==2): print "\nCorrecto! :)" if(res!=2) print "\nError :o" main() if(GPIO.input(9)): if(res==3): print "\nCorrecto! :)" if(res!=3) print "\nError :o" time.sleep(5) clear_output() main()
def set_up_gpio(self): # GPIO initialisation GPIO.setmode(GPIO.BOARD) GPIO.setup(self.SCK, GPIO.OUT, initial=GPIO.HIGH) GPIO.setup(self.CS, GPIO.OUT, initial=GPIO.HIGH) GPIO.setup(self.SDI, GPIO.OUT) GPIO.setup(self.SDO, GPIO.IN)
def on_message(client, userdata, msg): # log.info("incoming message (" + msg.topic + ")") if msg.topic == AWS_MQTT_SHADOW_TOPIC_PREFIX + userdata + \ "/shadow/update/delta": log.info("processing delta message") log.info("payload:{0}\n userdata:{1}".format(msg.payload.decode(), userdata)) j = json.loads(msg.payload.decode()) if "lock" in j["state"].keys(): log.info("set LED state to: {0}".format(j["state"]["lock"])) GPIO.output(LOCK_PIN, j["state"]["lock"]) if "alarm_reset" in j["state"].keys(): if j["state"]["alarm_reset"] == 1 and reset_queue.qsize() == 0: log.debug("reset alarm") global alarm_reset alarm_reset = 1 reset_queue.put(False) else: global alarm_reset alarm_reset = 0 elif msg.topic == AWS_MQTT_SHADOW_TOPIC_PREFIX + userdata + \ "/shadow/update/accepted": # log.info("message state accepted") pass elif msg.topic == AWS_MQTT_SHADOW_TOPIC_PREFIX + userdata + \ "/shadow/update/rejected": log.error("message state rejected. Reason: {0}" .format(str(msg.payload)))
def __init__(self, lm1, lm2, rm1, rm2): self.status = "x" self.leftMotor = [lm1, lm2] self.rightMotor = [rm1, rm2] self.motors = self.leftMotor + self.rightMotor GPIO.setup(self.motors, GPIO.OUT) self.stop()
def forward(t): gpio.output(7, False) gpio.output(11, True) gpio.output(13, True) gpio.output(15, False) time.sleep(t) gpio.cleanup()
def main(): # tell the GPIO module that we want to use the # chip's pin numbering scheme GPIO.setmode(GPIO.BCM) # setup pin 25 as an output GPIO.setup(17,GPIO.IN) GPIO.setup(18,GPIO.IN) while True: if GPIO.input(17): print "Vision Api activated" try: rc = subprocess.call("cd /home/pi/unblind && sh /home/pi/unblind/visionapi.sh && cd -", shell=True) except OSError as e: print( e ) print "button17 true" if GPIO.input(18): print "OCR Api activated" try: rc = subprocess.call("cd /home/pi/unblind && sh /home/pi/unblind/ocr.sh && cd -", shell=True) except OSError as e: print( e ) print "button18 true" time.sleep(0.1) GPIO.cleanup()
def rightTurn(t): gpio.output(7, False) gpio.output(11,True) gpio.output(13, False) gpio.output(15, True) time.sleep(t) gpio.cleanup()
def blink(): while True: GPIO.output(LedPin, GPIO.HIGH) # led on time.sleep(1) GPIO.output(LedPin, GPIO.LOW) # led off time.sleep(1)
def PowerCurrentGraph(source, days, delay): print("PowerCurrentGraph source:%s days:%s delay:%i" % (source, days, delay)) print("sleeping :", delay) time.sleep(delay) print("PowerCurrentGraph running now") # blink GPIO LED when it's run GPIO.setup(18, GPIO.OUT) GPIO.output(18, True) time.sleep(0.2) GPIO.output(18, False) # now we have get the data, stuff it in the graph try: print("trying database") db = mdb.connect('localhost', 'root', config.MySQL_Password, 'GroveWeatherPi') cursor = db.cursor() query = "SELECT TimeStamp, solarCurrent, batteryCurrent, loadCurrent FROM PowerSystem where now() - interval %i hour < TimeStamp" % ( days * 24) cursor.execute(query) result = cursor.fetchall() t = [] s = [] u = [] v = [] #x = [] for record in result: t.append(record[0]) s.append(record[1]) u.append(record[2]) v.append(record[3]) #x.append(record[4]) fig = pyplot.figure() print("count of t=", len(t)) #print (t) if (len(t) == 0): return #dts = map(datetime.datetime.fromtimestamp, t) #print dts #fds = dates.date2num(t) # converted # matplotlib date format object hfmt = dates.DateFormatter('%m/%d-%H') fig.set_facecolor('white') ax = fig.add_subplot(111, axisbg='white') #ax.vlines(fds, -200.0, 1000.0,colors='w') ax.xaxis.set_major_locator(dates.HourLocator(interval=6)) ax.xaxis.set_major_formatter(hfmt) ax.set_ylim(bottom=-200.0) pyplot.xticks(rotation='vertical') pyplot.subplots_adjust(bottom=.3) pylab.plot(t, s, color='b', label="Solar", linestyle="-", marker=".") pylab.plot(t, u, color='r', label="Battery", linestyle="-", marker=".") pylab.plot(t, v, color='g', label="Load", linestyle="-", marker=".") #pylab.plot(t, x, color='m',label="Power Eff",linestyle="-",marker=".") pylab.xlabel("Hours") pylab.ylabel("Current ma") pylab.legend(loc='upper left') if (max(u) > max(s)): myMax = max(u) + 100.0 else: myMax = max(s) pylab.axis([min(t), max(t), min(u), myMax]) pylab.figtext(.5, .05, ("GroveWeatherPi Power Current Last %i Days" % days), fontsize=18, ha='center') pyplot.setp(ax.xaxis.get_majorticklabels(), rotation=70) pylab.grid(True) pyplot.show() try: pyplot.savefig( "/home/pi/RasPiConnectServer/static/PowerCurrentGraph.png", facecolor=fig.get_facecolor()) except: pyplot.savefig( "/home/pi/SDL_Pi_GroveWeatherPi/static/PowerCurrentGraph.png", facecolor=fig.get_facecolor()) except mdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1])
import math import time import MySQLdb import sys import os import RPi.GPIO as GPIO from datetime import datetime import Adafruit_DHT from datetime import datetime sensor = Adafruit_DHT.DHT11 #Model sensor for humidity and temperature pin = 11 GPIO.setmode(GPIO.BCM) GPIO.setup(23, GPIO.IN) #Pin for moisture sensor global rain def WriteToDB(rain,temp,humid): #This is the time stamp that displays current time t = datetime.now() date = t.strftime('%m/%Y/%d %H:%M:%S') print date #Open Database connection and throw error code with description if not successful. try: db = MySQLdb.connect("IPaddress","username","password","databasename" ) except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) return
sys.exit() else: # initialise joystick joystick = pygame.joystick.Joystick(0) joystick.init() axes = joystick.get_numaxes() buttons = joystick.get_numbuttons() hats = joystick.get_numhats() print ("There is " + str(axes) + " axes") print ("There is " + str(buttons) + " button/s") print ("There is " + str(hats) + " hat/s") #GPIO Setup GPIO.setmode(GPIO.BOARD) GPIO.setup(29,GPIO.OUT) GPIO.setup(31,GPIO.OUT) #SPI Motor Driver L6470 Setup spi=spidev.SpiDev() spi.open(0,0) spi.max_speed_hz=10000 spi.xfer([0b11000000]) spi.xfer([0x16]) spi.xfer([7]) spi.xfer([0b01011000]) spi.close() spi.open(0,1) spi.max_speed_hz=10000
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #GPIO.setup(24, GPIO.IN) count = 0 while True: value = GPIO.input(24) #value = GPIO.input(24) if value == True: count = count + 1 print count time.sleep(0.1)
def initFM(): printMsg("Initializing FM Radio") # Use BCM pin numbering GPIO.setmode(GPIO.BCM) # Disable warning messages GPIO.setwarnings(False) # Reset pin on Si4703, and BCM 23 on RPi GPIO.setup(RST, GPIO.OUT) # SDA or SDIO on Raspberry Pi 3 and same on Si4703 GPIO.setup(SDA, GPIO.OUT) # Temporarily need SDA pin to put SI4703 into 2 wire mode (I2C) # The si4703 will not show up in i2cdetect until GPIO.output(SDA, GPIO.LOW) time.sleep(.1) # Transitioning the reset pin from low to high # completes putting the Si4703 in 2 wire mode GPIO.output(RST, GPIO.LOW) time.sleep(.1) GPIO.output(RST, GPIO.HIGH) time.sleep(.1) # Execute a gpio command to restore the SDA pin back to it # original i2c SDA line # '-g' causes pin numbers to be BCM # 'mode' is the option used to select the mode of the pin # 'alt0' is the alternate pin mode code for i2c subprocess.check_output(['gpio', '-g', 'mode', str(SDA), 'alt0']) readFmRegisters() reg[OSCILLATOR] = int(0x8100) writeFmRegisters() time.sleep(1) readFmRegisters() reg[POWERCFG] = int(0x4001) #Enable the Radio IC and turn off muted writeFmRegisters() time.sleep(.1) readFmRegisters() reg[SYSCONFIG1] |= (1 << 12) # Enable RDS reg[SYSCONFIG2] &= 0xFFF0 # Clear volume bits reg[SYSCONFIG2] = 0x0000 # Set volume to lowest reg[SYSCONFIG3] = 0x0100 # Set extended volume range (too loud for me wit$ write_registers() return
defaultVolume = 60 currentVolume = defaultVolume fmVolume = 0 muteVolume = False my_cron = CronTab(user='******') alarms = [] # Buttons on 2.8 capacitive touch PiTFT channel_list = [17, 22, 23, 27] backlightOn = True # set GPIO mode for buttons GPIO.setmode(GPIO.BCM) # initialize GPIO pins for buttons GPIO.setup(channel_list, GPIO.IN, pull_up_down=GPIO.PUD_UP) # setup backlight GPIO GPIO.setup(12, GPIO.OUT) backlight = GPIO.PWM(12, 1000) backlight.start(100) # Global song variables currentSongConfig = '/home/pi/radio/acr.conf' tempSongFile = '/home/pi/radio/acr.tmp' directoryMusic = "/home/pi/Music"
def destroy(): GPIO.output(LedPin, GPIO.LOW) # led off GPIO.cleanup() # Release resource
import Queue import threading import time import Robot import numpy as np from Adafruit_TSL2651 import * import RPi.GPIO as io io.setmode(io.BCM) io.setwarnings(False) io.setup(5,io.OUT) #red right io.setup(20, io.OUT) #yellow new run io.setup(25, io.OUT) #green going io.setup(27, io.OUT) #blue left LEFT_TRIM = 0 RIGHT_TRIM = 10 robot = Robot.Robot(left_trim=LEFT_TRIM, right_trim=RIGHT_TRIM) phototaxis = False directing = False class listenerThread(threading.Thread): def __init__(self, threadID, name, q): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.q = q def run(self): try:
def setup(): GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location GPIO.setup(LedPin, GPIO.OUT) # Set LedPin's mode is output GPIO.output(LedPin, GPIO.HIGH) # Set LedPin high(+3.3V) to turn on led
def _lcd_byte(self, bits, mode): # Send byte to data pins # bits = data # mode = True for character # False for command GPIO.output(LCD_RS, mode) # RS # High bits GPIO.output(LCD_D4, False) GPIO.output(LCD_D5, False) GPIO.output(LCD_D6, False) GPIO.output(LCD_D7, False) if bits & 0x10 == 0x10: GPIO.output(LCD_D4, True) if bits & 0x20 == 0x20: GPIO.output(LCD_D5, True) if bits & 0x40 == 0x40: GPIO.output(LCD_D6, True) if bits & 0x80 == 0x80: GPIO.output(LCD_D7, True) # Toggle 'Enable' pin time.sleep(E_DELAY) GPIO.output(LCD_E, True) time.sleep(E_PULSE) GPIO.output(LCD_E, False) time.sleep(E_DELAY) # Low bits GPIO.output(LCD_D4, False) GPIO.output(LCD_D5, False) GPIO.output(LCD_D6, False) GPIO.output(LCD_D7, False) if bits & 0x01 == 0x01: GPIO.output(LCD_D4, True) if bits & 0x02 == 0x02: GPIO.output(LCD_D5, True) if bits & 0x04 == 0x04: GPIO.output(LCD_D6, True) if bits & 0x08 == 0x08: GPIO.output(LCD_D7, True) # Toggle 'Enable' pin time.sleep(E_DELAY) GPIO.output(LCD_E, True) time.sleep(E_PULSE) GPIO.output(LCD_E, False) time.sleep(E_DELAY)
def flashturn(dir): if dir == robot.left: io.output(27, io.HIGH) time.sleep(0.2) io.output(27, io.LOW) elif dir == robot.right: io.output(5, io.HIGH) time.sleep(0.2) io.output(5, io.LOW) else: io.output(20, io.HIGH) time.sleep(0.2) io.output(20, io.LOW)
def __init__(self): GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) # Use BCM GPIO numbers GPIO.setup(LCD_E, GPIO.OUT) # E GPIO.setup(LCD_RS, GPIO.OUT) # RS GPIO.setup(LCD_D4, GPIO.OUT) # DB4 GPIO.setup(LCD_D5, GPIO.OUT) # DB5 GPIO.setup(LCD_D6, GPIO.OUT) # DB6 GPIO.setup(LCD_D7, GPIO.OUT) # DB7 GPIO.setup(LED_ON, GPIO.OUT) # Backlight enable # Initialise display self._lcd_byte(0x33, LCD_CMD) self._lcd_byte(0x32, LCD_CMD) self._lcd_byte(0x28, LCD_CMD) self._lcd_byte(0x0C, LCD_CMD) self._lcd_byte(0x06, LCD_CMD) self._lcd_byte(0x01, LCD_CMD) self.blight(1)
#sudo nano /etc/rc.local # before exit 0; add python /home/pi/off_button.py # # import RPi.GPIO as GPIO import os # # We chose GPIO16 beacuse is unused by HiFiBerry DAC+, Digi+ and Amp+ (i2C and gpio 18 to 21) #It's very important the pin is an input to avoid short-circuits #The pull-up resistor means the pin is high by default gpio_pin_number = 16 GPIO.setmode(GPIO.BCM) GPIO.setup(gpio_pin_number, GPIO.IN, pull_up_down=GPIO.PUD_UP) try: #Use falling edge detection to see if pin is pulled #low to avoid repeated polling GPIO.wait_for_edge(gpio_pin_number, GPIO.FALLING) #Send command to system to shutdown os.system("sudo shutdown -h now") except: pass #Revert all GPIO pins to their normal states (i.e. input = safe) GPIO.cleanup()
import RPi.GPIO as GPIO import time import pigpio pi = pigpio.pi() # Connect to local Pi. pin_IR = 16 pin_servo_open = 20 pin_servo_lock = 21 pin_switch = 26 bpm_list = [0, 0, 0, 0, 0] GPIO.setmode(GPIO.BCM) GPIO.setup(pin_IR, GPIO.IN) GPIO.setwarnings(False) GPIO.setup(pin_switch, GPIO.IN, pull_up_down=GPIO.PUD_UP) IR_cnt = 0 switch_cnt = 0 lock_switch = 0 #open_init #servo pi.set_servo_pulsewidth(pin_servo_open, 800) pi.set_servo_pulsewidth(pin_servo_lock, 800) time.sleep(1) try: while True: file = open("BPM_output.txt", 'r') data = file.read()
def _clean_up(self): GPIO.cleanup()
import math import RPi.GPIO as GPIO import xbox GPIO_RIGHT_BACK = 17 GPIO_RIGHT_FRONT = 18 GPIO_LEFT_BACK = 27 GPIO_LEFT_FRONT = 22 GPIO_LEFT_EN = 23 GPIO_RIGHT_EN = 24 GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(GPIO_RIGHT_BACK, GPIO.OUT) GPIO.setup(GPIO_RIGHT_FRONT, GPIO.OUT) GPIO.setup(GPIO_LEFT_BACK, GPIO.OUT) GPIO.setup(GPIO_LEFT_FRONT, GPIO.OUT) GPIO.setup(GPIO_LEFT_EN, GPIO.OUT) GPIO.setup(GPIO_RIGHT_EN, GPIO.OUT) def update_motors(x, y): if x < 0.0: # Stand still GPIO.output(GPIO_LEFT_BACK, 0) GPIO.output(GPIO_LEFT_FRONT, 0) elif x > 0.0: # third quadrant GPIO.output(GPIO_RIGHT_BACK, 0)
def blight(self, state): GPIO.output(LED_ON, state)
import RPi.GPIO as GPIO import time import os GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) class puertosGPIO: def __init__(self, pin, modo, default=1): self.pin = pin self.default = default if modo == "OUT": GPIO.setup(self.pin, GPIO.OUT) if self.default == 0: self.desactivarAlarma() def blink(self, ciclos, tiempo): if self.default == 1: #print( "Ejecucion iniciada...") iteracion = 0 while iteracion < ciclos: ## Segundos que durara la funcion GPIO.output(self.pin, True) #print("prende") time.sleep(tiempo) ## Esperamos 1 segundo GPIO.output(self.pin, False) #print("apaga") time.sleep(tiempo) ## Esperamos 1 segundo iteracion = iteracion + 1 #print("Ejecucion finalizada") else:
from gpiozero import PWMOutputDevice from time import sleep import time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) # Using BCM pin config #/////// Define Motort drivers /////// PWM_FORWARD_LEFT_PIN = 26 PWM_FORWARD_RIGHT_PIN = 13 PWM_REVERSE_LEFT_PIN = 19 PWM_REVERSE_RIGHT_PIN = 6 #////// Define pins for ultrasound /////// TRIG = 18 ECHO = 4 #////// Initialise Ultrasound GPIO.setup(TRIG, GPIO.OUT) GPIO.setup(ECHO, GPIO.IN) #//////// Initialise objects for H-Bridge PWM pins forwardLeft = PWMOutputDevice(PWM_FORWARD_LEFT_PIN, True, 0, 1000) reverseLeft = PWMOutputDevice(PWM_REVERSE_LEFT_PIN, True, 0, 1000) forwardRight = PWMOutputDevice(PWM_FORWARD_RIGHT_PIN, True, 0, 1000) reverseRight = PWMOutputDevice(PWM_REVERSE_RIGHT_PIN, True, 0, 1000)
def main(): try: while True: print "赤" GPIO.output (ledRed, True) sleep(interval) ledOff() print "青" GPIO.output (ledBlue, True) sleep(interval) ledOff() print "緑" GPIO.output (ledGreen, True) sleep(interval) ledOff() print "マゼンタ" GPIO.output (ledRed, True) GPIO.output (ledBlue, True) sleep(interval) ledOff() print "シアン" GPIO.output (ledBlue, True) GPIO.output (ledGreen, True) sleep(interval) ledOff() print "黃" GPIO.output (ledGreen, True) GPIO.output (ledRed, True) sleep(interval) ledOff() print "白" GPIO.output (ledRed, True) GPIO.output (ledBlue, True) GPIO.output (ledGreen, True) sleep(interval) ledOff() sleep (2) except KeyboardInterrupt: print " 終了しました" GPIO.cleanup()
def finalizoGPIO(): GPIO.cleanup() ## Hago una limpieza de los GPIO
# -*- coding: utf-8 -*- # Bezelie Sample Code for Raspberry Pi : 出力のサンプル # GPIO 16,20,21ピンとGNDにLEDを接続してから実行してください。 # ライブラリの読み込み from time import sleep # sleep(ウェイト処理)ライブラリの読み込み import RPi.GPIO as GPIO # GPIO(汎用入出力端子)ライブラリの読み込み # 変数 ledRed = 26 # as Red ledBlue = 20 # as Blue ledGreen = 21 # as Green interval = 1 # 色変え間隔 # 初期設定 GPIO.setmode(GPIO.BCM) GPIO.setup(ledRed, GPIO.OUT) GPIO.setup(ledBlue, GPIO.OUT) GPIO.setup(ledGreen, GPIO.OUT) # 関数 def ledOff(): GPIO.output (ledRed, False) GPIO.output (ledBlue, False) GPIO.output (ledGreen, False) sleep(0.04) # メインループ def main(): try: while True:
# Set vars from args try: command = args.com.upper() except AttributeError: print("Usage: python3 RRR.py -c [ON|BOOT|START / OFF|KILL|END / CYCLE|REBOOT|RESTART] -r [RIG-NUMBER]") exit() try: rigNum = args.rig except AttributeError: print("Uage: python3 RRR.py -c [ON|BOOT|START / OFF|KILL|END / CYCLE|REBOOT|RESTART] -r [RIG-NUMBER]") exit() # Set GPIO pin mode to BCM (Pin numbers, not GPIO types) GPIO.setmode(GPIO.BCM) # Check for a config file. Continue if found! try: open('config.ini') except FileNotFoundError: print("No config file found!\nPlease set up your config file by running 'python3 configCreator.py'") exit() # Read config file and set pins pinList = [] config = configparser.ConfigParser() config.read('config.ini') for key in config['PINS']: pinList.append(int(config['PINS'][key]))
# NODE import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(26, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(19, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(6, GPIO.OUT) GPIO.setup(12, GPIO.OUT) p = GPIO.PWM(12, 60) # ready_for_heartbreak = False servoMin = 150 servoMax = 600 ##def servo(channel, pulse): ## pulseLength = 1000000 ## pulseLength /= 60 ## pulseLength /= 4096 ## pulse *= 1000 ## pulse /= pulseLength ## pwm.setPWM(channel, 0, pulse) def smile(channel): GPIO.output(6, GPIO.HIGH) print('thats the stuff')
def ledOff(): GPIO.output (ledRed, False) GPIO.output (ledBlue, False) GPIO.output (ledGreen, False) sleep(0.04)
#! /usr/bin/env python from time import sleep import RPi.GPIO as GPIO import rospy from std_msgs.msg import Int32 DIR = 12 STEP = 5 CW = 1 CCW = 0 EN = 7 #M0=8 #M1=11 #M2=25 GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(EN, GPIO.OUT) #GPIO.setup(M0, GPIO.OUT) #GPIO.setup(M1, GPIO.OUT) #GPIO.setup(M2, GPIO.OUT) GPIO.setup(DIR, GPIO.OUT) GPIO.setup(STEP, GPIO.OUT) delay = 0.0005 #GPIO.output(M0, GPIO.LOW) #GPIO.output(M1, GPIO.LOW) #GPIO.output(M2, GPIO.LOW) GPIO.output(EN, GPIO.LOW) def walk():
def smile(channel): GPIO.output(6, GPIO.HIGH) print('thats the stuff') p.start(0.5) time.sleep(0.5) p.stop()
import RPi.GPIO as GPIO import os import re from csv import writer from datetime import datetime import time GPIO.setwarnings(True) GPIO.setmode(GPIO.BCM) def getTemps(): allTemps = list() ow_basedir = "/sys/bus/w1/devices/" ow_devices = os.listdir(ow_basedir) ow_retemp = re.compile('t=(\d*)') for thistring in ow_devices: if(thistring.startswith("28")): ow_path = os.path.join(ow_basedir, thistring, "w1_slave") ow_devfile = open(ow_path, "r") ow_devtext = ow_devfile.readlines() ow_temp = ow_retemp.search(ow_devtext[1]) allTemps.append(ow_temp.group(1)) print(allTemps)
def callback(distance): rospy.loginfo("starting motor..") angle = (360 * distance.data) / 4.71 if angle > 0: ##FOR CLOCKWISE DIRECTION rospy.loginfo("running motor %d cm forward", distance.data) step_count = (angle) / 1.8 rospy.loginfo(round(step_count)) step_count = round(step_count) rospy.loginfo(int(step_count)) for x in range(int(step_count)): GPIO.output(EN, GPIO.LOW) GPIO.output(DIR, GPIO.HIGH) GPIO.output(STEP, GPIO.HIGH) sleep(delay) GPIO.output(STEP, GPIO.LOW) sleep(delay) GPIO.output(EN, GPIO.HIGH) #sleep(0.005) elif angle < 0: ##FOR ANTICLOCKWISE DIRECTION angle = (angle) * (-1) rospy.loginfo("running motor %d cm backward", distance.data) a_step_count = (angle) / 1.8 rospy.loginfo(int(a_step_count)) a_step_count = round(a_step_count) a_step_count = int(a_step_count) #a_step_count=a_step_count*2 rospy.loginfo(int(a_step_count)) for x in range(int(a_step_count)): GPIO.output(EN, GPIO.LOW) GPIO.output(DIR, GPIO.LOW) GPIO.output(STEP, GPIO.HIGH) sleep(delay) GPIO.output(STEP, GPIO.LOW) sleep(delay) GPIO.output(EN, GPIO.HIGH) #sleep(0.005) GPIO.output(EN, GPIO.HIGH)