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(): 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 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 led_setup(): io.setmode(io.BOARD) for val in LED: io.setup(val, io.OUT) for val in RGB: io.setup(RGB[val], io.OUT)
def distance(measure): gpio.setmode(gpio.BOARD) gpio.setup(TRIG, gpio.OUT) gpio.setup(ECHO, gpio.IN) gpio.output(TRIG, False) gpio.output(TRIG, True) time.sleep(0.00001) gpio.output(TRIG, False) sig = 0 nosig = 0 while gpio.input(ECHO) == 0: nosig = time.time() while gpio.input(ECHO) == 1: sig = time.time() if nosig != None and sig != None: tl = sig - nosig distance = tl * 17150 distance = round(distance, 2) gpio.cleanup() return distance
def main(): GPIO.cleanup() GPIO.setmode(GPIO.BCM) GPIO.setup(DISPLAY_E, GPIO.OUT) GPIO.setup(DISPLAY_RS, GPIO.OUT) GPIO.setup(DISPLAY_DATA4, GPIO.OUT) GPIO.setup(DISPLAY_DATA5, GPIO.OUT) GPIO.setup(DISPLAY_DATA6, GPIO.OUT) GPIO.setup(DISPLAY_DATA7, GPIO.OUT) GPIO.setup(DISPLAY_E2, GPIO.OUT) display_init(DISPLAY_E) display_init(DISPLAY_E2) lcd_byte(DISPLAY_LINE_1, DISPLAY_CMD,DISPLAY_E) lcd_string("Schnatterente",DISPLAY_E) lcd_byte(DISPLAY_LINE_2, DISPLAY_CMD,DISPLAY_E) lcd_string("Nak nak nak!",DISPLAY_E) lcd_byte(DISPLAY_LINE_1, DISPLAY_CMD,DISPLAY_E2) lcd_string("Dein Display",DISPLAY_E2) lcd_byte(DISPLAY_LINE_2, DISPLAY_CMD,DISPLAY_E2) lcd_string("funktioniert! :)",DISPLAY_E2) time.sleep(25) GPIO.cleanup()
def main(): #Set up pins for GPIO output GPIO.setmode(GPIO.BCM) #Use BCM GPIO numbers GPIO.setup(LCD_E,GPIO.OUT) GPIO.setup(LCD_RS,GPIO.OUT) GPIO.setup(LCD_D4,GPIO.OUT) GPIO.setup(LCD_D5,GPIO.OUT) GPIO.setup(LCD_D6,GPIO.OUT) GPIO.setup(LCD_D7,GPIO.OUT) #Set up buttons for GPIO input GPIO.setup(BTN1, GPIO.IN) GPIO.setup(BTN2, GPIO.IN) #Initialize LCD Display lcd_init() #Display introductory message to_write = [LCD_FILLER, str_format_left("Raspberry Pi"), str_format_left("GPIO Test"), LCD_FILLER] lcd_write_lines(to_write) time.sleep(5) #run infinite loop that displays different messages for different button presses while True: if (GPIO.input(BTN1) == True): to_write = [LCD_FILLER, str_format_left("You hit"), str_format_left("Button 1"), LCD_FILLER] lcd_write_lines(to_write) time.sleep(1) if (GPIO.input(BTN2) == True): to_write = [LCD_FILLER, str_format_left("You hit"), str_format_left("Button 2"), LCD_FILLER] lcd_write_lines(to_write) time.sleep(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 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 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 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 main(): GPIO.cleanup() GPIO.setmode(GPIO.BCM) #Relais als Ausgang schalten GPIO.setup(RELAIS, GPIO.OUT) #Eimersensor als Eingang schalten GPIO.setup(SENSOR_BUCKET_PIN,GPIO.IN) #Datenbank initialisieren db = DATABASE() # Aktuelle Luftfeuchtigkeit holen humidity = db.getLatestHumidity() # Checken ob Wasser im Eimer ist if isBucketEmpty(): db.saveBucketEmpty() else: db.saveStatus("OK") # Giessen wenn Luftfeuchtigkeit unter 90 % if humidity < HUMIDITY_LIMIT: db.saveWatering(WATERING_TIME) GPIO.output(RELAIS, GPIO.HIGH) time.sleep(WATERING_TIME) GPIO.output(RELAIS, GPIO.LOW) else: GPIO.output(RELAIS, GPIO.LOW)
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 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 init_RF12() : GPIO.setmode(GPIO.BOARD) GPIO.setup(18, GPIO.IN, pull_up_down = GPIO.PUD_UP) GPIO.setup(22, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) writeCmd(0x0000) # initial SPI transfer added to avoid power-up problem time.sleep (5) # Give RFM12B time to boot up writeCmd(0x0000) writeCmd(0x80E7) #CREG 1 EL (ena TX), EF (ena RX FIFO), 12.0pF writeCmd(0x82D9) #er,!ebb,ET,ES,EX,!eb,!ew,DC // receive writeCmd(0xA640) #CREG 3 96-3960 freq range of values within band writeCmd(0xC647) #CREG 4 approx 49.2 Kbps, i.e. 10000/29/(1+6) Kbps writeCmd(0x94A0) #CREG 5 VDI,FAST,BW=134kHz,0dBm,-91dBm writeCmd(0xC2AC) #CREG 6 AL,!ml,DIG,DQD4 writeCmd(0xCA83) #CREG 7 0x83 FIFO8,2-SYNC,!ff,!DR writeCmd(0xCED4) #SYNC=2DXX writeCmd(0xC483) #CREG 9 @PWR,NO RSTRIC,!st,!fi,OE,EN writeCmd(0x9850) #C!mp,90kHz,MAX OUT writeCmd(0xCC17) #CPLL Setting Command writeCmd(0xE000) #CREG 12 Wake-Up Timer Command. Disabled writeCmd(0xC800) #CREG 13 Low Duty-Cycle Command. Disabled writeCmd(0xC040) #CREG 14 1.66MHz,3.1V fifoReset()
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 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 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 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 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 BuildGPIOList(): # Build a list of zones and store in memory global GPIOList global numgpio global AlarmActioned AlarmActioned = [] numgpio=0 RecordSet = GetDataFromHost(2,[0]) if RecordSet==False: return numgpio = len(RecordSet) GPIOList = [] for i in range(numgpio): if isNumber(RecordSet[i][0]): GPIOList.append(RecordSet[i][0]) numgpio = len(GPIOList) # Initialize the Raspberry Pi board pin numbers to the armed zones GPIO.setmode(GPIO.BOARD) if globals.ArmDisarm == True: GPIO.setup(globals.ArmPin, GPIO.IN) #Arm pin setup GPIO.setup(globals.DisarmPin, GPIO.IN) #Disarm pin setup for i in range(0,numgpio,1): GPIO.setup(GPIOList[i], GPIO.IN) circuit = GPIO.input(GPIOList[i]) AlarmActioned.append(circuit)
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 __init__(self, input_pin, reverse_logic, ding, dong, ha_informer): """ Create a doorbell that listens on input_pin and plays a 'ding' sound when it's pressed and a 'dong' sound when it's released. """ threading.Thread.__init__(self) self.daemon = True self.running = True self.inpin = input_pin self.reverse_logic = reverse_logic self.ding = ding self.dong = dong self.ding.start() self.dong.start() self.ha_informer = ha_informer self.ha_informer.start() if self.reverse_logic: self.ding_edge = GPIO.FALLING self.dong_edge = GPIO.RISING else: self.ding_edge = GPIO.RISING self.dong_edge = GPIO.FALLING GPIO.setmode(GPIO.BCM) GPIO.setup(self.inpin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) self.logging = logging.getLogger(self.__class__.__name__)
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 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 __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 __init__(self): self._gpio_map = {"PWM2":37, "DIR_CLK":38, "PWM3":35, "PWM4":36, "DIR_EN":33, "DIR_UP":31, "PWM1":32, "DIR_LATCH":29} self._pwm_map = [] GPIO.cleanup() GPIO.setmode(GPIO.BOARD) # set GPIO OUT mode for i in iter(self._gpio_map): GPIO.setup(self._gpio_map[i], GPIO.OUT) # set PWM #GPIO.output(self._gpio_map["PWM1"], GPIO.HIGH) #GPIO.output(self._gpio_map["PWM2"], GPIO.HIGH) #GPIO.output(self._gpio_map["PWM3"], GPIO.HIGH) #GPIO.output(self._gpio_map["PWM4"], GPIO.HIGH) # set PWM p1 = GPIO.PWM(self._gpio_map["PWM1"], 255) p2 = GPIO.PWM(self._gpio_map["PWM2"], 255) p3 = GPIO.PWM(self._gpio_map["PWM3"], 255) p4 = GPIO.PWM(self._gpio_map["PWM4"], 255) self._pwm_map = [p1, p2, p3, p4] for i in self._pwm_map: i.start(100)
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 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)
import RPi.GPIO as gpio import time gpio.setmode(gpio.BOARD) gpio.setup(7, gpio.OUT) gpio.output(7, True) time.sleep(1) gpio.output(7, False)
#!/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)
class Led: def __init__(self, pin): self.pin = pin GPIO.setup(self.pin, GPIO.OUT) def on(self, duration=0): GPIO.output(self.pin, GPIO.HIGH) if duration > 0: t = Timer(duration, self.off) t.start() def off(self): GPIO.output(self.pin, GPIO.LOW) """ from time import sleep GPIO.setmode(GPIO.BCM) red = Led(19) green = Led(17) blue = Led(27) yellow = Led(22) red.on(0.25) sleep(1) green.on(0.25) sleep(1) blue.on(0.25) sleep(1) yellow.on()
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(13, GPIO.OUT) pin1 = GPIO.PWM(13, 50) x = 2 dc = x/ (20 + x) print x pin1.start(dc) raw_input("Press Enter") while False: dc = x/ (20 + x) print x pin1.start(dc) # raw_input("Press Enter") x -= 0.01 time.sleep(0.1) pin1.stop() GPIO.cleanup()
import RPi.GPIO as GPIO import time from socketIO_client import SocketIO, LoggingNamespace GPIO.setmode(GPIO.BOARD) # Set board mode to BROAD GPIO.setup(16,GPIO.IN,pull_up_down=GPIO.PUD_UP) GPIO.setup(18,GPIO.IN,pull_up_down=GPIO.PUD_UP) GPIO.setup(22,GPIO.IN,pull_up_down=GPIO.PUD_UP) GPIO.setup(11,GPIO.OUT) GPIO.setup(13,GPIO.OUT) GPIO.setup(15,GPIO.OUT) print("Program Started") while True: button_state=GPIO.input(16) button_state2=GPIO.input(18) button_state3=GPIO.input(22) if button_state == False: print("Button Pressed") GPIO.output(11,True) #socketIO.send("Alert: Panic Button in Gym") #socketIO.wait(seconds=1) #time.sleep(0.2) GPIO.output(11,False) elif button_state2 == False: print("Button 2 Pressed") GPIO.output(13,True) #socketIO.send("Alert: Emergency Assistance Needed in Gym") #socketIO.wait(seconds=1)
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
import RPi.GPIO as GPIO import time # set the deault board numbering# BCM ---- GPIO5, GPIO6 like this GPIO.setmode(GPIO.BOARD) ''' GPIO5 and GPIO6 ---- Pertrol i,e pin 29 and 31 GPIO13 and GPIO19 used for diesal i,e pin33 and 35 ''' channel_list = (29, 31, 33, 35) def RESET_ALL_PINS_LOW(): global channel_list GPIO.output(channel_list, GPIO.LOW) # setup these pins as output GPIO.setup(29, GPIO.OUT) GPIO.setup(31, GPIO.OUT) GPIO.setup(33, GPIO.OUT) GPIO.setup(35, GPIO.OUT) def fill_petrol(amount, petrol_price): global channel_list
from flask import Flask, render_template_string, request # Importing the Flask modules required for this project import RPi.GPIO as GPIO # Importing the GPIO library to control GPIO pins of Raspberry Pi from time import sleep # Import sleep module from time library to add delays # Pins where we have connected servos servo_pin = 26 servo_pin1 = 19 GPIO.setmode(GPIO.BCM) # We are using the BCM pin numbering # Declaring Servo Pins as output pins GPIO.setup(servo_pin, GPIO.OUT) GPIO.setup(servo_pin1, GPIO.OUT) # Created PWM channels at 50Hz frequency p = GPIO.PWM(servo_pin, 50) p1 = GPIO.PWM(servo_pin1, 50) # Initial duty cycle p.start(0) p1.start(0) # Flask constructor takes the name of current module (__name__) as argument. app = Flask(__name__) # Enable debug mode app.config['DEBUG'] = True # Store HTML code TPL = ''' <html> <head><title>Web Application to control Servos </title></head> <body>
import RPi.GPIO as GPIO # Allows us to call our GPIO pins and names it just GPIO import time GPIO.setmode(GPIO.BOARD) # Set's GPIO pins to BCM GPIO numbering # to bu used : Ground 06 / GPIO012 INPUT_PIN = 32 # Sets our input pin, in this example I'm connecting our button to pin 12. Pin 0 is the SDA pin so I avoid using it for sensors/buttons GPIO.setup(INPUT_PIN, GPIO.IN) # Set our input pin to be an input # Create a function to run when the input is high # GPIO.add_event_detect(INPUT_PIN, GPIO.FALLING, callback=inputLow, bouncetime=200) # Wait for the input to go low, run the function when it does n=0 while (1): if (GPIO.input(INPUT_PIN) == True): # Physically read the pin now n = 0 else: n = n + 1 time.sleep(0.5) print(n)
# Motor A, Left Side GPIO CONSTANTS PWM_FORWARD_LEFT_PIN = 18 # IN1 - Forward Drive PWM_REVERSE_LEFT_PIN = 23 # IN2 - Reverse Drive # Motor B, Right Side GPIO CONSTANTS PWM_FORWARD_RIGHT_PIN = 24 # IN3 - Forward Drive PWM_REVERSE_RIGHT_PIN = 25 # IN4 - Reverse Drive # Initializing the motor pins and the speed speed = 0.4 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) # Initializing the ultrasonic sensor gpio.setmode(gpio.BCM) trigger = 20 echo = 21 gpio.setup(trigger, gpio.OUT) gpio.setup(echo, gpio.IN) def stop(): forwardLeft.value = 0 reverseLeft.value = 0 forwardRight.value = 0 reverseRight.value = 0 def forward(speed): forwardLeft.value = speed reverseLeft.value = 0 forwardRight.value = speed
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)
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(): global pwmMotorFRSpeed, pwmMotorFLSpeed, pwmMotorBRSpeed, pwmMotorBLSpeed, Stop # How many times to turn the pin on and off each second print 'Set Frequency' Frequency = 20 # How long the pin stays on each cycle, as a percent (here, it's 50%) - AKA Speed print 'Set DutyCycle' DutyCycle = 50 # Settng the duty cycle to 0 means the motors will not turn print 'Set Stop' Stop = 0 # Set the GPIO modes print 'Set the GPIO mode' # Use physical pin numbering GPIO.setmode(GPIO.BOARD) # Turn GPIO Warnings off # GPIO.setwarnings(False) # Use PWM on motor outputs so motors can be controlled # Setup Motor FR print '\nSet the GPIO Pin mode to be Output - Motor FR' GPIO.setup(pinMotorFRSpeed, GPIO.OUT) GPIO.setup(pinMotorFRForwards, GPIO.OUT) GPIO.setup(pinMotorFRBackwards, GPIO.OUT) print 'Set the GPIO to software PWM at ' + str(Frequency) + ' Hertz - Motor FR' pwmMotorFRSpeed = GPIO.PWM(pinMotorFRSpeed, Frequency) print 'Start the software PWM with a duty cycle of 0 (i.e. not moving) - Moter FR' pwmMotorFRSpeed.start(Stop) # Setup Motor FL print '\nSet the GPIO Pin mode to be Output - Motor FL' GPIO.setup(pinMotorFLSpeed, GPIO.OUT) GPIO.setup(pinMotorFLForwards, GPIO.OUT) GPIO.setup(pinMotorFLBackwards, GPIO.OUT) print 'Set the GPIO to software PWM at ' + str(Frequency) + ' Hertz - Motor FL' pwmMotorFLSpeed = GPIO.PWM(pinMotorFLSpeed, Frequency) print 'Start the software PWM with a duty cycle of 0 (i.e. not moving) - Moter FL' pwmMotorFLSpeed.start(Stop) # Setup Motor BR print '\nSet the GPIO Pin mode to be Output - Motor BR' GPIO.setup(pinMotorBRSpeed, GPIO.OUT) GPIO.setup(pinMotorBRForwards, GPIO.OUT) GPIO.setup(pinMotorBRBackwards, GPIO.OUT) print 'Set the GPIO to software PWM at ' + str(Frequency) + ' Hertz - Motor BR' pwmMotorBRSpeed = GPIO.PWM(pinMotorBRSpeed, Frequency) print 'Start the software PWM with a duty cycle of 0 (i.e. not moving) - Motor BR' pwmMotorBRSpeed.start(Stop) # Setup Motor BL print '\nSet the GPIO Pin mode to be Output - Motor BL' GPIO.setup(pinMotorBLSpeed, GPIO.OUT) GPIO.setup(pinMotorBLForwards, GPIO.OUT) GPIO.setup(pinMotorBLBackwards, GPIO.OUT) print 'Set the GPIO to software PWM at ' + str(Frequency) + ' Hertz - Motor BL' pwmMotorBLSpeed = GPIO.PWM(pinMotorBLSpeed, Frequency) print 'Start the software PWM with a duty cycle of 0 (i.e. not moving) - Motor BL\n' pwmMotorBLSpeed.start(Stop)
def initialize(self): GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(self.pin, GPIO.OUT) GPIO.output(self.pin, GPIO.LOW)
def setup(): GPIO.setmode(GPIO.BOARD) GPIO.setup(TrackingPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def __init__(self): self.trig = 38 # sends the signal self.echo = 40 # listens for the signal GPIO.setmode(GPIO.BOARD) GPIO.setup(self.echo, GPIO.IN) GPIO.setup(self.trig, GPIO.OUT)
def setup(): GPIO.setmode(GPIO.BOARD)
# ** python script to run in the background to watch GPIO ***** # ** pin for a falling edge and shutdown pi when falling edge ***** # ***************************************************************** import os import sys import RPi.GPIO as GPIO from time import sleep # ********* constants ********************** # these constants can also be updated from a config file if desired to pass values to the program AUTOSHUTDOWN = 1 # used for implementing a config file SWITCHGPIO = 8 # GPIO pin to watch # ****************************************** GPIO.setmode(GPIO.BCM) # use broadcom pin numbering GPIO.setwarnings(False) GPIO.setup(SWITCHGPIO, GPIO.IN, pull_up_down=GPIO.PUD_UP) def switchCallback(channel): global AUTOSHUTDOWN if AUTOSHUTDOWN == 1: os.system('/sbin/shutdown -h now') sys.exit(0) def main(): global SWITCHGPIO GPIO.add_event_detect(SWITCHGPIO, GPIO.FALLING, callback=switchCallback)
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)
resetPin = 16; # The program is made for recording and writing a sample with a few minutes between each sample. # It is not well suited for sampling with few seconds intervals becuse of the time the program uses. # It is however possible to do it for testing purposes. # The timing of sampletimes is a bit dogy and may result in shifting of samples (e.g. start at 12.00 # with and interval of 5min and ending up with a sample at 13.11 then 13.16 etc.) even though this # problem should be resolved by line 72. sampleIntervalH = 0; # Sampe interval hours sampleIntervalM = 5; # Sampe interval minutes sampleIntervalS = 0; # Sampe interval seconds failCount = 0; # Keeps track of no. of fails, resets Arduino at a certain number. #Setup part print "Setting up..." GPIO.setmode(GPIO.BOARD) # Pins assigned by pin number. GPIO.setup(resetPin, GPIO.OUT) # Sets up the in used to reset the Arduino board. ser = serial.Serial('/dev/ttyAMA0', 9600, timeout = 1) ser.open() GPIO.output(resetPin, True) time.sleep(1) GPIO.output(resetPin, False) time.sleep(2) print "Setup complete.\n" # Operational Part. nextSampleTime = datetime.datetime.today() while True: try:
def turnOffDiodes(self,gpio1, gpio2): GPIO.setmode(GPIO.BCM) self.turnOffGpio(gpio1) self.turnOffGpio(gpio2)
def setup(): GPIO.setmode(GPIO.BCM)
# LED pin numbers yled = 5 rled = 6 gled = 13 ## Functions and Definitions ## ''' Displays current date and time to screen ''' def DisplayDateTime(): # Month day, Year, Hour:Minute:Seconds date_time = time.strftime("%B %d, %Y, %H:%M:%S", time.gmtime()) print("Program run: ", date_time) ## -- Code Starts Here -- ## # Setup Code # GPIO.setmode(GPIO.BCM) # use BCM pin numbering for GPIO DisplayDateTime() # Display current date and time # 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) # Wake up Roomba sequence GPIO.output(gled, GPIO.HIGH) # Turn on green LED to say we are alive print(" Starting ROOMBA...") Roomba = RoombaCI_lib.Create_2("/dev/ttyS0", 115200) Roomba.ddPin = 23 # Set Roomba dd pin number GPIO.setup(Roomba.ddPin, GPIO.OUT, initial=GPIO.LOW) Roomba.WakeUp(131) # Start up Roomba in Safe Mode # 131 = Safe Mode; 132 = Full Mode (Be ready to catch it!)
def __init__(self, dev='/dev/spidev0.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()
def setup(): GPIO.setmode(GPIO.BCM) GPIO.setup(onPin, GPIO.OUT) GPIO.output(onPin, True)
def lightDiodes(self, gpio1, gpio2): GPIO.setmode(GPIO.BCM) self.turnOnGpio(gpio1) self.turnOnGpio(gpio2)
IoPort.output(SCK, False) time.sleep(dly) def Sck_b(dly): IoPort.output(SCK, True) time.sleep(dly) IoPort.output(SCK, False) time.sleep(2 * dly) IoPort.output(SCK, True) time.sleep(dly) MOSI = 18 SCK = 23 Key1 = 21 Key2 = 19 IoPort.setmode(IoPort.BCM) IoPort.setup(MOSI, IoPort.OUT) IoPort.setup(SCK, IoPort.OUT) IoPort.setup(Key1, IoPort.IN) IoPort.setup(Key2, IoPort.IN) while True: if KeyInput(Key1) == True: spi_c = Sck_a elif KeyInput(Key2) == True: spi_c = Sck_b else: continue # 둘다 뗴고 있으면(KeyInput때문에 반대가 됨) continue Spi_out(1, 0.2, spi_c) Spi_out(1, 0.2, spi_c) Spi_out(0, 0.2, spi_c)
def init(): GPIO.setmode(GPIO.BOARD) GPIO.setup(FlamePin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
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)
LCD_E = 24 # enable (switching signal) LCD_D4 = 23 # data bit 4 LCD_D5 = 17 # data bit 5 LCD_D6 = 27 # dat bit 6 LCD_D7 = 22 # data bit 7 pause = 0.1 # used as query interval for push button B1 = 14 # push button one connects to GPIO 14 B2 = 15 # push button two connects with GPIO 15 P1 = 0 #tracks position in the below list of six strings to display to user display_string = ["", "", "", "", "", ""] 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(B1, GPIO.IN) # Push button 1 GPIO.setup(B2, GPIO.IN) # Push button 2 # Define some device constants LCD_WIDTH = 16 # Maximum characters per line LCD_CHR = True LCD_CMD = False LCD_LINE_1 = 0x80 # LCD RAM address for the 1st line LCD_LINE_2 = 0xC0 # LCD RAM address for the 2nd line