def atExit(): # set all output pins to 0 for pin in pinSignals: GPIO.output(pin, 0) # disable buzzer if defined if pinBuzzer > 0: GPIO.output(pinBuzzer, 0)
def single_led_on(n): if (A==-1): print "***********************************************" print "** **" print "** ERROR: you MUST call tree.setup() first!! **" print "** **" print "***********************************************" raise Exception('You MUST call tree.setup() first!!') # First, set all the nodes to be input (effectively # 'disconnecting' them from the Raspberry Pi) GPIO.setup(A, GPIO.IN) GPIO.setup(B, GPIO.IN) GPIO.setup(C, GPIO.IN) GPIO.setup(D, GPIO.IN) # Now determine which nodes are connected to the anode # and cathode for this LED if (n==1): anode, cathode = C, A elif (n==2): anode, cathode = C, D elif (n==4): anode, cathode = D, C elif (n==8): anode, cathode = D, B elif (n==16): anode, cathode = B, D elif (n==32): anode, cathode = A, B elif (n==64): anode, cathode = B, A elif (n==128): anode, cathode = A, C else: return # invalid LED number # Configure the anode and cathode nodes to be outputs GPIO.setup(anode, GPIO.OUT) GPIO.setup(cathode, GPIO.OUT) # Make the anode high (+3.3v) and the cathode low (0v) GPIO.output(anode, GPIO.HIGH) GPIO.output(cathode, GPIO.LOW)
def read_data(): base=0 data=[] # reset GPIO.setmode(GPIO.BCM) GPIO.setup( DHT11_DATA_PIN , GPIO.OUT) GPIO.output( DHT11_DATA_PIN , GPIO.LOW) time.sleep(0.03) # 必须大于18ms GPIO.setup( DHT11_DATA_PIN , GPIO.IN) while GPIO.input( DHT11_DATA_PIN ) == GPIO.HIGH: continue while GPIO.input( DHT11_DATA_PIN ) == GPIO.LOW: continue # 固定拉高80us,可用来做基准 while GPIO.input( DHT11_DATA_PIN ) == GPIO.HIGH: base += 1 continue base = base / 2 # Get data while len(data)< DHT11_DATA_LEN*8: i = 0 # 检测50us以上的低位 while GPIO.input( DHT11_DATA_PIN ) == GPIO.LOW: continue # 此时电平为高,持续26-28us表示0,否则持续70us表示1 while GPIO.input( DHT11_DATA_PIN ) == GPIO.HIGH: i += 1 if i > 100: #最后一个数据也许不会拉低,手动判断 break if i < base: data.append(0) else: data.append(1) print("DHT11 get data: ", data) return data
def start(): last = GPIO.input(button) while True: val = GPIO.input(button) if val != last: last = val if val == 1 and recorded == True: print 'Push button...' rf = open(path+'recording.wav', 'w') rf.write(audio) rf.close() inp = None alexa() elif val == 0: GPIO.output(25, 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 = "" l, data = inp.read() if l: audio += data recorded = True print 'Recording...' elif val == 0: l, data = inp.read() if l: audio += data
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 init(self): app.logger.info("INIT GPIO") try: GPIO.setmode(GPIO.BCM) app.logger.info(app.brewapp_hardware_config) for h in app.brewapp_hardware_config: hw = app.brewapp_hardware_config[h]; app.logger.info(hw) g = self.translateDeviceName(hw["config"]["switch"]) app.logger.info(g) if(g != None): app.logger.info("SETUP HARDWARE: " + str(h) + " GPIO: " + str(g)) GPIO.setup(g, GPIO.OUT) if(self.getConfigValue(h, "inverted", False)): app.logger.warning("SETUP INVERTED") GPIO.output(g, 1) else: app.logger.warning("SETUP NOT INVERTED") GPIO.output(g, 0) app.brewapp_gpio = True self.state = True app.logger.info("ALL GPIO INITIALIZED") except Exception as e: app.logger.error("SETUP GPIO FAILED " + str(e)) app.brewapp_gpio = False self.state = False
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 flickerLED(times = 1, ledPin = 23): GPIO.setup(ledPin, GPIO.OUT) for i in range(times): GPIO.output(ledPin, True) time.sleep(0.1) GPIO.output(ledPin, False) time.sleep(0.1)
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 set(pin, status): GPIO.setup(pin, GPIO.OUT) if status == True: status=GPIO.LOW else: status=GPIO.HIGH GPIO.output(pin, status)
def on(self): ''' Set the led on ''' if not self.__is_pulse: GPIO.output(self.__pin, self.__real_true) self.__is_on = True
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 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 setup(): gpio.setmode(gpio.BOARD) gpio.setup([ds, clock, latch], gpio.OUT) gpio.output([ds, clock, latch], gpio.LOW) gpio.setup([inc, count], gpio.IN, pull_up_down=gpio.PUD_UP)
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 sonar(): while finished != True: global globalstop GPIO_TRIGGER = 8 GPIO_ECHO = 8 GPIO.setup(8, GPIO.OUT) # Send 10us pulse to trigger GPIO.output(GPIO_TRIGGER, True) time.sleep(0.00001) GPIO.output(GPIO_TRIGGER, False) start = time.time() count = time.time() GPIO.setup(8, GPIO.IN) while GPIO.input(GPIO_ECHO) == 0 and time.time() - count < 0.1: start = time.time() stop = time.time() while GPIO.input(GPIO_ECHO) == 1: stop = time.time() # Calculate pulse length elapsed = stop - start # Distance pulse travelled in that time is time # multiplied by the speed of sound (cm/s) distance = elapsed * 34000 # That was the distance there and back so halve the value distance = distance / 2 if distance < 20: globalstop = 1 print("Too close") else: globalstop = 0 print("Far") time.sleep(1)
def __init__(self, VCC_Pin, Signal_Pin): self.VCC_Pin = VCC_Pin self. Signal_Pin = Signal_Pin GPIO.setmode(GPIO.BCM) GPIO.setup(VCC_Pin, GPIO.OUT, initial=True) GPIO.output(VCC_Pin, GPIO.HIGH) GPIO.setup(Signal_Pin, GPIO.IN, initial=False)
def main(): LED_OFF = 0 LED_ON = 1 - LED_OFF button_pins = [17, 13, 20, 23] led_pins = [27, 19, 21, 24] for pin in button_pins: GPIO.setup( pin, GPIO.IN, pull_up_down = GPIO.PUD_DOWN ) for pin in led_pins: GPIO.setup( pin, GPIO.OUT, initial = LED_OFF ) led = 0 while True: text = '' for pin in [0,1,2,3]: text += '{0}'.format(pin) if GPIO.input(button_pins[pin]) else ' ' print(text) GPIO.output(led_pins[led], LED_OFF) led += 1 if led == 4: led = 0 GPIO.output(led_pins[led], LED_ON) time.sleep(0.5)
def send(module, value): # to do : evaluate using bitwise operations to make this faster? #if moduleMap_d == False: # print "You must run init() before using this module" # return False # make with the bit stuffing module_bin_str = dec2bin(module, 6) value_bin_str = dec2bin(value, 16) word1_str = value_bin_str[11:16] + module_bin_str + "0" word2_str = value_bin_str[0:11] + "1" print "duplexPort.py | send |", module, value for i in range(12): pin = PINS_OUT[i] val = int(word1_str[i]) #print pin, val GPIO.output(pin,val) #time.sleep(.1) #p = read() #time.sleep(.1) for i in range(12): pin = PINS_OUT[i] val = int(word2_str[i]) #print pin, val GPIO.output(pin,val)
def led_change(): if ledstatus.get(): gpio.output(37, gpio.HIGH) lbl.configure(text="Die LED leuchtet.") else: gpio.output(37, gpio.LOW) lbl.configure(text="Die LED ausgeschalten.")
def set_pin(pin, val): if val == 1: GPIO.output(pin, GPIO.HIGH) elif val == 0: GPIO.output(pin, GPIO.LOW) else: raise Exception('invalid value')
def handleLightChange(data): roomId = data['roomId'] state = data['state'] pinNumber = pins['light'][roomId][0][0]['pinNumber'] if state == 1: GPIO.output(pinNumber, GPIO.HIGH) if state == 0: GPIO.output(pinNumber, GPIO.LOW) for states in pins['light'].itervalues(): for pinState in states[0]: pinState['state'] = GPIO.input(pinState['pinNumber']) states[1]['overallState'] = GPIO.input(states[0][0]['pinNumber']) emit('serverResponse', { 'type': 'light', 'roomId': roomId, 'state': pins['light'][roomId][1]['overallState'] }, broadcast=True) print "Light change!" return
def hold(): GPIO.output(ledPin, GPIO.HIGH) # printer.printImage(Image.open('gfx/goodbye.png'), True) # printer.feed(3) # subprocess.call("sync") subprocess.call(["shutdown", "-h", "now"]) GPIO.output(ledPin, GPIO.LOW)
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(18, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(17, GPIO.OUT) # GPIO.setup(25,GPIO.OUT) # GPIO.output(25,True) while True: pressed = not GPIO.input(18) if pressed: # the button is being pressed, so turn on the green LED # and turn off the red LED GPIO.output(17,True) # GPIO.output(25,False) print "button true" else: # the button isn't being pressed, so turn off the green LED # and turn on the red LED GPIO.output(17,False) # GPIO.output(25,True) print "button false" time.sleep(0.1) print "button pushed" GPIO.cleanup()
def setup_io_pins(self): GPIO.setmode(GPIO.BCM) GPIO.setup(pedal, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(led_rgb, GPIO.OUT) GPIO.setup(led_peak, GPIO.OUT) GPIO.setup(rf_pin, GPIO.IN) GPIO.output(led_peak, 1)
def toggle_garage(): if GPIO_installed: print 'Garage Pin True' GPIO.output(garage_pin, GPIO.LOW) time.sleep(1) print 'Garage Pin False' GPIO.output(garage_pin, GPIO.HIGH)
def sonar(n): # Send 10us pulse to trigger GPIO.output(GPIO_TRIGGER, True) time.sleep(0.00001) GPIO.output(GPIO_TRIGGER, False) start = time.time() # this doesn't allow for timeouts ! while GPIO.input(GPIO_ECHO)==0: start = time.time() while GPIO.input(GPIO_ECHO)==1: stop = time.time() # Calculate pulse length elapsed = stop-start # Distance pulse travelled in that time is time # multiplied by the speed of sound (cm/s) distance = elapsed * 34000 # That was the distance there and back so halve the value distance = distance / 2 return distance
def recv_ack(self): gp.output(self.sda_pin, 1) gp.setup(self.sda_pin, gp.IN) res = self.get_sda_lv() self.clk_one() gp.setup(self.sda_pin, gp.OUT) return res
def shiftInData(self, data, length): for i in np.arange(length): if data & (1 << ((length - 1) - i)) > 0: GPIO.output(SDI, GPIO.HIGH) else: GPIO.output(SDI, GPIO.LOW) self.pulseSCK()
def fan_control(function): if function == "on": print("Turning fan", function) GPIO.output(relay, GPIO.LOW) if function == "off": print("Turning fan", function) GPIO.output(relay, GPIO.HIGH)
def runFan(): GPIO.output(FAN_1, GPIO.HIGH) GPIO.output(FAN_2, GPIO.LOW)
def destroy(): global Pwm Pwm.stop() GPIO.output(LedPin, GPIO.LOW) GPIO.cleanup()
def setup(): GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(pecho, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(ptrig, GPIO.OUT) GPIO.output(ptrig, 0)
def forward(speed_left,speed_right): GPIO.output(IN1, GPIO.HIGH) GPIO.output(IN2, GPIO.LOW) GPIO.output(IN3, GPIO.HIGH) GPIO.output(IN4, GPIO.LOW) changespeed(speed_left,speed_right)
def stopcar(): GPIO.output(IN1, GPIO.LOW) GPIO.output(IN2, GPIO.LOW) GPIO.output(IN3, GPIO.LOW) GPIO.output(IN4, GPIO.LOW) changespeed(0,0)
def left_turn(speed_left,speed_right): GPIO.output(IN1, GPIO.HIGH) GPIO.output(IN2, GPIO.LOW) GPIO.output(IN3, GPIO.LOW) GPIO.output(IN4, GPIO.HIGH) changespeed(speed_left,speed_right)
def stopFan(): GPIO.output(FAN_1, GPIO.LOW) GPIO.output(FAN_2, GPIO.LOW)
def actionMq5(pin): GPIO.output(11, False) #Enviamos la señal de activación al buzzer pin 7 HIGH time.sleep(1) #La señal (pitido) dura 5 segundos GPIO.output(11,True) #Cerramos la señal poniendo el pin 7 en LOW y el buzzer se calla. print('Sensor mq5 detected action!') return
def Motor_Forward(): print 'motor forward' GPIO.output(ENA,GPIO.HIGH) GPIO.output(ENB,GPIO.HIGH) GPIO.output(IN1,GPIO.HIGH) GPIO.output(IN2,GPIO.LOW) GPIO.output(IN3,GPIO.HIGH) GPIO.output(IN4,GPIO.LOW)
## -- Code Starts Here -- ## # Setup Code # GPIO.setmode(GPIO.BCM) # Use BCM pin numbering for GPIO # Display Running Sketch Info (?) # LED Pin setup GPIO.setup(yled, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(rled, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(gled, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(ddPin, GPIO.OUT, initial=GPIO.LOW) # Wake Up Roomba Sequence Roomba.write(itb(7)) # Restart Roomba time.sleep(8) # wait 8 seconds before continuing GPIO.output(gled, GPIO.HIGH) # Turn on green LED to say we are alive print(" STARTING ROOMBA... ") Roomba.write(itb(128)) # START command time.sleep(1) Roomba.write(itb(131)) # Control command # 131 = Safe Mode # 132 = Full Mode (Be ready to catch it!) time.sleep(0.1) BlinkCleanLight() # Blink the Clean light on Roomba # Main Code # message = "Hello World!" Xbee.write(message.encode()) # Send test message x = 0 # Move Roomba
def Motor_TurnRight(): print 'motor_turnright' GPIO.output(ENA,GPIO.HIGH) GPIO.output(ENB,GPIO.HIGH) GPIO.output(IN1,GPIO.LOW) GPIO.output(IN2,GPIO.HIGH) GPIO.output(IN3,GPIO.HIGH) GPIO.output(IN4,GPIO.LOW)
#!/usr/bin/env python # -*- coding: utf-8 -*- #the sensor has to be connected to pin 1 for power, pin 6 for ground # and pin 7 for signal(board numbering!). import time, sys import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) #GPIO.setmode(GPIO.BCM) GPIO.setup(7, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(11, GPIO.OUT)#Indicamos que el pin 11 será de salida GPIO.output(11,True) #Indicamos que el pin 11 esta LOW (sin señal) GPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) def actionMq5(pin): GPIO.output(11, False) #Enviamos la señal de activación al buzzer pin 7 HIGH time.sleep(1) #La señal (pitido) dura 5 segundos GPIO.output(11,True) #Cerramos la señal poniendo el pin 7 en LOW y el buzzer se calla. print('Sensor mq5 detected action!') return def actionTermo(pin): for i in range(5): GPIO.output(11, False) #Enviamos la señal de activación al buzzer pin 7 HIGH time.sleep(0.1) #La señal (pitido) dura 5 segundos GPIO.output(11,True) #Cerramos la señal poniendo el pin 7 en LOW y el buzzer se calla. time.sleep(0.1) GPIO.output(11, False) time.sleep(0.1)
def lampon(request): GPIO.setmode(GPIO.BCM) GPIO.setup(2, GPIO.OUT) GPIO.output(2, True) return HttpResponse("Turned on")
def Motor_Stop(): print 'motor_stop' GPIO.output(ENA,GPIO.LOW) GPIO.output(ENB,GPIO.LOW) GPIO.output(IN1,GPIO.LOW) GPIO.output(IN2,GPIO.LOW) GPIO.output(IN3,GPIO.LOW) GPIO.output(IN4,GPIO.LOW)
GPIO.setmode(GPIO.BOARD) # pin setup GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # aux GPIO.setup(13, GPIO.OUT) # M0 GPIO.setup(15, GPIO.OUT) # M1 ser = serial.Serial(port='/dev/serial0', baudrate=9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=1) # set transmitter/receiver mode GPIO.output(13, GPIO.LOW) GPIO.output(15, GPIO.LOW) try: while True: ## aux = GPIO.input(12)- ## print('aux val '+str(aux)) ser.write(b'3') # num="3" # ser.write(bytes(num.encode("ascii"))) ## if ser.in_waiting: ## print('rxd val '+str(ser.readline())) GPIO.cleanup() ser.close()
def Motor_TurnLeft(): print 'motor_turnleft' GPIO.output(ENA,GPIO.HIGH) GPIO.output(ENB,GPIO.HIGH) GPIO.output(IN1,GPIO.HIGH) GPIO.output(IN2,GPIO.LOW) GPIO.output(IN3,GPIO.LOW) GPIO.output(IN4,GPIO.HIGH)
def detectFace(faces, hog, img): for (x, y, w, h) in faces: #Tạo khuôn hình vuông để hiện thị cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) result = cv2.face.MinDistancePredictCollector() rec.predict(hog[y:y + h, x:x + w], result, 0) id = result.getLabel() conf = result.getDist() if (conf < 50): if (id == 1): id = "Tu_" + str(conf) #Lưu lại thông tin người dùng vào Cơ sở dữ liệu nếu nhận diện thành công. sql = """INSERT INTO Detail(ID, Name, tdate, ttime) values('1','Tu', CURRENT_DATE(), NOW())""" curs.execute(sql) #Lưu ảnh của người được nhận và thư mục DataAsset với định dạng User.id_người_sử_dụng.jpg . cv2.imwrite("DataAsset/User." + id + '.' + ".jpg", gray[y:y + h, x:x + w]) #2s luu vao Database 1 lan. #time.sleep(2) #Commit lên Mysql db.commit() #Động cơ Servo sẽ mở cửa. servo.ChangeDutyCycle(5.5) GPIO.output(ledPinOpen, GPIO.HIGH) time.sleep(1) GPIO.output(ledPinOpen, GPIO.LOW) #servo.stop() # servo.ChangeDutyCycle(5.5) # time.sleep(2) elif (id == 2): id = "Thang_" + str(conf) #Lưu lại thông tin người dùng vào Cơ sở dữ liệu nếu nhận diện thành công sql = """INSERT INTO Detail(ID, Name, tdate, ttime) values('2','Thang', CURRENT_DATE(), NOW())""" curs.execute(sql) #Lưu ảnh của người được nhận. cv2.imwrite("DataAsset/User." + id + '.' + ".jpg", gray[y:y + h, x:x + w]) #time.sleep(2) db.commit() servo.ChangeDutyCycle(5.5) GPIO.output(ledPinOpen, GPIO.HIGH) time.sleep(1) GPIO.output(ledPinOpen, GPIO.LOW) #servo.stop() # servo.ChangeDutyCycle(5.5) # time.sleep(2) else: id = "Unknow" sql = """INSERT INTO Detail(ID, Name, tdate, ttime) values('3','Unknow', CURRENT_DATE(), NOW())""" curs.execute(sql) #Lưu ảnh của người được nhận. cv2.imwrite("DataAsset/Unknow." + '.' + ".jpg", gray[y:y + h, x:x + w]) #time.sleep(2) db.commit() GPIO.output(ledPinWarning, GPIO.HIGH) time.sleep(1) GPIO.output(ledPinWarning, GPIO.LOW) buzzer.ChangeFrequency(1000) time.sleep(1) buzzer.ChangeFrequency(1) #count = count + 1 #if (count == 3) : # buzzer.ChangeFrequency(1000) # time.sleep(2) # buzzer.ChangeFrequency(1) # count = 0 cv2.putText(img, str(id), (x, y + h), font, 1, (255, 255, 255), 2, cv2.LINE_AA)
def distSense(self): GPIO.output(TRIG, False) time.sleep(0.000001) GPIO.output(TRIG, True) time.sleep(0.00001) GPIO.output(TRIG, False) GPIO.output(TRIG2, False) time.sleep(0.000001) GPIO.output(TRIG2, True) time.sleep(0.00001) GPIO.output(TRIG2, False) while GPIO.input(ECHO) == 0 or GPIO.input(ECHO2) == 0: StartTime = time.time() while GPIO.input(ECHO) == 1 or GPIO.input(ECHO2) == 1: StopTime = time.time() TimeElapsed = StopTime - StartTime distance = TimeElapsed * 17150 distance = round(distance, 2) return distance
AIN2 = 6 PWMA = 5 BIN1 = 26 BIN2 = 20 PWMB = 21 # Define led pins as output GPIO.setup(STDBY, GPIO.OUT) GPIO.setup(AIN1, GPIO.OUT) GPIO.setup(AIN2, GPIO.OUT) GPIO.setup(BIN1, GPIO.OUT) GPIO.setup(BIN2, GPIO.OUT) GPIO.setup(PWMA, GPIO.OUT) GPIO.setup(PWMB, GPIO.OUT) # Run PWM GPIO.output(AIN1, 0) GPIO.output(AIN2, 1) GPIO.output(BIN1, 0) GPIO.output(BIN2, 1) GPIO.output(STDBY, 1) #Default 50% Duty Cycle, Tweak for appropriate speed while (1): GPIO.output(PWMA, 1) GPIO.output(PWMB, 1) #time.sleep(0.005) #GPIO.output(PWMA, 0) #GPIO.output(PWMB, 0) #time.sleep(0.005)
#DiamondFinder - Written by Johnathan Powell for Cache Makers #Program activate when a button is pressed on pin 14 (using BCM numbering) #Searches a 3x3 collumn below the player to the bottom of the world for diamond ore, if #ore is found, light will illuminate and the number of blocks found will be output in chat. from mcpi.minecraft import Minecraft mc = Minecraft.create() import time import RPi.GPIO as GPIO buttonPin = 14 ledPin = 23 GPIO.setmode(GPIO.BCM) GPIO.setup(buttonPin, GPIO.IN) GPIO.setup(ledPin, GPIO.OUT) GPIO.output(ledPin, False) try: #loop until keyboard interrupt while True: #if button is pressed if GPIO.input(buttonPin): mc.postToChat("Now finding diamonds...") found = 0 x, y, z = mc.player.getPos() ytest = y #search down to the bottom of the world while ytest > -63: bi = mc.getBlock(x, ytest, z) #if block is a diamond if bi == 56:
led = 24 import RPi.GPIO as GPIO from time import sleep GPIO.setmode(GPIO.BCM) GPIO.setup(led, GPIO.OUT) while True: GPIO.output(led, GPIO.HIGH) sleep(1) GPIO.output(led, GPIO.LOW) sleep(1)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) equ = cv2.equalizeHist(gray) faces = face_cascade.detectMultiScale(equ, 1.3, 5) if len(faces) == 0: rows, cols = equ.shape M = cv2.getRotationMatrix2D((cols / 2, rows / 2), 30, 1) dst = cv2.warpAffine(equ, M, (cols, rows)) faces = face_cascade.detectMultiScale(dst, 1.3, 5) if len(faces) == 0: rows, cols = equ.shape M = cv2.getRotationMatrix2D((cols / 2, rows / 2), -30, 1) dst = cv2.warpAffine(equ, M, (cols, rows)) faces = face_cascade.detectMultiScale(dst, 1.3, 5) #Nút được nhấn mới bắt đầu nhận diện và đèn led sáng. if buttonState == False: GPIO.output(ledPin, GPIO.HIGH) detectFace(faces, dst, img) else: GPIO.output(ledPin, GPIO.LOW) else: #Nút được nhấn mới bắt đầu nhận diện và đèn led sáng if buttonState == False: GPIO.output(ledPin, GPIO.HIGH) detectFace(faces, dst, img) else: GPIO.output(ledPin, GPIO.LOW) else: if buttonState == False: GPIO.output(ledPin, GPIO.HIGH) detectFace(faces, equ, img) else:
def turnleft(self): # self.reset() GPIO.output(self.IN1,False) GPIO.output(self.IN2,True) GPIO.output(self.IN3,True) GPIO.output(self.IN4,False)
#!/usr/bin/python import RPi.GPIO as GPIO import os import time GPIO.setmode(GPIO.BOARD) GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(26, GPIO.OUT) GPIO.output(26, 0) while True: if (GPIO.input(16) == 1): print("ON") elif (GPIO.input(16) == 0): print("OFF") time.sleep(0.25) os.system('clear')
def backward(self): # self.reset() GPIO.output(self.IN1,False) GPIO.output(self.IN2,True) GPIO.output(self.IN3,False) GPIO.output(self.IN4,True)
t = time.localtime() #Get Status inputValue = GPIO.input(17) intValue= str(inputValue) try: while forever == 1: while GPIO.input(switchPin)== False: CurrentTime=time.strftime('%H') # Get current time in hours only TimeInt = int(CurrentTime) print (TimeInt) if (TimeInt <=CheckEnd) or (TimeInt >=CheckStart): GPIO.cleanup(relayPin) GPIO.setup(relayPin, GPIO.OUT, initial=GPIO.LOW) GPIO.output(relayPin, 1) time.sleep(0.5) GPIO.cleanup(relayPin) print ("Garage Open") f = open('relay-status.txt','w') f.write(intValue) f.close() t = time.localtime() print (time.asctime(t)) server = smtplib.SMTP( sendersmtp, 587 ) server.starttls() server.login(sender, senderpw) server.sendmail(sender, receiver, message ) server.quit() print ("Close door request sent. Text sent! Checking again in 5 minutes")
def stop(self): #Rest all the GPIO as LOW GPIO.output(self.IN1,False) GPIO.output(self.IN2,False) GPIO.output(self.IN3,False) GPIO.output(self.IN4,False)
def turnright(self): # self.reset() GPIO.output(self.IN1,True) GPIO.output(self.IN2,False) GPIO.output(self.IN3,False) GPIO.output(self.IN4,True)
#!/usr/bin/python3 import RPi.GPIO as GPIO import cgi, cgitb GPIO.setmode(GPIO.BCM) GPIO.setup(23, GPIO.OUT) form = cgi.FieldStorage() coolstat = form.getvalue("led2") print("Content-type: text/html\n\n") if (coolstat != None): if (coolstat == "power_on"): cooler_power = 1 print("Cooler is ON") else: cooler_power = 0 print("Cooler is OFF") GPIO.output(23, cooler_power) else: if (GPIO.input(23) == 1): print("Cooler is ON") else: print("Cooler is OFF")
def forward(self): # self.reset() GPIO.output(self.IN1,True) GPIO.output(self.IN2,False) GPIO.output(self.IN3,True) GPIO.output(self.IN4,False)