def importarGPIO(): #importamos la libreria GPIO import RPi.GPIO as GPIO #Definimos el modo BCM GPIO.setmode(GPIO.BCM) #Desactivo Errores GPIO.setwarnings(False) #Importamos la libreria time import time #Ahora definimos Todos los pines del 2-11 como salida GPIO.setup(2, GPIO.OUT) GPIO.setup(3, GPIO.OUT) GPIO.setup(4, GPIO.OUT) GPIO.setup(5, GPIO.OUT) GPIO.setup(6, GPIO.OUT) GPIO.setup(7, GPIO.OUT) GPIO.setup(8, GPIO.OUT) GPIO.setup(9, GPIO.OUT) GPIO.setup(10, GPIO.OUT) GPIO.setup(11, GPIO.OUT) #Importamos la libreria para comandos de la consola/shell import os
def initializeSystem(): # Setup GPIO GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(alert, GPIO.IN, pull_up_down = GPIO.PUD_UP) GPIO.setup(switch, GPIO.IN, pull_up_down = GPIO.PUD_UP)
def reset(self): if self._rst > 0: GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(self._rst, GPIO.OUT) # toggle pin GPIO.output(self._rst, GPIO.HIGH) sleep(0.1) GPIO.output(self._rst, GPIO.LOW) sleep(0.1) GPIO.output(self._rst, GPIO.HIGH) sleep(0.2) # give it some time to come back GPIO.cleanup(self._rst)
def manageInputs(): print "Setting the switches to inputs" GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) #Set pull-ups to pins GPIO.setup(5, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(26, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(19, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(6, GPIO.IN, pull_up_down=GPIO.PUD_UP) #Read inputs just one time input_state_5 = GPIO.input(5) input_state_26 = GPIO.input(26) input_state_19 = GPIO.input(19) input_state_13 = GPIO.input(13) input_state_6 = GPIO.input(6) GPIO.setmode(GPIO.BCM) GPIO.setup(LED1, GPIO.OUT) GPIO.setup(LED2, GPIO.OUT) GPIO.setup(LED3, GPIO.OUT) GPIO.setup(LED4, GPIO.OUT) GPIO.setup(LED5, GPIO.OUT) GPIO.setup(LED6, GPIO.OUT) GPIO.setup(LED7, GPIO.OUT) GPIO.setup(LED8, GPIO.OUT) GPIO.setup(LED9, GPIO.OUT)
def initBrickPi(): BrickPiSetup() # setup the serial port for communication BrickPi.MotorEnable[PORT_A] = 1 #Enable the Motor A BrickPi.MotorEnable[PORT_B] = 1 #Enable the Motor B BrickPi.MotorEnable[PORT_C] = 1 #Enable the Motor C BrickPi.MotorEnable[PORT_D] = 1 #Enable the Motor D BrickPi.MotorSpeed[PORT_A] = 0 #Set the speed of MotorA (-255 to 255) BrickPi.MotorSpeed[PORT_B] = 0 #Set the speed of MotorB (-255 to 255) BrickPi.MotorSpeed[PORT_C] = 0 #Set the speed of MotorC (-255 to 255) BrickPi.MotorSpeed[PORT_D] = 0 #Set the speed of MotorD (-255 to 255) BrickPi.SensorType[PORT_1] = TYPE_SENSOR_TOUCH #Bumper right bumper BrickPi.SensorType[PORT_4] = TYPE_SENSOR_TOUCH #Bumper left bumper BrickPiSetupSensors() #Send the properties of sensors to BrickPi #Setup GPIO for LEDs GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(12, GPIO.OUT) #right LED GPIO.setup(13, GPIO.OUT) #left LED updateStuff = threading.Thread( target=updateBrickPi ); updateStuff.start()
def initilise_gpio(self): gpio.setwarnings(False) gpio.setmode(gpio.BCM) for mapping in self.gpio_mapping['mapping']: gpio_pin = int(self.gpio_mapping['mapping'][mapping]) gpio.setup(gpio_pin, gpio.OUT)
def __init__(self): self.log('AquaPi initializing...') GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(PIN_POWER, GPIO.OUT) self.led = BlinkM() self.led.reset() self.led.set_fade_speed(self.led_fade_speed) # self.led.write_script_line(Scripts.TRANSFER, 0, 10, 'c', 0xff, 0xff, 0xff) # self.led.write_script_line(Scripts.TRANSFER, 1, 10, 'c', 0x00, 0x00, 0x00) self.spi = spidev.SpiDev() self.spi.open(0, SPI_ADC) self.sio = serial.Serial('/dev/ttyAMA0', 9600, serial.EIGHTBITS, serial.PARITY_NONE, serial.STOPBITS_ONE, 1) self.sensor_temp = TempSensor(self.spi, ADC_TEMP) self.sensor_light = AnalogSensor(self.spi, ADC_LIGHT) self.sensor_liquid = SerialSensor(self.sio) self.metro_sensor_sample = Metro(500) self.metro_sensor_send = Metro(30000) self.metro_poll = Metro(6000) self.metro_health = Metro(180000) self.events = deque() self.running = False self.current_color = False self.happy()
def __init__(self): pygame.mixer.init(44100) self.pin = 10 GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(self.pin, GPIO.IN) self.sounds = { 0: [pygame.mixer.Sound('/home/pi/space_balls/sounds/start.ogg')], 1: [pygame.mixer.Sound('/home/pi/space_balls/sounds/shoot.ogg')], 2: [pygame.mixer.Sound('/home/pi/space_balls/sounds/hit.ogg')], 3: [pygame.mixer.Sound('/home/pi/space_balls/sounds/lose_evil.ogg'), pygame.mixer.Sound('/home/pi/space_balls/sounds/lose_cmon.ogg'), pygame.mixer.Sound('/home/pi/space_balls/sounds/lose_blimp.ogg'), pygame.mixer.Sound('/home/pi/space_balls/sounds/lose_friends.ogg'), pygame.mixer.Sound('/home/pi/space_balls/sounds/lose_goof.ogg'), pygame.mixer.Sound('/home/pi/space_balls/sounds/lose_gunner.ogg')] } self.SEND_SOUND = 0; self.dev = usb.core.find(idVendor = 0x6666, idProduct = 0x0003) if self.dev is None: raise ValueError('No USB device found matching idVendor and idProduct') self.dev.set_configuration() GPIO.add_event_detect(self.pin, GPIO.RISING, callback=self.receive_sound) if GPIO.input(self.pin): self.receive_sound(self.pin)
def posibilidad(): GPIO.setwarnings(False) cuenta=0 while True: if(GPIO.input(2)): cuenta=cuenta+1 print"boton 1" if(GPIO.input(3)): cuenta=0 print"boton 2" if(GPIO.input(4)): cuenta=cuenta-1 print"boton 3" if(cuenta>6): GPIO.output(17,True) GPIO.output(27,False) GPIO.output(22,False) if(cuenta>4): GPIO.output(27,True) GPIO.output(17,False) GPIO.output(22,False) if(cuenta>1): GPIO.output(22,True) GPIO.output(17,False) GPIO.output(27,False)
def main(): parser = argparse.ArgumentParser('3ch PWM controller') parser.add_argument("-c","--channel", type=int, help="output channel", default = 3) parser.add_argument("-v","--value", type=int, help="pwm value (maybe in percentage)") parser.add_argument("-f","--freq", type=int, help="pwm frequency", default = 50) args = parser.parse_args() channel = args.channel value = args.value freq = args.freq GPIO.setwarnings(False) #pinRed = 3 #pinGreen = 5 #pinBlue = 7 GPIO.setup(channel, GPIO.OUT) #GPIO.setup(pinRed, GPIO.OUT) #GPIO.setup(pinGreen, GPIO.OUT) #GPIO.setup(pinBlue, GPIO.OUT) p = GPIO.PWM(channel, freq) # channel=pinRed frequency=50Hz #chGreen = GPIO.PWM(pinGreen, 200) # channel=pinRed frequency=50Hz #chBlue = GPIO.PWM(pinBlue, 200) # channel=pinRed frequency=50Hz p.start(100) p.ChangeFrequency(50) # where freq is the new frequency in Hz p.ChangeDutyCycle(value) raw_input('Press return to stop:') # use raw_input for Python 2 p.stop() GPIO.cleanup()
def init(self,bitrate,SDAPIN,SCLPIN): if(SDAPIN != SCLPIN): self.SCL = SCLPIN self.SDA = SDAPIN else: print "SDA = GPIO"+str(self.SDA)+" SCL = GPIO"+str(self.SCL) #configer SCL as output GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(self.SCL, GPIO.OUT) GPIO.setup(self.SDA, GPIO.OUT) GPIO.output(self.SDA, GPIO.HIGH) GPIO.output(self.SCL, GPIO.HIGH) if bitrate == 100: self.int_clk = 0.0000025 elif bitrate == 400: self.int_clk = 0.000000625 elif bitrate == 1000: self.int_clk = 1 elif bitrate == 3200: self.int_clk = 1
def __init__(self, RS=2, EN=3, DB=[22,27,17,4], RGB=[9,10,11]): self.RS = RS self.EN = EN self.DB = DB self.RGB = [] GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) #disable warnings GPIO.setup(self.RS, GPIO.OUT) GPIO.setup(self.EN, GPIO.OUT) for pin in self.DB: GPIO.setup(pin, GPIO.OUT) for x in xrange(0, len(RGB)): GPIO.setup(RGB[x], GPIO.OUT) self.RGB.append(GPIO.PWM(RGB[x], 50)) self.RGB[x].start(100) #start at 100% self.write4bits(0x33) # initialization self.write4bits(0x32) # initialization self.write4bits(0x28) # 2 line 5x7 matrix self.write4bits(0x0C) # turn cursor off 0x0E to enable cursor self.write4bits(0x06) # shift cursor right """ Initialize to default text direction (for romance languages) """ self.displaymode = self.LCD_ENTRYLEFT | self.LCD_ENTRYSHIFTDECREMENT self.write4bits(self.LCD_ENTRYMODESET | self.displaymode) # set the entry mode self.clear()
def setupGPIO(): GPIO.setwarnings(False) GPIO.cleanup() GPIO.setmode(GPIO.BCM) GPIO.setup(button, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(lights, GPIO.OUT) GPIO.output(lights, GPIO.LOW)
def setup_gpio(): GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) for inputNumber in inputNumbers: GPIO.setup(inputNumber, GPIO.IN)
def TM1638_init(): GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(DIO, GPIO.OUT) GPIO.setup(CLK, GPIO.OUT) GPIO.setup(STB, GPIO.OUT) sendCommand(0x8f)
def __init__(self, pin_rs=25, pin_e=24, pins_db=[23, 17, 21, 22], GPIO=None): # Emulate the old behavior of using RPi.GPIO if we haven't been given # an explicit GPIO interface to use if not GPIO: import RPi.GPIO as GPIO GPIO.setwarnings(False) self.GPIO = GPIO self.pin_rs = pin_rs self.pin_e = pin_e self.pins_db = pins_db self.GPIO.setmode(GPIO.BCM) self.GPIO.setup(self.pin_e, GPIO.OUT) self.GPIO.setup(self.pin_rs, GPIO.OUT) for pin in self.pins_db: self.GPIO.setup(pin, GPIO.OUT) self.write4bits(0x33) # initialization self.write4bits(0x32) # initialization self.write4bits(0x28) # 2 line 5x7 matrix self.write4bits(0x0C) # turn cursor off 0x0E to enable cursor self.write4bits(0x06) # shift cursor right self.displaycontrol = self.LCD_DISPLAYON | self.LCD_CURSOROFF | self.LCD_BLINKOFF self.displayfunction = self.LCD_4BITMODE | self.LCD_1LINE | self.LCD_5x8DOTS self.displayfunction |= self.LCD_2LINE # Initialize to default text direction (for romance languages) self.displaymode = self.LCD_ENTRYLEFT | self.LCD_ENTRYSHIFTDECREMENT self.write4bits(self.LCD_ENTRYMODESET | self.displaymode) # set the entry mode self.clear()
def __init__(self): # Need a state set for this launcher. self.menu = ["Remote Control"] self.menu += ["Three Point Turn"] self.menu += ["Straight Line Speed"] self.menu += ["Line Following"] self.menu += ["Proximity"] self.menu += ["Quit Challenge"] self.menu += ["Power Off Pi"] self.menu_quit_challenge = 3 # default menu item is remote control self.menu_state = 0 self.menu_button_pressed = False self.drive = None self.wiimote = None # Current Challenge self.challenge = None self.challenge_name = "" GPIO.setwarnings(False) self.GPIO = GPIO # LCD Display self.lcd = Adafruit_CharLCD( pin_rs=25, pin_e=24, pins_db=[23, 17, 27, 22], GPIO=self.GPIO ) self.lcd.begin(16, 1) self.lcd.clear() self.lcd.message('Initiating...') self.lcd_loop_skip = 5 # Shutting down status self.shutting_down = False
def __init__(self, update_shift_reg=False, update_arduino=True): self.last_time = time.time() gpio.setmode(gpio.BCM) gpio.setwarnings(False) if update_arduino: self.arduino = arduino.Arduino("ttyACM0") #self.cup_dispenser_uno = arduino.Arduino("ttyACM1") self.nano = arduino.Arduino("ttyUSB") else: self.arduino = None for output in Outputs: if output.value < _SHIFT_REG_ADDRESS_OFFSET: gpio.setup(output.value, gpio.OUT) self.WriteOutput(output, 0) for pin in Inputs: gpio.setup(pin.value, gpio.IN, pull_up_down=gpio.PUD_UP) if update_shift_reg: self.current_shifted_byte = [0] * 24 self.current_shifted_byte[Outputs.COMPRESSOR.value - _SHIFT_REG_ADDRESS_OFFSET] = 1 self.signal_refresh = Queue.Queue(1) self.thread = threading.Thread(target=self.__RefreshShiftOutputs) self.thread.daemon = True self.thread.start() self.WriteOutput(Outputs.COMPRESSOR, 0)
def right_stop_at_black(): cap = cv2.VideoCapture(0) GPIO.setmode (GPIO.BCM) GPIO.setwarnings (False) GPIO.setup (23, GPIO.OUT) GPIO.setup (22, GPIO.OUT) PWML4 = GPIO.PWM (22,100) PWMR4 = GPIO.PWM (23,100) PWMR4.start(0) PWML4.start(0) counter =0 while(1): ret, img = cap.read() ret,thresh = cv2.threshold(img,130,255,cv2.THRESH_BINARY) b1,g1,r1 = thresh[250,520] PWMR4.ChangeDutyCycle(90) PWML4.ChangeDutyCycle(90) if (b1>200 and g1>200 and r1>200): counter+=1 elif counter>0: PWMR4.stop() PWML4.stop() break cap.release() #GPIO.cleanup() return
def load_settings(): """Loads the settings to know gpio ports and returns a dictionary""" gpio.setwarnings(False) settings_file = open('/home/pi/gpio_settings.cfg') settings = json.load(settings_file) return settings
def test_alreadyinuse(self): """Test 'already in use' warning""" GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) with open('/sys/class/gpio/export','wb') as f: f.write(str(LED_PIN_BCM).encode()) time.sleep(0.05) # wait for udev to set permissions with open('/sys/class/gpio/gpio%s/direction'%LED_PIN_BCM,'wb') as f: f.write(b'out') with open('/sys/class/gpio/gpio%s/value'%LED_PIN_BCM,'wb') as f: f.write(b'1') with warnings.catch_warnings(record=True) as w: GPIO.setup(LED_PIN, GPIO.OUT) # generate 'already in use' warning self.assertEqual(len(w),0) # should be no warnings with open('/sys/class/gpio/unexport','wb') as f: f.write(str(LED_PIN_BCM).encode()) GPIO.cleanup() GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(True) with open('/sys/class/gpio/export','wb') as f: f.write(str(LED_PIN_BCM).encode()) time.sleep(0.05) # wait for udev to set permissions with open('/sys/class/gpio/gpio%s/direction'%LED_PIN_BCM,'wb') as f: f.write(b'out') with open('/sys/class/gpio/gpio%s/value'%LED_PIN_BCM,'wb') as f: f.write(b'1') with warnings.catch_warnings(record=True) as w: GPIO.setup(LED_PIN, GPIO.OUT) # generate 'already in use' warning self.assertEqual(w[0].category, RuntimeWarning) with open('/sys/class/gpio/unexport','wb') as f: f.write(str(LED_PIN_BCM).encode()) GPIO.cleanup()
def __init__(self,pin_step=0,delay=0.1,pin_direction=0,pin_ms1=0,pin_ms2=0,pin_sleep=0,pin_enable=0,pin_reset=0,name="Stepper"): self.pin_step = pin_step self.delay = delay / 2 self.pin_direction = pin_direction self.pin_microstep_1 = pin_ms1 self.pin_microstep_2 = pin_ms2 self.pin_sleep = pin_sleep self.pin_enable = pin_enable self.pin_reset = pin_reset self.name = name gpio.setmode(gpio.BCM) gpio.setwarnings(False) if self.pin_step > 0: gpio.setup(self.pin_step, gpio.OUT) if self.pin_direction > 0: gpio.setup(self.pin_direction, gpio.OUT) gpio.output(self.pin_direction, True) if self.pin_microstep_1 > 0: gpio.setup(self.pin_microstep_1, gpio.OUT) gpio.output(self.pin_microstep_1, False) if self.pin_microstep_2 > 0: gpio.setup(self.pin_microstep_2, gpio.OUT) gpio.output(self.pin_microstep_2, False) if self.pin_sleep > 0: gpio.setup(self.pin_sleep, gpio.OUT) gpio.output(self.pin_sleep,True) if self.pin_enable > 0: gpio.setup(self.pin_enable, gpio.OUT) gpio.output(self.pin_enable,False) if self.pin_reset > 0: gpio.setup(self.pin_reset, gpio.OUT) gpio.output(self.pin_reset,True)
def gpio_setup(): GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(LED, GPIO.OUT) GPIO.setup(TRIG, GPIO.OUT) GPIO.setup(ECHO, GPIO.IN) GPIO.output(TRIG, False)
def water(sensor): GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) if sensor == 0: GPIO.setup(17,GPIO.OUT) GPIO.setup(27,GPIO.IN) GPIO.output(17, GPIO.LOW) time.sleep(1.0) GPIO.output(17, True) time.sleep(0.00001) GPIO.output(17, False) while GPIO.input(27) == 0: signaloff = time.time() while GPIO.input(27) == 1: signalon = time.time() timepassed = signalon - signaloff distance = timepassed * 17000 consumido = distance * 35 volumen = 100 - ((consumido * 100) / 15000) value = str (volumen) redondeo = value [:4] print (redondeo) else: print ("Incorrect usonic() function varible.")
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 reading(sensor): GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(24, GPIO.OUT) GPIO.setup(24, GPIO.LOW) GPIO.setup(25,GPIO.IN) if sensor == 0: time.sleep(0.3) GPIO.output(24, True) time.sleep(0.00001) GPIO.output(24, False) while GPIO.input(25) == 0: signaloff = time.time() while GPIO.input(25) == 1: signalon = time.time() timepassed = signalon - signaloff distance = timepassed * 17000 return distance GPIO.cleanup()
def setup(): GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(mclk,GPIO.OUT, initial=GPIO.LOW) GPIO.setup(mosi,GPIO.OUT) GPIO.setup(sclk,GPIO.IN) GPIO.setup(miso,GPIO.IN)
def getInstance(): if Sensor.__instance is None: GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.cleanup() Sensor.__instance=dht11.DHT11(pin=23) return Sensor.__instance
def __init__(self): gpio.setwarnings(False) gpio.setmode(gpio.BOARD) self.logger = logger.Logger() self.config = config.Config() self.config.read_config() self.cameras_switcher = cameras_switcher.CamerasSwitcher(gpio) self.pi_camera = PiCamera() self.pi_camera.resolution = (1920, 1080) self.protected_areas = protected_areas.ProtectedAreas(self.logger, gpio, self.cameras_switcher, self.pi_camera) self.modem = modem.Modem(self.logger) self.email = email_sender.EmailSender(self.logger, self.config) self.sms = sms.Sms(self.config, self.email) self.detectors_controller = detectors.Detectors(self.config, self.protected_areas) self.avail_space_controller = avail_space.AvailSpace(self.logger) self.alarm_controller = alarm.Alarm( self.logger, self.config, self.avail_space_controller, self.detectors_controller, self.protected_areas, self.sms, self.email)
def initialize(): GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(PINS.SPIMOSI, GPIO.OUT) GPIO.setup(PINS.SPIMISO, GPIO.IN) GPIO.setup(PINS.SPICLK, GPIO.OUT) GPIO.setup(PINS.SPICS, GPIO.OUT)
def handleMessage(self): is_open = 0 #1일때 열려있음 is_work = 0 #습도,스타일링 둘중 하나라도 일하고 있음 / 스타일링 중/ 습도 조절중 is_catch = 0 #사람얼굴 체크하면 1 #connect sensord led_R = 20 led_Y = 21 PIR_sensor = 17 servomotor_pin = 18 GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(led_R, GPIO.OUT) GPIO.setup(led_Y, GPIO.OUT) GPIO.setup(PIR_sensor, GPIO.IN) GPIO.setup(servomotor_pin, GPIO.OUT) print("PIR Ready..") time.sleep(2) #PMW: change pulse p = GPIO.PWM(servomotor_pin, 50) sensor_args = { '11': Adafruit_DHT.DHT11, '22': Adafruit_DHT.DHT22, '2302': Adafruit_DHT.AM2302 } print(len(sys.argv)) if len(sys.argv) == 3 and sys.argv[1] in sensor_args: sensor = sensor_args[sys.argv[1]] pin = sys.argv[2] else: #ERROR occurs HERE!!! print( 'Usage: sudo ./Adafruit_DHT.py [11|22|2302] <GPIO pin number>') print( 'Example: sudo ./Adafruit_DHT.py 2302 4 - Read from an AM2302 connected to GPIO pin #4' ) sys.exit(1) humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) p.start(0) p.ChangeDutyCycle(2.5) #0 print("servo, humidity Ready..") time.sleep(2) requestObject = json.dumps(self.data) # requestString = '{'work':'ticket' || '1'}' # responseString = '{"work":"0(cam) || 2(dehumid)", "user":"******"}' requestString = literal_eval(requestObject) obj = json.loads(requestString) print(obj["work"]) msg = obj["work"] #클라이언트 메세지에서 (ticket 혹은 1) is_work[1] on/off 결정(스타일링 여부) if msg == "1": print("start sytling") is_work = 1 #작동중임,, time.sleep(10) print("styling done") is_work = 0 responseString = '{"work":"", "username":""}' else: try: while True: ##PIR sensor #Human detected && not working if GPIO.input(PIR_sensor) == 1 and is_work == 0: GPIO.output(led_Y, 1) GPIO.output(led_R, 0) # type_=1 print("detected, count start..") time.sleep(5) print("count done") if GPIO.input(PIR_sensor) == 1: is_work = 1 # 카메라 켜고 사람 인식 start cap = cv2.VideoCapture(-1) #0 or -1 counter = 1 while cap.isOpened(): ret, img = cap.read() counter += 1 if ret: cv2.imshow('camera-0', img) if (counter % 5 == 0): cv2.imwrite("./snapshot.png", img) break else: print('no camera!') break cap.release() cv2.destroyAllWindows() # load the known faces and embeddings along with OpenCV's Haar # cascade for face detection print( "[INFO] loading encodings + face detector...") data = pickle.loads( open("encodings.pickle", "rb").read()) detector = cv2.CascadeClassifier( "haarcascade_frontalface_default.xml") vs = open('shapshot.png', 'r') # grab the frame from the threaded video stream and resize it # to 500px (to speedup processing) frame = vs.read() #frame = imutils.resize(frame, width=500) # convert the input frame from (1) BGR to grayscale (for face # detection) and (2) from BGR to RGB (for face recognition) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # detect faces in the grayscale frame rects = detector.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)) # OpenCV returns bounding box coordinates in (x, y, w, h) order # but we need them in (top, right, bottom, left) order, so we # need to do a bit of reordering boxes = [(y, x + w, y + h, x) for (x, y, w, h) in rects] # compute the facial embeddings for each face bounding box encodings = face_recognition.face_encodings( rgb, boxes) names = [] # loop over the facial embeddings for encoding in encodings: # attempt to match each face in the input image to our known # encodings matches = face_recognition.compare_faces( data["encodings"], encoding) name = "Unknown" # check to see if we have found a match if True in matches: # find the indexes of all matched faces then initialize a # dictionary to count the total number of times each face # was matched matchedIdxs = [ i for (i, b) in enumerate(matches) if b ] counts = {} # loop over the matched indexes and maintain a count for # each recognized face face for i in matchedIdxs: name = data["names"][i] counts[name] = counts.get(name, 0) + 1 # determine the recognized face with the largest number # of votes (note: in the event of an unlikely tie Python # will select first entry in the dictionary) name = max(counts, key=counts.get) # update the list of names names.append(name) print(names[0]) # loop over the recognized faces for ((top, right, bottom, left), name) in zip(boxes, names): # draw the predicted face name on the image cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2) y = top - 15 if top - 15 > 15 else top + 15 cv2.putText(frame, name, (left, y), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 2) # display the image to our screen cv2.imshow("Frame", frame) # send user name responseString = '{"work":"1", "username":'******'}' else: #적외선 인식작업 재개 continue #Human not detected || working (door is opening , styling ...) else: GPIO.output(led_R, 1) GPIO.output(led_Y, 0) print("not detected !") #survo motor if is_work == 0 or is_open == 1: print('door is opened or machine not working') humidity, temperature = Adafruit_DHT.read_retry( sensor, pin) if humidity is not None and temperature is not None: print('Temp={0:0.1f}* Humidity={1:0.1f}%'. format(temperature, humidity)) humidity = math.floor(humidity) print(humidity) if humidity > 70: #door is closed but humidity is high-> we should open if is_open == 0: #open p.ChangeDutyCycle(7.5) #90 is_open = 1 time.sleep(1) is_work = 1 responseString = '{"work":"2", "username":"******"}' break #we should close else: if is_open == 1: p.ChangeDutyCycle(5.0) is_open = 0 is_work = 0 responseString = '{"work":"2", "username":"******"}' break else: print("it is working and it is closed") except KeyboardInterrupt: print("Stopped by User") p.stop() GPIO.cleanup() # type_=-1 # responseString = '{"state":"disconnected", "type":"-1", "message":""}' # responseString = '{"state":"connected", "type":'+str(type_)+ '"message":'+str(successcnt)+'}' self.sendMessage(responseString) #메시지 내용: 인식한 사람 이름 print("send message") # successcnt_dt=0 print(responseString) self.sendMessage(responseString)
#welcome to this project for Raspberry Pi. #code bellow will le you connect LEDs to your Raspberry Pi. #we assume at this stage, the INPUT will be letters and space only. #No numbers or special characters. import RPi.GPIO as GPIO import time #here are the 2 LEDs allocations for the Raspberry board: blue, red = 22, 23 #in here are all the necessary setups: GPIO.setmode(GPIO.BCM), GPIO.setwarnings(False) GPIO.setup(blue, GPIO.OUT), GPIO.setup(red, GPIO.OUT) #turning the red LED on for 0.5 seconds def redLED(): GPIO.output(red, GPIO.HIGH) time.sleep(0.5) GPIO.output(red, GPIO.LOW) time.sleep(0.30) #turning the blue LED on for 0.15 seconds def blueLED(): GPIO.output(blue, GPIO.HIGH) time.sleep(0.15) GPIO.output(blue, GPIO.LOW) time.sleep(0.30)
def setup(): GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(line_pin_right,GPIO.IN) GPIO.setup(line_pin_middle,GPIO.IN) GPIO.setup(line_pin_left,GPIO.IN)
#!/usr/bin/python import RPi.GPIO as io import time io.setmode(io.BOARD) io.setwarnings(False) pump_pin = 38 io.setup(pump_pin, io.OUT) def pump_water(time_sec): if time_sec > 10: print('No') return io.output(pump_pin, io.HIGH) time.sleep(time_sec) io.output(pump_pin, io.LOW) # ---- MAIN() ---- pump_water(3)
def map(x, in_min, in_max, out_min, out_max): maps = ((x - in_max) * (out_max - out_min) / (in_max - in_min) + out_min + 10) return maps kp = 100 servo1 = 21 servo2 = 20 deltadt = 0.1 dt1 = 4 dt2 = 7 rp.setmode(rp.BCM) rp.setwarnings(False) rp.setup(servo1, rp.OUT) rp.setup(servo2, rp.OUT) pwm1 = rp.PWM(servo1, 50) pwm2 = rp.PWM(servo2, 50) pwm1.start(4) pwm2.start(2) webcam = PiCamera() webcam.resolution = (640, 480) webcam.framerate = 90 video = PiRGBArray(webcam, size=(640, 480)) pwm2.ChangeDutyCycle(2) for i in range(2, 12, 1): #pwm1.ChangeDutyCycle(dty) pwm2.ChangeDutyCycle(i)
def init_dht(): # initialize GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.cleanup()
import bluetooth import RPi.GPIO as gpio #calling for header file which helps in using gpios of PI from functions import * # Set GPIO settings here gpio.setmode( gpio.BCM) #programming the gpio by BCM pin numbers. (like PIN40 as gpio21) gpio.setwarnings(False) # Set outputs here # Initialize outputs here def connectBluetooth(pin): server_socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM) port = 1 server_socket.bind(("", port)) server_socket.listen(1) print('Waiting for connection...') client_socket, address = server_socket.accept() print('Accepted connection from ', address) while 1: data = client_socket.recv(1024) print("Received: %s" % data) if (data == "0" ): #if '0' is sent from the Android App, turn OFF the LED print("gpio 21 LOW, LED OFF") gpio.output(pin, 0) if (data == "1" ): #if '1' is sent from the Android App, turn OFF the output
polarity1 = 0 polarity2 = 0 polarity3 = 0 upsidedown = 0 #python has capitalized booleans #robotExists = False # this is used for debugging on non-pi machines wihtout robots robotExists = True from time import sleep # Import the sleep function from the time module if robotExists: import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library GPIO.setwarnings(False) # Ignore warning for now GPIO.setmode(GPIO.BCM) # Use physical pin numbering if not robotExists: print("no robot here") if robotExists: print("there is a robot") import json enPin1 = 14 stepPin1 = 15 dirPin1 = 18 enPin2 = 25 stepPin2 = 8 dirPin2 = 7
#Step 1: A VCC mux line is selected, pulling that line high (this also pulls the same line on the data muxes high) #Step 2: A GND mux line is selected, pulling that line low #Step 3: An ADC read is triggered #Step 4: The GND mux line selection is incremented by one, loop to step 3 #Step 5: Once all 40 GND mux lines have been gone through increment VCC select line by one, loop to step 3 #Notes: Since we are using 3 muxes to select the 40 inputs/outputs things get a little weird #After 16 increments we switch the pins we are using, then after 16 more we switch again but only increment 8 #If we have enough pins we want to keep the other two inactive vcc muxes disable while we are reading from the other #The multiplexers need about max 60 nanoseconds to change their states. With a super optimized program written in C #or assembly on a microcontroller this may be something to consider. For our uses (especially w/ Python) our code will #execute plenty slow to allow the multiplexers the time they need #GPIO Setup: Setting all 20 mux control pins to outputs GPIO.setwarnings(False) #Mutes irrelevant warnings GPIO.setmode(GPIO.BOARD) #Pin numbering in hardware mode #VCC MUXES GPIO.setup(S01, GPIO.OUT) GPIO.setup(S11, GPIO.OUT) GPIO.setup(S21, GPIO.OUT) GPIO.setup(S31, GPIO.OUT) GPIO.setup(S02, GPIO.OUT) GPIO.setup(S12, GPIO.OUT) GPIO.setup(S22, GPIO.OUT) GPIO.setup(S32, GPIO.OUT) GPIO.setup(S03, GPIO.OUT) GPIO.setup(S13, GPIO.OUT) GPIO.setup(S23, GPIO.OUT) #GND MUXES
def init(): GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(PIN, GPIO.OUT)
curgen = 0 # Current random gen num roundn = 1 # Round number wins = 0 # Win count losses = 0 # Lose count wlmode = 2 # Win/Loss indicator mode. # Setting for how to indicate # the win/loss of a round. # - Value=1: Classic flashing of # all the 4-color LEDs. # - Value=2: Usage of 2 additional # dedicated red/green # win/loss LEDs, set by # winpin and losepin. GPIO.setmode(GPIO.BCM) # cobbler numbers are bcm GPIO.setwarnings(False) # Silence channel-in-use warnings for led in leds: # Init LED modes GPIO.setup(led, GPIO.OUT) for btn in btns: # Init button modes GPIO.setup(btn, GPIO.IN) GPIO.setup(ipin, GPIO.OUT) # Init indicator LED GPIO.setup(dpin, GPIO.IN) # Init 'done' button if wlmode == 2: GPIO.setup(winpin, GPIO.OUT) GPIO.setup(losepin, GPIO.OUT) def ledwipe(): for led in leds: GPIO.output(led, False)
def __init__(self, canal=22): self._canal = canal GPIO.setmode(GPIO.BCM) GPIO.setup(self._canal, GPIO.IN) GPIO.setwarnings(False) GPIO.add_event_detect(self._canal, GPIO.RISING)
def lights_on(): GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(19, GPIO.OUT) GPIO.output(19, GPIO.HIGH) return '<a href="./PHP/13on.php"><input type="button" class="MyButton" value="Relay 13"></a>'
def handle(msg): sensor = 7 GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(18, GPIO.OUT) GPIO.setup(23, GPIO.OUT) GPIO.setup(sensor, GPIO.IN) chat_id = msg['chat']['id'] str_UserID = str(chat_id) command = msg['text'].lower() print 'Comando Recebido: %s' % command logging.info("Usuario ID:{1} enviou comando {0}".format(command, str_UserID)) def movimento(msg): bot.sendMessage(chat_id, text="Movimento Detectado") time.sleep(3) camera.start_preview() camera.capture('movimento.jpg') bot.sendPhoto(chat_id, photo=open('movimento.jpg', 'rb')) time.sleep(20) try: GPIO.add_event_detect(7, GPIO.RISING, movimento) except: GPIO.cleanup() try: if command == '/start' or command == '/start@' + MyBotName.lower(): mensagem = "Ola usuario ID: {1}, eu sou o {0} do Telegram. ".format(MyBotName, str_UserID) mensagem = mensagem + "Vc pode me controlar usando os seguintes " \ "comandos:\n\n" \ "/tirar_foto Tira a foto e envia \n" \ "/time Retorna a hora atual \n" \ "/ligar_led Liga o led vermelho \n " \ bot.sendMessage(chat_id, mensagem) elif command == '/tirar_foto': camera.start_preview() camera.capture('tirar_foto.jpg') bot.sendPhoto(chat_id, photo=open('tirar_foto.jpg', 'rb')) mensagem = 'Imagem capiturado com sucesso na data :' bot.sendMessage(chat_id, mensagem + str(datetime.datetime.now())) time.sleep(2) GPIO.cleanup(sensor, 7) elif command == '/roll': bot.sendMessage(chat_id, random.randint(1,6)) elif command == '/time': bot.sendMessage(chat_id, str(datetime.datetime.now())) elif command == '/ligar_led1': if not GPIO.input(18): GPIO.output(18, 1) mensagem = 'Led ligado' bot.sendMessage(chat_id, mensagem) #led_status = True elif command == '/desligar_led1': GPIO.output(18, 0) mensagem = 'Led Desligado' bot.sendMessage(chat_id, mensagem) #led_status = False GPIO.cleanup(18) elif command == '/ligar_led0': GPIO.output(23, 1) mensagem = 'Led ligado' bot.sendMessage(chat_id, mensagem) #led_status = True elif command == '/desligar_led0': GPIO.output(23, 0) mensagem = 'Led Desligado' bot.sendMessage(chat_id, mensagem) #led_status = False GPIO.cleanup(23) else: mensagem = "Nao reconheco o comando {0}. Envie o comando /start para solicitar ajuda...".format(command) bot.sendMessage(chat_id, mensagem) finally: pass
import RPi.GPIO as GPIO # import com.farhat.dht11 as dht11 # import dht11 from import dht11 import time import datetime import psycopg2 # initialize GPIO GPIO.setwarnings(True) GPIO.setmode(GPIO.BCM) # read data using pin 14 instance = dht11.DHT11(pin=17) connection = psycopg2.connect(user="******", password="******", host="127.0.0.1", port="5432", database="pi") try: while True: result = instance.read() if result.is_valid(): cursor = connection.cursor() postgres_insert_query = """ INSERT INTO SENSORPINGS (read_on, tempreature, humidity) VALUES (%s,%s,%s)""" record_to_insert = (datetime.datetime.now(), result.temperature, result.humidity) cursor.execute(postgres_insert_query, record_to_insert)
def setup(): GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False)
class SDL_Pi_WeatherRack: GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) # instance variables _currentWindCount = 0 _currentRainCount = 0 _shortestWindTime = 0 _pinAnem = 0 _pinRain = 0 _intAnem = 0 _intRain = 0 _ADChannel = 0 _ADMode = 0 _currentRainCount = 0 _currentWindCount = 0 _currentWindSpeed = 0.0 _currentWindDirection = 0.0 _lastWindTime = 0 _shortestWindTime = 0 _sampleTime = 5.0 _selectedMode = SDL_MODE_SAMPLE _startSampleTime = 0 _currentRainMin = 0 _lastRainTime = 0 _ads1015 = 0 def __init__(self, pinAnem, pinRain, intAnem, intRain, ADMode): GPIO.setup(pinAnem, GPIO.IN) GPIO.setup(pinRain, GPIO.IN) # when a falling edge is detected on port pinAnem, regardless of whatever # else is happening in the program, the function callback will be run GPIO.add_event_detect(pinAnem, GPIO.RISING, callback=self.serviceInterruptAnem) GPIO.add_event_detect(pinRain, GPIO.RISING, callback=self.serviceInterruptRain) ADS1015 = 0x00 # 12-bit ADC ADS1115 = 0x01 # 16-bit ADC # Select the gain self.gain = 6144 # +/- 6.144V #self.gain = 4096 # +/- 4.096V # Select the sample rate self.sps = 250 # 250 samples per second # Initialise the ADC using the default mode (use default I2C address) # Set this to ADS1015 or ADS1115 depending on the ADC you are using! self.ads1015 = ADS1x15(ic=ADS1015, address=0x48) # determine if device present try: value = self.ads1015.readRaw( 1, self.gain, self.sps) # AIN1 wired to wind vane on WeatherPiArduino time_.sleep(1.0) value = self.ads1015.readRaw( 1, self.gain, self.sps) # AIN1 wired to wind vane on WeatherPiArduino # now figure out if it is an ADS1015 or ADS1115 if ((0x0F & value) == 0): config.ADS1015_Present = True config.ADS1115_Present = False # check again (1 out 16 chance of zero) value = self.ads1015.readRaw( 0, self.gain, self.sps) # AIN1 wired to wind vane on WeatherPiArduino if ((0x0F & value) == 0): config.ADS1015_Present = True config.ADS1115_Present = False else: config.ADS1015_Present = False config.ADS1115_Present = True self.ads1015 = ADS1x15(ic=ADS1115, address=0x48) else: config.ADS1015_Present = False config.ADS1115_Present = True self.ads1015 = ADS1x15(ic=ADS1115, address=0x48) except TypeError as e: print "Type Error" config.ADS1015_Present = False config.ADS1115_Present = False SDL_Pi_WeatherRack._ADMode = ADMode # Wind Direction Routines def current_wind_direction(self): if (SDL_Pi_WeatherRack._ADMode == SDL_MODE_I2C_ADS1015): value = self.ads1015.readADCSingleEnded( 1, self.gain, self.sps) # AIN1 wired to wind vane on WeatherPiArduino voltageValue = value / 1000 else: # user internal A/D converter voltageValue = 0.0 direction = voltageToDegrees(voltageValue, SDL_Pi_WeatherRack._currentWindDirection) return direction def current_wind_direction_voltage(self): if (SDL_Pi_WeatherRack._ADMode == SDL_MODE_I2C_ADS1015): value = self.ads1015.readADCSingleEnded( 1, self.gain, self.sps) # AIN1 wired to wind vane on WeatherPiArduino voltageValue = value / 1000 else: # user internal A/D converter voltageValue = 0.0 return voltageValue # Utility methods def reset_rain_total(self): SDL_Pi_WeatherRack._currentRainCount = 0 def accessInternalCurrentWindDirection(self): return SDL_Pi_WeatherRack._currentWindDirection def reset_wind_gust(self): SDL_Pi_WeatherRack._shortestWindTime = 0xffffffff def startWindSample(self, sampleTime): SDL_Pi_WeatherRack._startSampleTime = micros() SDL_Pi_WeatherRack._sampleTime = sampleTime # get current wind def get_current_wind_speed_when_sampling(self): compareValue = SDL_Pi_WeatherRack._sampleTime * 1000000 if (micros() - SDL_Pi_WeatherRack._startSampleTime >= compareValue): # sample time exceeded, calculate currentWindSpeed timeSpan = (micros() - SDL_Pi_WeatherRack._startSampleTime) SDL_Pi_WeatherRack._currentWindSpeed = ( float(SDL_Pi_WeatherRack._currentWindCount) / float(timeSpan)) * WIND_FACTOR * 1000000.0 #print "SDL_CWS = %f, SDL_Pi_WeatherRack._shortestWindTime = %i, CWCount=%i TPS=%f" % (SDL_Pi_WeatherRack._currentWindSpeed,SDL_Pi_WeatherRack._shortestWindTime, SDL_Pi_WeatherRack._currentWindCount, float(SDL_Pi_WeatherRack._currentWindCount)/float(SDL_Pi_WeatherRack._sampleTime)) SDL_Pi_WeatherRack._currentWindCount = 0 SDL_Pi_WeatherRack._startSampleTime = micros() #print "SDL_Pi_WeatherRack._currentWindSpeed=", SDL_Pi_WeatherRack._currentWindSpeed return SDL_Pi_WeatherRack._currentWindSpeed def setWindMode(self, selectedMode, sampleTime): # time in seconds SDL_Pi_WeatherRack._sampleTime = sampleTime SDL_Pi_WeatherRack._selectedMode = selectedMode if (SDL_Pi_WeatherRack._selectedMode == SDL_MODE_SAMPLE): self.startWindSample(SDL_Pi_WeatherRack._sampleTime) #def get current values def get_current_rain_total(self): rain_amount = 0.2794 * float(SDL_Pi_WeatherRack._currentRainCount) SDL_Pi_WeatherRack._currentRainCount = 0 return rain_amount def current_wind_speed(self): # in milliseconds if (SDL_Pi_WeatherRack._selectedMode == SDL_MODE_SAMPLE): SDL_Pi_WeatherRack._currentWindSpeed = self.get_current_wind_speed_when_sampling( ) else: # km/h * 1000 msec SDL_Pi_WeatherRack._currentWindCount = 0 delay(SDL_Pi_WeatherRack._sampleTime * 1000) SDL_Pi_WeatherRack._currentWindSpeed = ( float(SDL_Pi_WeatherRack._currentWindCount) / float(SDL_Pi_WeatherRack._sampleTime)) * WIND_FACTOR return SDL_Pi_WeatherRack._currentWindSpeed def get_wind_gust(self): latestTime = SDL_Pi_WeatherRack._shortestWindTime SDL_Pi_WeatherRack._shortestWindTime = 0xffffffff time = latestTime / 1000000.0 # in microseconds if (time == 0): return 0 else: return (1.0 / float(time)) * WIND_FACTOR # Interrupt Routines def serviceInterruptAnem(self, channel): #print "Anem Interrupt Service Routine" currentTime = (micros() - SDL_Pi_WeatherRack._lastWindTime) SDL_Pi_WeatherRack._lastWindTime = micros() if (currentTime > 1000): # debounce SDL_Pi_WeatherRack._currentWindCount = SDL_Pi_WeatherRack._currentWindCount + 1 if (currentTime < SDL_Pi_WeatherRack._shortestWindTime): SDL_Pi_WeatherRack._shortestWindTime = currentTime def serviceInterruptRain(self, channel): #print "Rain Interrupt Service Routine" currentTime = (micros() - SDL_Pi_WeatherRack._lastRainTime) SDL_Pi_WeatherRack._lastRainTime = micros() if (currentTime > 500): # debounce SDL_Pi_WeatherRack._currentRainCount = SDL_Pi_WeatherRack._currentRainCount + 1 if (currentTime < SDL_Pi_WeatherRack._currentRainMin): SDL_Pi_WeatherRack._currentRainMin = currentTime
#!/usr/bin/env python3 #Programa que mide la humedad del suelo y activa o desactiva el riego en función de la misma. #Librerías. from gpiozero import DigitalInputDevice import RPi.GPIO as GPIO import time #Métodos GPIO.setmode(GPIO.BCM) #Nos referimos a los pines por su número de Broadcomm SOC Channel. GPIO.setwarnings(False) #Método para ocultar avisos. #Relé conectado al GPIO27. GPIO.setup(27, GPIO.OUT) GPIO.output(27, GPIO.HIGH) #Higrómetro conectado al GPIO17. d0_input = DigitalInputDevice(17) #Función principal. while True: if (not d0_input.value): GPIO.output(27, GPIO.LOW) #Relé apagado, se desactiva el riego. print("Riego desactivado") time.sleep(2) else: GPIO.output(27, GPIO.HIGH) #Relé encendido, se activa el riego. print("Riego activado") time.sleep(2)
import RPi.GPIO as GPIO # using Rpi.GPIO module from time import sleep # import function sleep for delay GPIO.setmode(GPIO.BCM) # GPIO numbering GPIO.setwarnings(False) # enable warning from GPIO AN2 = 12 # set pwm2 pin on MD10-Hat DIG2 = 26 # set dir2 pin on MD10-Hat GPIO.setup(AN2, GPIO.OUT) # set pin as output GPIO.setup(DIG2, GPIO.OUT) # set pin as output sleep(1) # delay for 1 seconds p2 = GPIO.PWM(DIG2, 100) # set pwm for M2 speed = int(input()) if (speed > 50) : try: while True: print "STOP" # display "Forward" when programe run GPIO.output(AN2, GPIO.LOW) # set AN2 as HIGH, M2B will turn ON p2.start(0) # set Direction for M2 sleep(1) #delay for 2 second print "GO" GPIO.output(AN2, GPIO.HIGH) # set AN2 as HIGH, M2B will STOP p2.start(speed) sleep(1) #delay for 3 second GPIO.output(AN2, GPIO.HIGH) # set AN2 as HIGH, M2B will STOP p2.start(speed)
def init(): GPIO.setwarnings(False) GPIO.setup(pin_4, GPIO.OUT) GPIO.setup(pin_17, GPIO.OUT) GPIO.setup(pin_23, GPIO.OUT) GPIO.setup(pin_24, GPIO.OUT)
def __init__(self): GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT) self.p = GPIO.PWM(7,50) self.p.start(7.5)
def initialize(self): GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(self.pin, GPIO.OUT) GPIO.output(self.pin, GPIO.LOW)
import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library from time import sleep GPIO.setwarnings(False) # disable the warning sign GPIO.setmode(GPIO.BCM) # select the board type BCM GPIO.setup(15,GPIO.OUT) # set the pin mode for i in range (5): GPIO.output(15, GPIO.HIGH) sleep(1) # takes seconds as argument GPIO.output(15, GPIO.LOW) sleep(1) print(i)
minCa = caMi maxCa = caMa maxMap = mapMa minMap = mapMi kclMax = kclMa kclMin = kclMi pygame.init() windowSurface = pygame.display.set_mode((800, 480)) myfont2 = pygame.font.SysFont("cambria", 50) myfont = pygame.font.SysFont("cambria", 100) # GPIO.setwarnings(False) # No warning for GPIO already in use GPIO.setmode(GPIO.BCM) buzzer = 23 # buzzer connected to pin 23 GPIO.setup(buzzer, GPIO.OUT) gpgga_info = "$GPGGA," ser = serial.Serial("/dev/ttyS0") # Open port with baud rate GPGGA_buffer = 0 NMEA_buff = 0 # lat_in_degrees = 0 long_in_degrees = 0 # piln = myfont2.render('Pilnekr.', 1, (255, 255, 255))
import RPi.GPIO as GPIO import fileinput from time import sleep import time import datetime #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; #GPIO Settings GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(26, GPIO.OUT) #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; #Main Code while True: ##START BIT GPIO.output(26, 0) sleep(0.009) GPIO.output(26, 1) sleep(0.0045) ##ADDRESS address = "0000000011111111" for digit in address: GPIO.output(26, 0) sleep(0.00056) GPIO.output(26, 1) if int(digit): sleep(0.00169) else: sleep(0.00056)
def setup(): """Setup GPIO for I/O This must be called before calling the other functions.""" GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False)
def init(): GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD)
import RPi.GPIO as ir print "PIN 3 High" ir.setwarnings(False) ir.setmode(ir.BOARD) ir.setup(3, ir.OUT) ir.output(3, ir.HIGH)
def setupPin(): GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) if LOGGING: log.debug("Set GPIO %d as input" % gpioPin) GPIO.setup(gpioPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
def setupGPIO(pins): GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) for pin in pins: GPIO.setup(pin,GPIO.OUT) print ("setup Completed")