def read_tag_serial(self): GPIO.cleanup() MIFAREReader = MFRC522.MFRC522() (status, TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL) if status == MIFAREReader.MI_OK: (status, uid) = MIFAREReader.MFRC522_Anticoll() if status == MIFAREReader.MI_OK: result = hex(uid[0])[2:].zfill(2) + hex(uid[1])[2:].zfill(2) + hex(uid[2])[2:].zfill(2) + hex(uid[3])[2:].zfill(2) return result else: return None else: return None
def MFRC522_Init(self): GPIO.output(self.NRSTPD, 1) self.MFRC522_Reset(); self.Write_MFRC522(self.TModeReg, 0x8D) self.Write_MFRC522(self.TPrescalerReg, 0x3E) self.Write_MFRC522(self.TReloadRegL, 30) self.Write_MFRC522(self.TReloadRegH, 0) self.Write_MFRC522(self.TxAutoReg, 0x40) self.Write_MFRC522(self.ModeReg, 0x3D) self.AntennaOn()
def stop(self): super().stop() GPIO.cleanup()
import os import sys import time from threading import Thread import OPi.GPIO as GPIO D0 = 3 D1 = 5 GPIO.setmode(GPIO.BOARD) GPIO.setup(D0, GPIO.IN) GPIO.setup(D1, GPIO.IN) def listen_card(): while True: cardnumber = 0 bit_count = 0 for x in range(0, 26): data0 = GPIO.input(D0) data1 = GPIO.input(D1) while (data0 == 1 and data1 == 1): data0 = GPIO.input(D0) data1 = GPIO.input(D1) cardnumber = cardnumber << 1 if data1 == 1: cardnumber = cardnumber | 0x01 bit_count += 1
def resetModem(): GPIO.output( onPin, GPIO.LOW) # set the GSM ON/OFF pin to low to turn off the modem time.sleep(10) GPIO.output( onPin, GPIO.HIGH) # set the GSM ON/OFF pin to high to turn on the modem time.sleep(5) # Then Toggle the power key GPIO.output(pwrKey, GPIO.HIGH) GPIO.output(pwrKey, GPIO.LOW) time.sleep(5) GPIO.output(pwrKey, GPIO.HIGH) time.sleep(30) status = GPIO.input(statusPin) dns = '8.8.8.8' if gsmConf.get('DNS') is None else gsmConf.get('DNS') apn = 'airtelgprs.com' if gsmConf.get('APN') is None else gsmConf.get( 'APN') apnUser = '******' if gsmConf.get('APN_USER') is None else gsmConf.get( 'APN_USER') apnPass = '******' if gsmConf.get('APN_PASS') is None else gsmConf.get( 'APN_PASS') usbInterface = '3' if gsmConf.get('USBINTERFACE') is None else gsmConf.get( 'USBINTERFACE') usbModem = '1e0e:9001' if gsmConf.get('USBMODEM') is None else gsmConf.get( 'USBMODEM') command = f'sudo sakis3g "connect" DNS="{dns}" APN="CUSTOM_APN" CUSTOM_APN="{apn}" APN_USER="******" APN_PASS="******" USBINTERFACE="{usbInterface}" OTHER="USBMODEM" USBMODEM="{usbModem}"' try: if status == 1: subprocess.call([command], shell=True) except Exception as e: LOG.error('Error resetting modem : %s', e) time.sleep(5) LOG.info('GSM Status: %s', GPIO.input(statusPin))
#!/usr/bin/env python # -*- coding: utf-8 -*- import OPi.GPIO as GPIO from time import sleep GPIO.setboard(GPIO.ZEROPLUS2H5) GPIO.setmode(GPIO.SOC) # set up SOC numbering alive_gpio = GPIO.PA + 7 GPIO.setup(alive_gpio, GPIO.OUT) try: print 'Arduino-OPi watchdog started' while True: GPIO.output(alive_gpio, 1) # set port/pin value to 1/HIGH/True sleep(0.7) GPIO.output(alive_gpio, 0) sleep(80) except KeyboardInterrupt: GPIO.output(alive_gpio, 0) GPIO.cleanup() # clean up after yourself print 'Arduino-OPi watchdog finished'
import time import sys import OPi.GPIO as GPIO import orangepi.pipc BOARD = orangepi.pipc.BOARD GPIO.setmode(BOARD) pin=int(sys.argv[1]) GPIO.setup(pin, GPIO.OUT) while True: GPIO.output(pin, GPIO.HIGH) time.sleep(1) GPIO.output(pin, GPIO.LOW) time.sleep(1)
def led_on(): print("LED ON") GPIO.output(LED_PIN, 1)
import OPi.GPIO as GPIO GPIO.setboard(GPIO.PCPCPLUS) GPIO.setmode(GPIO.BOARD) # for i in range (1, 25): # try: # GPIO.setup(i, 1) # print(i) # except: # pass GPIO.setup(15, GPIO.OUT)
def cleanup(): for pin in [c11, c12, c21, c22]: GPIO.output(pin, 0) GPIO.cleanup()
def setup(): GPIO.setboard(GPIO.PCPCPLUS) GPIO.setmode(GPIO.BOARD) for pin in [c11, c12, c21, c22]: GPIO.setup(pin, GPIO.OUT)
def bw(delay): GPIO.output(c21, 1) GPIO.output(c22, 0) sleep(delay) GPIO.output(c21, 0) GPIO.output(c11, 1) GPIO.output(c12, 0) sleep(delay) GPIO.output(c11, 0) GPIO.output(c21, 0) GPIO.output(c22, 1) sleep(delay) GPIO.output(c22, 0) GPIO.output(c11, 0) GPIO.output(c12, 1) sleep(delay) GPIO.output(c12, 0)
def end_read(signal, frame): global continue_reading print "Ctrl+C captured, ending read." continue_reading = False GPIO.cleanup()
#!/usr/bin/env python3 try: import OPi.GPIO as GPIO GPIO.setboard(GPIO.PRIME) # Orange Pi PC board GPIO.setmode(GPIO.BOARD) # set up BOARD BCM numbering GPIO.setwarnings(True) # Turn warnings on/off except: print("Error importing the GPIO lib, exit") exit(1) # Pins estilo BCM PIN_FANCONTROL = 7 PIN_DHT11 = 35 # import dht11 import time import datetime # from timeloop import Timeloop from datetime import timedelta from influxdb import InfluxDBClient from math import sqrt # timeloop instance tl = Timeloop() INTERVAL_MEASURE = 30 INTERVAL_PUSH = 300 ## vars
#!/usr/bin/env python # -*- coding: utf-8 -*- import OPi.GPIO as GPIO from time import sleep # this lets us have a time delay GPIO.setboard(GPIO.PCPCPLUS) # Orange Pi PC board GPIO.setmode(GPIO.BOARD) # Declaration of the break between the changes of the relay status (in seconds) delayTime = 1 # Declaration of the input pin which is connected with the sensor. Additional to that, the pullup resistor will be activated. RELAIS_PIN = 40 GPIO.setup(RELAIS_PIN, GPIO.OUT) GPIO.output(RELAIS_PIN, False) print "Sensor-test [press ctrl+c to end]" # Main program loop try: while True: GPIO.output(RELAIS_PIN, True) # NO is now connected through time.sleep(delayTime) GPIO.output(RELAIS_PIN, False) # NC is now connected through time.sleep(delayTime) except KeyboardInterrupt: # here you put any code you want to run before the program # exits when you press CTRL+C print "An error or exception occurred!"
#!/usr/bin/envy python # -*- coding utf-8 -*- import OPi.GPIO as GPIO from time import sleep GPIO.setboard(GPIO.ZEROPLUS2H3) GPIO.setmode(GPIO.BOARD) #led = GPIO.PA+3 GPIO.setup(3, GPIO.OUT) while 1: GPIO.output(3, 1) sleep(0.1) GPIO.output(3, 0) sleep(0.1)
import os import sys import time import OPi.GPIO as g g.setwarnings(False) g.setmode(g.BOARD) prog = 'y1 g1 s1 g0 s1 r1 s2 r0 y0' for item in prog.split(): cmd = item[0].lower() val = item[1:] if cmd == 's': time.sleep(float(val)) if cmd == 'r': if val == '1': g.setup(12, g.OUT) g.output(12, 0) g.cleanup(12) else: g.setup(12, g.IN) g.cleanup(12) if cmd == 'g': if val == '1': g.setup(15, g.OUT) g.output(15, 0) g.cleanup(15) else: g.setup(15, g.IN) g.cleanup(15)
import OPi.GPIO as GPIO import time LED_PIN = 35 GPIO.setboard(GPIO.PC2) GPIO.setmode(GPIO.BOARD) GPIO.setup(LED_PIN, GPIO.OUT) def led_on(): print("LED ON") GPIO.output(LED_PIN, 1) def led_off(): print("LED OFF") GPIO.output(LED_PIN, 0)
def resetPinMode(self): print "resetting pin mode" self.stopServod() print "servod stopped" for pin in self.validPins: try: self.pinRef[pin].stop() # stop PWM from running self.pinRef[pin] = None except: pass self.pinRef[pin] = None #reset pwm flag try: GPIO.remove_event_detect(pin) #Stop Any event detection for input and counting except: pass try: self.callbackInUse[pin] = False #reset event callback flags except: pass if (self.pinUse[pin] == self.POUTPUT): GPIO.setup(pin,GPIO.IN) elif (self.pinUse[pin] == self.PINPUT): GPIO.setup(pin,GPIO.IN) elif (self.pinUse[pin] == self.PINPUTDOWN): GPIO.setup(pin,GPIO.IN) elif (self.pinUse[pin] == self.PINPUTNONE): GPIO.setup(pin,GPIO.IN) elif (self.pinUse[pin] == self.PCOUNT): GPIO.setup(pin,GPIO.IN) self.pinUse[pin] = self.PUNUSED self.pinServoValue[pin] = None print "reset pin", pin self.pinValue[pin] = 0 self.pinInvert[pin] = False
def led_off(): print("LED OFF") GPIO.output(LED_PIN, 0)
def setPinMode(self): for pin in self.validPins: #print pin try: GPIO.remove_event_detect(pin) except: pass try: self.callbackInUse[pin] = False except: pass if (self.pinUse[pin] == self.POUTPUT): print 'setting pin' , pin , ' to out' GPIO.setup(pin,GPIO.OUT) if (self.pinInvert[pin] == True): GPIO.output(pin,1) else: GPIO.output(pin,0) self.pinValue[pin] = 0 elif (self.pinUse[pin] == self.PINPUT): print 'setting pin' , pin , ' to in with pull up' GPIO.setup(pin,GPIO.IN,pull_up_down=GPIO.PUD_UP) try: GPIO.add_event_detect(pin, GPIO.BOTH, callback=self.gpioBoth,bouncetime=50) # add rising edge detection on a channel except: pass elif (self.pinUse[pin] == self.PINPUTDOWN): print 'setting pin' , pin , ' to in with pull down' GPIO.setup(pin,GPIO.IN,pull_up_down=GPIO.PUD_DOWN) try: GPIO.add_event_detect(pin, GPIO.BOTH, callback=self.gpioBoth,bouncetime=50) # add rising edge detection on a channel except: pass elif (self.pinUse[pin] == self.PINPUTNONE): print 'setting pin' , pin , ' to in with pull down' GPIO.setup(pin,GPIO.IN) try: GPIO.add_event_detect(pin, GPIO.BOTH, callback=self.gpioBoth,bouncetime=50) # add rising edge detection on a channel except: pass elif (self.pinUse[pin] == self.PCOUNT): if self.callbackInUse[pin] == False: print 'setting pin' , pin , ' as counting pin' GPIO.setup(pin,GPIO.IN)#,pull_up_down=GPIO.PUD_DOWN)#,pull_up_down=GPIO.PUD_DOWN) try: # add event callback but use try block just in case its already set if self.encoderCallback == 1: #GPIO.add_event_detect(pin, GPIO.RISING, callback=self.my_callbackB)#,bouncetime=10) # add rising edge detection on a channel self.callbackInUse[pin] = True self.encoderCallback = 2 if self.debug: print "callback B set for pin ", pin if self.encoderCallback == 0: #GPIO.add_event_detect(pin, GPIO.RISING, callback=self.my_callbackA)#,bouncetime=10) # add rising edge detection on a channel self.callbackInUse[pin] = True self.encoderCallback = 1 if self.debug: print "callback A set for pin ", pin except Exception,e: print "Error on event detection setup on pin" ,pin print str(e) else: print ("Callback already in use")
def __init__(self): self.volume = 1 self.preMuteVolume = self.volume self.button = 0 self.last_screen_update = time.time() self.cast = False print('Trying to get handle to Chromecast ' + config.chromecasts[0] + '...') try: self.get_cast_handle(config.chromecasts[0]) except cat_api.CastError as error: logging.error(logging.exception(error)) sys.exit("ERROR: Couldn't connect to '" + config.chromecasts[0] + "'. Check config.py and name/IP.") if config.use_display: print('Trying to initialize screen on default i2c bus...') try: self.screen = Oled(); self.show(';)') sleep(.5) except Exception as error: logging.error(logging.exception(error)) sys.exit('ERROR Could not access screen: ' + str(error)) if config.board_type == 'orange': GPIO.setboard(GPIO.ZERO) # for orange pi zero GPIO.setmode(GPIO.BOARD) # for orange pi zero if config.board_type == 'raspberry': GPIO.setmode(GPIO.BCM) # for rasbpian on raspberry pi GPIO.setup(config.clk, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(config.dt, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(config.sw, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.add_event_detect(config.sw, GPIO.FALLING, callback=self.toggleMute, bouncetime=500)
def cleanup(self): GPIO.cleanup()
def __init__(self, pin): self.pin = pin self.is_on = False GPIO.setup(pin, GPIO.OUT) GPIO.output(pin, 0)
def __init__(self, debug=False): GPIO.setboard(GPIO.PCPCPLUS) # Orange Pi PC Plus board GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.cleanup() self.piRevision = 3 #self.piRevision = self.getPiRevision() self.i2cbus = 1 #if self.piRevision == 1: # self.i2cbus = 0 #print "RPi.GPIO Version" , GPIO.VERSION print "OPi.GPIO Version" , GPIO.VERSION #print "Board Revision" , self.piRevision #self.numOfPins = 41 #Orange Pi has 40 #Set some constants and initialise lists self.numOfPins = 27 #there are actually 26 but python can't count properly :) if self.piRevision > 2: self.numOfPins = 41 self.PINPUT = 4 self.POUTPUT = 1 self.PPWM = 2 self.PUNUSED = 8 self.PSONAR = 16 self.PULTRA = 32 self.PSERVOD = 64 self.PSTEPPER = 128 self.PCOUNT = 256 self.PINPUTDOWN = 512 self.PINPUTNONE = 1024 self.PPWMMOTOR = 2048 self.PPWMLED = 4096 #self.INVERT = False self.ledDim = 100 self.PWMMOTORFREQ = 10 self.dsSensorId = "" self.senderLoopDelay = 0.2 self.mFreq = 10 self.ultraFreq = 1 self.ultraSamples = 7 self.pFreq = 200 self.pinUse = [self.PUNUSED] * self.numOfPins self.servodPins = None self.pinRef = [None] * self.numOfPins self.pinCount = [0] * self.numOfPins self.countDirection = [1] * self.numOfPins self.pinEncoderDiff = [0] * self.numOfPins self.encoderStopCounting = [0] * self.numOfPins self.pinLastState = [0] * self.numOfPins self.encoderTime = [0] * self.numOfPins self.encoderTimeDiff = [0.0] * self.numOfPins self.gpioLookup = [0] * self.numOfPins self.callbackInUse = [False] * self.numOfPins self.pinValue = [0] * self.numOfPins self.pinInvert = [False] * self.numOfPins #print "pinValue" , self.pinValue #print "pin Value 3 = ", self.pinValue[3] self.pinUltraRef = [None] * self.numOfPins self.pinTrigger = [0] * self.numOfPins self.pinTriggerName = ["x"] * self.numOfPins self.anyTrigger = 0 self.pinServoValue = [None] * self.numOfPins self.gpioMyPinEventDetected = [False] * self.numOfPins self.pinTriggerLastState = [0] * self.numOfPins self.encoderCallback = 0 self.piAndBash = [self.PUNUSED] * 16 self.pinEventEnabled = True self.encoderInUse = 0 self.nunchuckLevel = 1 self.capTouch = None self.capTouchHelper = None self.ADS1015 = None self.lightDirection = 0 self.lightValue = 0 self.lightInfo = False self.autoLink = False self.linkPrefix = None self.linkIP = None self.mqttBroker = None self.mqttListener = None self.mqttClient = None self.mqttTopic = None self.mqttRetainFlag = True self.pinMapName = [None] * self.numOfPins self.stepperAPos = 0 self.stepperBPos = 0 self.stepperDPos = 0 self.validPins = [ 3, 5, 7, 8, 10,11,12,13, 15,16, 18,19, 21,22,23,24, 26] if self.piRevision == 1: # 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 # [ 3, 5,99,99, 7,99,99,26,24,21,19,23,99,99, 8,10,99,11,12,99,99,13,15,16,18,22,99] self.gpioLookup = [99,99,99, 0,99, 1,99, 4,14,99,15,17,18,21,99,22,23,99,24,10,99, 9,25,11, 8,99, 7] if self.piRevision == 2: self.gpioLookup = [99,99,99, 2,99, 3,99, 4,14,99,15,17,18,27,99,22,23,99,24,10,99, 9,25,11, 8,99, 7] if self.piRevision > 2: self.validPins = [ 3, 5, 7, 8, 10,11,12,13, 15,16, 18,19, 21,22,23,24, 26, 29, 31,32,33, 35,36,37,38, 40] self.gpioLookup = [99,99,99, 3,99, 5,99, 7, 8,99,10,11,12,13,99,15,16,99,18,19,99,21,22,23,24,99,26,99,99,29,99,31,32,33,99,35,36,37,38,99,40] #[99,99,99, 2,99, 3,99, 4,14,99,15,17,18,27,99,22,23,99,24,10,99, 9,25,11, 8,99, 7,99,99, 5,99, 6,12,13,99,19,16,26,20,99,21] self.revgpioLookup = [99] *41 for index, item in enumerate(self.gpioLookup): if item != 99: self.revgpioLookup[item] = index #print self.revgpioLookup #self.ULTRA_IN_USE = [False] * self.PINS #self.ultraTotalInUse = 0 #self.ultraSleep = 1.0 self.debug = debug if self.debug: print "sghGC Debug enabled"
#!/usr/bin/env python # -*- coding: utf-8 -*- import OPi.GPIO as GPIO import time # this lets us have a time delay GPIO.setboard(GPIO.PCPCPLUS) GPIO.setmode(GPIO.BOARD) # Declaration and initialisation of the input pins which are connected with the sensor. PIN_CLK = 13 PIN_DT = 12 BUTTON_PIN = 11 GPIO.setup(PIN_CLK, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(PIN_DT, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Needed variables will be initialised Counter = 0 Richtung = True PIN_CLK_LETZTER = 0 PIN_CLK_AKTUELL = 0 delayTime = 0.01 # Initial reading of Pin_CLK PIN_CLK_LETZTER = GPIO.input(PIN_CLK) # This output function will start at signal detection
def pinUpdate(self, pin, value,type = 'plain',stepDelay = 0.003): #print "pinUpdate p,v,t,pwmref: ",pin,value,type,self.pinRef[pin] #print "pin",pin #print "pvalue",self.pinValue self.pinValue[pin] = value self.mFreq = max(5,abs(value/2)) if (self.ledDim < 100) and (type == 'plain'): type = "pwm" value = value * self.ledDim try: #print pin,value,type,self.pinUse[pin] if type[0:3] == "pwm": # #print "processing pwm" #return if (self.pinInvert[pin] == True): # Invert data value (needed for active low devices) value = 100 - abs(value) #print "motor freq calc", self.mFreq try: #print "try jsut updating pwm" self.pinRef[pin].ChangeDutyCycle(max(0,min(100,abs(value)))) # just update PWM value if type == "pwmmotor": #print "motor freq used a", self.mFreq self.pinRef[pin].ChangeFrequency(self.mFreq) # change freq to motor freq elif type != "pwmbeep": #print "motor freq used a", self.mFreq self.pinRef[pin].ChangeFrequency(self.pFreq) # change freq to motor freq #print "updating pwm suceceed" except: #print "pwm not set so now setting up" try: GPIO.remove_event_detect(pin) self.callbackInUse[pin] = False except: pass GPIO.setup(pin,GPIO.OUT) # Setup if type == "pwmmotor": #print "motor freq used b", self.mFreq self.pinRef[pin] = GPIO.PWM(pin,self.mFreq) # create new PWM instance elif type != "pwmbeep": #print "motor freq used a", self.mFreq self.pinRef[pin] = GPIO.PWM(pin,self.pFreq) # create new PWM instance self.pinRef[pin].start(max(0,min(100,abs(value)))) # update PWM value #print "pwm setup on pin",pin, "now has ref",self.pinRef[pin] self.pinUse[pin] = self.PPWM # set pin use as PWM elif type == "plain": #print "Plain processing- Pin " , pin , " commanded to be " , value #print "pinUpdate p,v,t,pwmref: ",pin,value,type,self.pinRef[pin] if (self.pinInvert[pin] == True): # Invert data value (useful for 7 segment common anode displays) value = 1 - abs(value) if (self.pinUse[pin] == self.POUTPUT): # if already an output GPIO.output(pin, int(value)) # set output to 1 ot 0 #print 'pin' , pin , ' was already an output. Now set to' , value elif (self.pinUse[pin] in [self.PINPUT,self.PINPUTNONE,self.PINPUTDOWN]): # if pin is an input try: GPIO.remove_event_detect(pin) self.callbackInUse[pin] = False except: pass self.pinUse[pin] = self.POUTPUT # switch it to output GPIO.setup(pin,GPIO.OUT) GPIO.output(pin, int(value)) # set output to 1 to 0 #print 'pin' , pin , ' was an input - change to output value' , value elif (self.pinUse[pin] == self.PUNUSED): # if pin is not allocated self.pinUse[pin] = self.POUTPUT # switch it to output GPIO.setup(pin,GPIO.OUT) GPIO.output(pin,int(value)) # set output to 1 or 0 #print 'pin' , pin , ' was ununsed - now out value ' , value elif (self.pinUse[pin] == self.PPWM): # pin was set as pwm #print "pinUpdate p,v,t,pwmref: ",pin,value,type,self.pinRef[pin] try: #print "pinUpdate p,v,t,pwmref: ",pin,value,type,self.pinRef[pin] #print ("Stopping previous instance on pin",pin) #print "pinref on pin" ,pin , "is" ,self.pinRef[pin] self.pinRef[pin].stop() #print ("previous instance on pin",pin ,"stopped") self.pinRef[pin] = None except: pass self.pinUse[pin] = self.POUTPUT # switch it to output GPIO.setup(pin,GPIO.OUT) #print "switched to output" GPIO.output(pin, int(value)) # set output to 1 to 0 #print 'pin' , pin , ' was PWM now set to ' , value except ValueError: print "mistake made in trying to update an invalid pin" print pin,value,type pass
def __init__(self, pins, params): super().__init__(params) GPIO.setboard(GPIO.ZEROPLUS2H5) GPIO.setmode(GPIO.BOARD) GPIO.setup(pins['ENABLE'], GPIO.OUT) GPIO.setup(pins['STEP'], GPIO.OUT) GPIO.setup(pins['DIR'], GPIO.OUT) # GPIO.setup(pins['PWM'], GPIO.OUT) GPIO.setup(pins['FIRE'], GPIO.OUT) self.enable_pin = lambda x: GPIO.output(pins['ENABLE'], x) self.step_pin = lambda x: print('step') or GPIO.output(pins['STEP'], x) self.dir_pin = lambda x: GPIO.output(pins['DIR'], x) self.pwm_pin = lambda x: print('[M] PWM PIN ->', x) self.fire_pin = lambda x: GPIO.output(pins['FIRE'], x)
def pinSonar2(self, trig,echo): #print pin #print self.pinUse[pin] self.pinUse[trig] = self.PSONAR self.pinUse[echo] = self.PSONAR GPIO.setup(trig,GPIO.OUT) ti = time.time() # setup a list to hold 3 values and then do 3 distance calcs and store them #print 'sonar started' distlist = [0] * self.ultraSamples distance = 0 ts=time.time() try: for k in range(self.ultraSamples): #print "sonar pulse" , k GPIO.output(trig, 0) time.sleep(0.06)#set pin low for 60ms as per spec sheet to allow for old pulses not finished GPIO.output(trig, 1) # Send Pulse high time.sleep(0.00002) # wait GPIO.output(trig, 0) # bring it back low - pulse over. t0=time.time() # remember current time GPIO.setup(echo,GPIO.IN) #PIN_USE[i] = PINPUT don't bother telling system t1=t0 # This while loop waits for input pin (7) to be low but with a timeout while ((GPIO.input(echo)==0) and ((t1-t0) < 0.02)): #time.sleep(0.00001) t1=time.time() t1=time.time() #print 'low' , (t1-t0) * 1000 t2=t1 # This while loops waits for input pin to go high to indicate pulse detection # with timeout #tcount = 0 while ((GPIO.input(echo)==1) and ((t2-t1) < 0.02)): #time.sleep(0.000005) t2=time.time() #tcount += 1 t2=time.time() #print "tcount",tcount #print 'high' , (t2-t1).microseconds t3=(t2-t1) # t2 contains time taken for pulse to return #print "time of pulse flight " , t3 * 1000 # 20cm (40 in total ~~ 1.2 milliseconds) #distance = t3 * 17150 # calc distance in cm t3 * 343 / 2 * 100 distlist[k]=int(t3 * 17150) #print distance GPIO.setup(trig,GPIO.OUT) #tf = time.time() - ts #print ("Proctime:",tf) #print ("Dist:",sorted(distlist)) #print "mid: ", self.ultraSamples / 2 distance = sorted(distlist)[int(self.ultraSamples / 2)] # sort the list and pick middle value as best distance except: print ("ultra fail") pass #print "total time " , tf #for k in range(5): #print distlist[k] #print "pulse time" , distance*58 #print "total time in microsecs" , (tf-ti).microseconds # only update Scratch values if distance is < 500cm if (distance > 280): distance = 299 if (distance < 2): distance = 1 #distance = "x:" +str(int(distlist[0])) + "*" + str(int(distlist[1])) +"*" + str(int(distlist[2])) +"*" + str(int(distlist[3])) +"*" + str(int(distlist[4])) #distance = "fred" return int(distance) return distance
def __init__(self, dev='/dev/spidev1.0', spd=1000000): spi.openSPI(device=dev, speed=spd) GPIO.setmode(GPIO.BOARD) GPIO.setup(22, GPIO.OUT) GPIO.output(self.NRSTPD, 1) self.MFRC522_Init()
#!/usr/bin/env python # -*- coding: utf-8 -*- import OPi.GPIO as GPIO from time import sleep # this lets us have a time delay pin = 12 GPIO.setboard(GPIO.THREE) # Orange Pi PC board GPIO.setmode(GPIO.BOARD) # set up BOARD BCM numbering GPIO.setup(pin, GPIO.OUT) # set BCM7 (pin 26) as an output (LED) try: print("Press CTRL+C to exit") while True: GPIO.output(pin, 1) # set port/pin value to 1/HIGH/True sleep(0.1) GPIO.output(pin, 0) # set port/pin value to 0/LOW/False sleep(0.1) GPIO.output(pin, 1) # set port/pin value to 1/HIGH/True sleep(0.1) GPIO.output(pin, 0) # set port/pin value to 0/LOW/False sleep(0.1) sleep(0.5) except KeyboardInterrupt: GPIO.output(pin, 0) # set port/pin value to 0/LOW/False GPIO.cleanup() # Clean GPIO print("Bye.")
#Needed modules will be imported and configured. import OPi.GPIO as GPIO from time import sleep # this lets us have a time delay GPIO.setboard(GPIO.PCPCPLUS) GPIO.setmode(GPIO.BOARD) # Output pin declaration for the Buzzer. Buzzer_PIN = 7 GPIO.setup(Buzzer_PIN, GPIO.OUT, initial=GPIO.LOW) print("Buzzer-test [press ctrl+c to end the test]") # Main program loop try: while True: print("Buzzer will be on for 4 seconds") GPIO.output(Buzzer_PIN, GPIO.HIGH) #Buzzer will be switched on sleep(4) #Waitmode for 4 seconds print("Buzzer will be off for 4 seconds") GPIO.output(Buzzer_PIN, GPIO.LOW) #Buzzer will be switched off sleep( 2) #Waitmode for another 2 seconds in which the buzzer will be off except KeyboardInterrupt: # here you put any code you want to run before the program # exits when you press CTRL+C print("An error or exception occurred!") except:
def __init__(self, dev='/dev/spidev1.0', spd=1000000): spi.openSPI(device=dev,speed=spd) GPIO.setmode(GPIO.BOARD) GPIO.setup(22, GPIO.OUT) GPIO.output(self.NRSTPD, 1) self.MFRC522_Init()