Exemple #1
0
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()
Exemple #2
0
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
Exemple #3
0
 def __new__(cls, port, consigne = 0):
     #Initialisation du nouveau moteur
     if port in cls._MOTEURS: #Si le port est déjà pris
         raise MoteurExistErreur
     if port not in Moteur._PORTS: #Si le port est dispo
         raise MoteurPortErreur
     if consigne < -100 or consigne > 100: #Si la vitesse est comprise dans [-100;100]
         raise MoteurConsigneError
     self = object.__new__(cls)
     self._port = port
     self._isRuning = False
     self._consigne = consigne
     cls._MOTEURS[port] = self
     if port == 'A':
         pinA = 33
         pinB = 35
         self._pinTacho1 = 7
         self._pinTAcho2 = 11
     elif port == 'B':
         pinA = 37
         pinB = 40
     else:
         pinA = 38
         pinB = 36
     GPIO.setup(pinA, GPIO.OUT) #On initialise les pins en sortie
     GPIO.setup(pinB, GPIO.OUT)
     self._pwm1 = GPIO.PWM(pinA, 1000) #On les mets en tant que sortie PWMs
     self._pwm2 = GPIO.PWM(pinB, 1000)
     #GPIO.setup(self._pinTacho1, GPIO.IN) #On initialise les entrée pour récupéré signal tacho
     #GPIO.setup(self._pinTacho2, GPIO.IN)
     return self
Exemple #4
0
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 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)
Exemple #6
0
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 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
Exemple #8
0
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)		
Exemple #9
0
    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
Exemple #10
0
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)
Exemple #11
0
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()
Exemple #12
0
    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'''
Exemple #13
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()
Exemple #14
0
 def __init__(self, channel, led_pin, f):
     self.channel = channel
     self.f = f
     self.led_pin = led_pin
     self.p = Process(target=self.target_f)
     GPIO.setup(self.channel, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
     GPIO.setup(self.led_pin, GPIO.OUT, initial=GPIO.LOW)
Exemple #15
0
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()
Exemple #16
0
 def __init__(self, lm1, lm2, rm1, rm2):
     self.status = "x"
     self.leftMotor = [lm1, lm2]
     self.rightMotor = [rm1, rm2]
     self.motors = self.leftMotor + self.rightMotor
     GPIO.setup(self.motors, GPIO.OUT)
     self.stop()
Exemple #17
0
def set(pin, status):
	GPIO.setup(pin, GPIO.OUT)
	if status == True:
		status=GPIO.LOW
	else:
		status=GPIO.HIGH
	GPIO.output(pin, status)
    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)
Exemple #19
0
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()
Exemple #20
0
    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)
Exemple #21
0
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)
Exemple #22
0
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)
Exemple #23
0
    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__)
Exemple #24
0
 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 __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)
Exemple #26
0
    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()
Exemple #27
0
def main():
	try:
        # 继电器停止
		GPIO.setup(GPIO_RELAY, GPIO.IN) 

		# 启动 呼吸灯
		thread_led()
        
		# 读取传感器
		load_sensor()
		# 读取天气预报
		get_caiyun()

		# OLED 屏幕显示,附带整点报时
		thread_oled()

		# 启动读取思科路由状态
		thread_cisco()
 		# 启动读取传感器参数线程
		thread_sensor()       
		# 启动读取彩云天气
		thread_caiyun()

		while True:
			time.sleep(1)
	except KeyboardInterrupt:
		thread_run = False
		print('User press Ctrl+c ,exit;')
	finally:
		cleanup()
		pass
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 setup_pin(self, pin):
     """
     Setup pin for this relay
     :rtype: None
     """
     # TODO add some extra checks here.  Maybe verify BCM?
     GPIO.setup(pin, GPIO.OUT)
Exemple #30
0
 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)
Exemple #31
0
#!/usr/bin/env python
import time
import RPi.GPIO as GPIO

#Main
GPIO.setmode(GPIO.BOARD)
GPIO.setup(16,GPIO.OUT)
GPIO.output(16,GPIO.HIGH)

while True:
	aux=raw_input('\nPress s to take a shot, q to quit: ')
	if aux is 's':
		GPIO.output(16,GPIO.LOW)
		time.sleep(0.5)
		GPIO.output(16,GPIO.HIGH)
	elif aux is 'q':
		GPIO.cleanup()
		break
Exemple #32
0
def setup():
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(LedPin, GPIO.OUT)
    GPIO.output(LedPin, GPIO.HIGH)
Exemple #33
0
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(37,GPIO.OUT)
print "LED on"
GPIO.output(37,GPIO.HIGH)
time.sleep(1)
print "LED off"
GPIO.output(37,GPIO.LOW)
Exemple #34
0
def run_printer(q, completion):
    completion.value = -1  # -1 indicates no active job, otherwise a percentage

    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)

    GPIO.setup(RIGHT_PULSE, GPIO.OUT)
    GPIO.setup(RIGHT_DIRECTION, GPIO.OUT)
    GPIO.setup(LEFT_PULSE, GPIO.OUT)
    GPIO.setup(LEFT_DIRECTION, GPIO.OUT)

    GPIO.output(RIGHT_PULSE, GPIO.HIGH)
    GPIO.output(RIGHT_DIRECTION, GPIO.HIGH)
    GPIO.output(LEFT_PULSE, GPIO.HIGH)
    GPIO.output(LEFT_DIRECTION, GPIO.LOW)

    GPIO.setup(LEFT_LIMIT, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.setup(RIGHT_LIMIT, GPIO.IN, pull_up_down=GPIO.PUD_UP)

    pen_up()
    drawing = False

    left = right = origin_x = origin_y = -1

    while True:
        job = q.get()
        if job == 'STOP':
            break
        lines_max = lines_left = len(job)
        for l in [line.strip() for line in job]:
            lines_left -= 1
            completion.value = 1 - lines_left / lines_max

            if not l or l.startswith(';'):  # Blank line or comment
                continue
            elif l == 'G28':  # Centering routine (required before we can move in the coordinate system)
                left, right, origin_x, origin_y = center()
                drawing = False
            elif l.startswith('G0 '):  # Fast move (pen up)
                if drawing:
                    pen_up()
                    drawing = False
                m = re.search(
                    r'G0 X(?P<x>-?\d+(\.\d*)?) Y(?P<y>-?\d+(\.\d*)?)',
                    l)  # Normal X, Y coordinate move
                if m:
                    if origin_x < 0:
                        continue  # Refuse to move in the coordinate system if we have not centered
                    left, right = move_to(origin_x + float(m.group('x')),
                                          origin_y + -1 * float(m.group('y')),
                                          left, right)
                    continue
                m = re.search(r'G0 L(?P<left>-?\d+) R(?P<right>-?\d+)',
                              l)  # Manual L, R step move
                if m:
                    left_shift, right_shift = int(m.group('left')), int(
                        m.group('right'))
                    if left_shift > 0:
                        GPIO.output(LEFT_DIRECTION, GPIO.LOW)
                    else:
                        GPIO.output(LEFT_DIRECTION, GPIO.HIGH)
                    pulse(LEFT_PULSE, abs(left_shift))
                    if right_shift > 0:
                        GPIO.output(RIGHT_DIRECTION, GPIO.HIGH)
                    else:
                        GPIO.output(RIGHT_DIRECTION, GPIO.LOW)
                    pulse(RIGHT_PULSE, abs(right_shift))
                    left = right = origin_x = origin_y = -1  # Manual movements invalidate any calibrated coordinates
            elif l.startswith('G1 '):  # Draw (pen down)
                if origin_x < 0:
                    continue  # Refuse to move in the coordinate system if we have not centered
                if not drawing:
                    pen_down()
                    drawing = True
                m = re.search(
                    r'G1 X(?P<x>-?\d+(\.\d*)?) Y(?P<y>-?\d+(\.\d*)?).*', l)
                if m:
                    left, right = move_to(origin_x + float(m.group('x')),
                                          origin_y + -1 * float(m.group('y')),
                                          left, right)

        completion.value = -1

    GPIO.cleanup()
Exemple #35
0
import time
# import datetime
# import csv
# import threading
# import os
import RPi.GPIO as GPIO

import board
import busio
import adafruit_ads1x15.ads1015 as ADS
from adafruit_ads1x15.analog_in import AnalogIn
#import numpy as np

P_LED_pins = [21]
GPIO.setmode(GPIO.BCM)
GPIO.setup(P_LED_pins, GPIO.OUT)

GPIO.output(P_LED_pins, 1)

# Create the I2C bus
i2c = busio.I2C(board.SCL, board.SDA)

# Create the ADC object using the I2C bus
ads = ADS.ADS1015(i2c)

# Create single-ended input on channel 0
# photoreceptor_channel = 0
pd = AnalogIn(ads, ADS.P0)

print("{:>5}\t{:>5}".format('raw', 'v'))
def main():

    GPIO.setmode(GPIO.BOARD)  #setting the pin numbering method of raspberry pi

    ####################setting pins as output or input for the sensor and motors
    ###################motors, servo, and trigger pins os ultrasonic sensor will be set as output
    ##################echo pin will be set as input

    GPIO.setup(TRIG1, GPIO.OUT)
    GPIO.setup(ECHO1, GPIO.IN)
    GPIO.setup(TRIG2, GPIO.OUT)
    GPIO.setup(ECHO2, GPIO.IN)
    GPIO.setup(TRIG3, GPIO.OUT)
    GPIO.setup(ECHO3, GPIO.IN)
    GPIO.setup(servo1, GPIO.OUT)
    GPIO.setup(servo2, GPIO.OUT)
    GPIO.setup(left1, GPIO.OUT)
    GPIO.setup(left2, GPIO.OUT)
    GPIO.setup(right1, GPIO.OUT)
    GPIO.setup(right2, GPIO.OUT)
    ###################################

    #######initially setting the pins in OFF condition
    GPIO.output(TRIG1, False)
    GPIO.output(TRIG2, False)
    GPIO.output(TRIG3, False)
    #########################

    ####for initialization of the servo motor .....a servo motor will work with a PWM signal of 50HZ frequency
    pwm1 = GPIO.PWM(servo1, 50)
    pwm2 = GPIO.PWM(servo2, 50)
    ######################################

    #########setting a threshold distance value for the sensors that is if the distance between obstacle and ultrasonic sensor is less than threshod value than all the process of image processing will be executed
    max_front_dist = 25
    max_left_dist = 20
    max_right_dist = 20
    ##################3

    #######starting servo motor with a PWM value of 5 the full rotation of servo motor will be between 0-12 where 0 correspinds to 0 degree and 12 correspinds to 180 degree rotation
    pwm1.start(5)
    pwm2.start(5)

    time.sleep(2)  ####giving a little delay for everything to setup

    ######this will keep on running on and on in loop
    try:
        while True:

            #####string distance calculated by sensors in variables
            front_dist = check_front_dist()
            left_dist = check_left_dist()
            right_dist = check_right_dist()
            ################3

            #####logic for the autonomous movement

            ####if front sendor encounters some obstacle
            if front_dist < max_front_dist:
                stop()
                pwm1.ChangeDutyCycle(
                    7
                )  #change the angle of servo with camera to face towards the obstacle
                time.sleep(1)
                isHuman = cam(
                )  #isHuamn will store the value True of False i.e. whether the obstacle is person or not

                if isHuman == True:  #if obstacle is person then rotate to shield towards human in order to protect him/her fro the UV light
                    print("human detected")
                    pwm2.ChangeDutyCycle(7)
                    time.sleep(1)
                else:
                    print("human not detected")

####for autonomous movement....that is after encountering an obstacel turn the not to a side where the obstacle is farther means if the distance from left sensor 20cm and form right sendor it si 30 cm then the  bot will move to the right and vice versa
                if right_dist > left_dist:
                    if right_dist < max_right_dist and left_dist < max_left_dist:  #if both senors encounter obstacle that is less then threshold value of distance then bot first move backwards and the figure out left or right
                        stop()
                        time.sleep(tf)
                        backward()
                        time.sleep(1)
                    else:
                        right()
                        time.sleep(0.5)
                elif left_dist > right_dist:
                    if right_dist < max_right_dist and left_dist < max_left_dist:
                        stop()
                        time.sleep(tf)
                        backward()
                        time.sleep(1)
                    else:
                        left()
                        time.sleep(0.5)

###############if obstacle is on right then take snapshot process it and check whether human or not and move the shield the accordingly and then rotate to the left
            elif right_dist < max_right_dist:
                stop()
                pwm1.ChangeDutyCycle(11)
                time.sleep(1)
                isHuman = cam()

                if isHuman == True:
                    print("human detected")
                    pwm2.ChangeDutyCycle(11)
                    time.sleep(1)
                else:
                    print("human not detected")
                left()
                time.sleep(0.5)

############same as uppper one but rotate to rigth
            elif left_dist < max_left_dist:
                stop()
                pwm1.ChangeDutyCycle(3)
                time.sleep(1)
                isHuman = cam()

                if isHuman == True:
                    print("human detected")
                    pwm2.ChangeDutyCycle(3)
                    time.sleep(1)
                else:
                    print("human not detected")
                right()
                time.sleep(0.5)

#####if there is not obstacle then keep on moving forward
            else:
                forward()

#######if CTRl+C is pressed the program will terminate and all the pins of raspberry pi will be cleared whichever logic they hold right now
    except KeyboardInterrupt:
        GPIO.cleanup()
Exemple #37
0
 def setup_GPIO(self, pinRain, pinVent1, pinVent2):
     GPIO.setmode(GPIO.BCM)
     GPIO.setup(pinVent1, GPIO.OUT, initial=1)
     GPIO.setup(pinVent2, GPIO.OUT, initial=1)
     GPIO.setup(pinRain, GPIO.IN)
Exemple #38
0
#!/usr/bin/python
# -*- coding: utf-8 -*-
# http://elecrow.com/

import RPi.GPIO as GPIO
import time

# define motion pin
motion_pin = 16

# set GPIO as GPIO.BOARD
GPIO.setmode(GPIO.BOARD)
# set pin mode as INPUT
GPIO.setup(motion_pin, GPIO.IN)

try:
    while True:
       if(GPIO.input(motion_pin) == 0):
             print("Nothing moves ...")
       elif(GPIO.input(motion_pin) == 1):
             print("Motion detected!")
       time.sleep(0.1)
except KeyboardInterrupt:
    GPIO.cleanup()
            break
        else:
            time.sleep(0.5)
            

def button_callback(channel):
    #buffer = "S%s" % (quote_array[idx])
    buffer = "Spush me"
    print(buffer + "\n")
    serial.write(buffer.encode())
    wait_for_ready()
    #idx += 1

    
serial = serial.Serial("/dev/ttyAMA0", baudrate=9600)
serial.write(str.encode("\n"))
time.sleep(1)
serial.write(str.encode("V15\n")) # Adjust volume
wait_for_ready()
print("Ready...\n")

f = open("quotefile.txt", "r")
for x in f:
  quote_array.append(x)

GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
GPIO.setup(15, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Set pin 15 to be an input pin and set initial value to be pulled low (off)
GPIO.add_event_detect(15,GPIO.RISING,callback=button_callback, bouncetime = 2000) # Setup event on pin 15 rising edge
message = input("Press enter to quit\n\n") # Run until someone presses enter
GPIO.cleanup() # Clean up
Exemple #40
0
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)

PIR_PIN = 20
GPIO.setup(PIR_PIN, GPIO.IN)


def getMotion():
    while True:
        if GPIO.input(PIR_PIN):
            return True
        else:
            return False
# 10_RGB_LED.py
from tkinter import *      
import RPi.GPIO as GPIO
import time

# Configure the Pi to use the BCM (Broadcom) pin names, rather than the pin positions
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
GPIO.setup(23, GPIO.OUT)
GPIO.setup(24, GPIO.OUT)

# Start Pulse Width Modulation (PWM) on the red, green and blue channels 
pwmRed = GPIO.PWM(18, 500)
pwmRed.start(100)

pwmGreen = GPIO.PWM(23, 500)
pwmGreen.start(100)

pwmBlue = GPIO.PWM(24, 500)
pwmBlue.start(100)


# group together all of the GUI code into a class called App
class App:
    
    # this function gets called when the app is created
    def __init__(self, master):
        # A frame holds the various GUI controls
        frame = Frame(master)
        frame.pack()
        
Exemple #42
0
#Libraries
import RPi.GPIO as GPIO
import time
 
#GPIO Mode (BOARD / BCM)
GPIO.setmode(GPIO.BOARD)
 
#set GPIO Pins
GPIO_TRIGGER = 13
GPIO_ECHO = 11
 
#set GPIO direction (IN / OUT)
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)
 
def distance():
    # set Trigger to HIGH
    GPIO.output(GPIO_TRIGGER, True)
 
    # set Trigger after 0.01ms to LOW
    time.sleep(0.00001)
    GPIO.output(GPIO_TRIGGER, False)
 
    StartTime = time.time()
    StopTime = time.time()
 
    # save StartTime
    while GPIO.input(GPIO_ECHO) == 0:
        StartTime = time.time()
 
    # save time of arrival
import RPi.GPIO as GPIO                    #Import GPIO library
import time                                #Import time library
GPIO.setmode(GPIO.BCM)                     #Set GPIO pin numbering 

GPIO_TRIGGER = 23
GPIO_ECHO = 24                             #Associate pin 14 to Echo

print ("Posture Test in progress")

GPIO.setup(GPIO_TRIGGER,GPIO.OUT)          #Set pin as GPIO out
GPIO.setup(GPIO_ECHO,GPIO.IN)              #Set pin as GPIO in

while True:

  GPIO.output(GPIO_TRIGGER, False)         #Set TRIG as LOW
  print ("Checking Stance")                #Checking the User stance
  time.sleep(10)                           #Checking the user stance for 30 Seconds

  GPIO.output(GPIO_TRIGGER, True)          #Set TRIG as HIGH
  time.sleep(0.00001)                      #Delay of 0.00001 seconds
  GPIO.output(GPIO_TRIGGER, False)         #Set TRIG as LOW

  while GPIO.input(GPIO_ECHO)==0:          #Check if Echo is LOW
    pulse_start = time.time()              #Time of the last  LOW pulse
 
  while GPIO.input(GPIO_ECHO)==1:          #Check whether Echo is HIGH
    pulse_end = time.time()                #Time of the last HIGH pulse 

  pulse_duration = pulse_end - pulse_start #pulse duration to a variable

  distance = pulse_duration * 17150        #Calculate distance
Exemple #44
0
import time
import RPi.GPIO as GPIO

USING_PIN = 12

GPIO.setmode(GPIO.BOARD)
GPIO.setup(USING_PIN, GPIO.OUT)

p = GPIO.PWM(USING_PIN, 50)
p.start(0)
try:
    while 1:
        for dc in range(0, 101, 5):
            p.ChangeDutyCycle(dc)
            time.sleep(0.1)
        for dc in range(100, -1, -5):
            p.ChangeDutyCycle(dc)
            time.sleep(0.1)
except KeyboardInterrupt:
    pass
p.stop()
GPIO.cleanup()
import math
import atexit
  
pin = 16 # pin 12 is 6th from the left on the outside

steering_angle = 0

pwm = GPIO.PWM(pin, 10)
pwm.start(get_duty_cycle())

def get_duty_cycle():
    return 1.5 + (get_steering_angld()/2)

def get_steering_angle():
    return steering_angle

def set_steering_angld(new_steering_angle):
    steering_angle = new_steering_angle
    pwm.ChangeDutyCycle(get_duty_cycle)


@atexit.register
def goodbye():
    pwm.stop()
    GPIO.cleanup()


GPIO.setmode(GPIO.BOARD)
GPIO.setup(pin, GPIO.OUT)

Exemple #46
0
# Based on https://maker.pro/raspberry-pi/tutorial/how-to-interface-a-pir-motion-sensor-with-raspberry-pi-gpio
# just seeing that the PIR works.

import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.IN)  #Read output from PIR motion sensor
while True:
    i = GPIO.input(11)
    if i == 0:  #When output from motion sensor is LOW
        print "No intruders", i
        time.sleep(0.1)
    elif i == 1:  #When output from motion sensor is HIGH
        print "Intruder detected", i
        time.sleep(0.1)
Exemple #47
0
tail  = -10             # Index of last 'off' pixel
color = 0xFF0000        # 'On' color (starts red)

def makeColor(r, g, b):
    return (r << 16) + (g << 8) + b

def colorWheel(wheelPos):
    """
    0 is red, 85 is green, 170 is blue
    """
    if wheelPos < 85:
        return makeColor(255 - wheelPos * 3, wheelPos * 3, 0)

    elif wheelPos < 170:
        wheelPos -= 85
        return makeColor(0, 255 - wheelPos * 3, wheelPos * 3)

    else:
        wheelPos -= 170
        return makeColor(wheelPos * 3, 0, 255 - wheelPos * 3)


GPIO.setmode(GPIO.BCM)
# Turn off warnings...
GPIO.setwarnings(False)

GPIO.setup(LED, GPIO.OUT)

# Setup the Inputs
GPIO.setup(IRLED, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
Exemple #48
0
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
LED_PIN=12
GPIO.setup(LED_PIN,GPIO.OUT)
def mos(list):
        if list == 1:
                GPIO.output(LED_PIN,GPIO.HIGH)
                time.sleep(1)
                GPIO.output(LED_PIN,GPIO.LOW)
                time.sleep(0.5)
        elif list == 0:
                GPIO.output(LED_PIN,GPIO.HIGH)
                time.sleep(0.5)
                GPIO.output(LED_PIN,GPIO.LOW)
                time.sleep(0.5)
_A=[0, 1]
_B=[1,0, 0, 0]
_C=[1, 0, 1, 0]
_D=[1, 0, 0]
_E=[0]
_F=[0, 0, 1, 0]
_G=[1, 1, 0]
_H=[0, 0, 0, 0]
_I=[0, 0]
_J=[0, 1, 1, 1]
_K=[1, 0, 1]
_L=[0, 1, 0, 0]
_M=[1, 1]
_N=[1, 0]
_O=[1, 1, 1]
from time import sleep
import os

############
# CONSTANTS#
############
# Input pin is 15 (GPIO22)
INPUT_PIN = 15
# To turn on debug print outs, set to 1
DEBUG = 1

###################
# INITIALIZE PINS #
###################
GPIO.setmode(GPIO.BOARD)
GPIO.setup(INPUT_PIN, GPIO.IN,pull_up_down=GPIO.PUD_DOWN)
#GPIO.setup(INPUT_PIN, GPIO.IN)

# Main loop, listen for infinite packets
while True:
    print("\nWaiting for GPIO low")

    # If there was a transmission, wait until it finishes
    #GPIO.wait_for_edge(INPUT_PIN, GPIO.RISING)
    value = 1
    while value:
        sleep(0.001)
        #print("Last read value: {}".format(value))
        value = GPIO.input(INPUT_PIN)       

    # timestamps for pulses and packet reception
Exemple #50
0
maxSpeed 	= 1000
aceleracion	= False

try:
	GPIO.setmode(GPIO.BCM)
	GPIO.setwarnings(False)
	if(mineral):
		Giro 		= 21
		Velocidad 	= 20
		motor		= "Mineral"
	else:
		Giro 		= 26
		Velocidad 	= 25
		motor		= "Levadura"
		
	GPIO.setup(Velocidad,GPIO.OUT)
	GPIO.setup(Giro,GPIO.OUT)
	stepper = GPIO.PWM(Velocidad,300)
	stepper.start(0)
	print(motor," arrancado")
	c = 0
	
	while True:
		stepper.ChangeDutyCycle(50)
		if aceleracion:
			for i in range(10,maxSpeed,10):
				stepperSpeed(stepper,i)
				time.sleep(0.1)
			
			for i in reversed(range(10,maxSpeed,10)):
				stepperSpeed(stepper,i)
Exemple #51
0
def set_pin_data(channel):
    #GPIO.setup(channel, GPIO.IN)
    GPIO.setup(channel, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)  # set initial value to be pulled low (off)
    GPIO.add_event_detect(channel, GPIO.RISING, callback=button_callback)
    print("channel %s active" % channel)
Exemple #52
0
from count import count_above
from multiprocessing import Process
import time
#import ray
import threading
import json
#ray.init()

i = 0
ls = np.zeros((100, 800, 1280), dtype=np.uint8)
results = np.zeros((800, 1280), dtype=np.uint8)
adc_threshold1 = np.uint8(10)
pix_threshold = np.uint8(199)
camera = arducam.mipi_camera()
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.IN)
GPIO.setup(8, GPIO.IN)
GPIO.setup(9, GPIO.OUT, initial - GPIO.LOW)
GPIO.setup(10, GPIO.OUT, initial=GPIO.LOW)

start_proc = threading.Event()
next_frame = threading.Event()
start_cap = threading.Event()

counter = 0
loop = 0


def wait_sig():
    while (True):
        if (GPIO.input(7)):
Exemple #53
0
import RPi.GPIO as IO         # calling for header file which helps us use GPIO’s of PI
import time                             # calling for time to provide delays in program
IO.setwarnings(False)           # do not show any warnings
x=1                
IO.setmode (IO.BCM)        # programming the GPIO by BCM pin numbers. (like PIN29 as‘GPIO5’)
IO.setup(4,IO.OUT)            # initialize GPIO Pins as an output.
IO.setup(5,IO.OUT)
IO.setup(6,IO.OUT)
while 1:                               # execute loop forever
    for y in range(8):            # loop for counting up 8 times
        IO.output(4,1)            # pull up the data pin for every bit.
        time.sleep(0.1)            # wait for 100ms
        IO.output(5,1)            # pull CLOCK pin high
        time.sleep(0.1)
        IO.output(5,0)            # pull CLOCK pin down, to send a rising edge
        IO.output(4,0)            # clear the DATA pin
        IO.output(6,1)            # pull the SHIFT pin high to put the 8 bit data out parallel
        time.sleep(0.1)
        IO.output(6,0)            # pull down the SHIFT pin

    for y in range(8):            # loop for counting up 8 times
        IO.output(4,0)            # clear the DATA pin, to send 0
        time.sleep(0.1)            # wait for 100ms
        IO.output(5,1)            # pull CLOCK pin high
        time.sleep(0.1)
        IO.output(5,0)            # pull CLOCK pin down, to send a rising edge
        IO.output(4,0)            # keep the DATA bit low to keep the countdown
        IO.output(6,1)            # pull the SHIFT pin high to put the 8 bit data out parallel
        time.sleep(0.1)
        IO.output(6,0)
# -*- coding: UTF-8 -*-

import RPi.GPIO as GPIO
import time

### 設定
PIN_L_1 = 22
PIN_L_2 = 27
PIN_L_3 = 17

GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN_L_1, GPIO.IN)
GPIO.setup(PIN_L_2, GPIO.IN)
GPIO.setup(PIN_L_3, GPIO.IN)

status_l_1 = 0;
status_l_2 = 0;
status_l_3 = 0;

### ヘッダ
print("Content-Type: text/event-stream")
print("Connection: close")
print("")

try:
    while True:
        print("event: heartbeat")
        print("data: alive")
        print("")
        value_l_1 = GPIO.input(PIN_L_1)
        if value_l_1 != status_l_1:
Exemple #55
0
import time
import RPi.GPIO as GPIO
import config_pins

GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)

GPIO.setup(config_pins.pin_empfangen, GPIO.IN)

dit = 0.3

initial_lichttimer_start = False
initial_dunkeltimer_start = False
initial_letzte_zeichen_timer = False


def main():
    empfange_paket()


def empfange_paket():
    empfangsstring = ''

    #Wechsel von Hell auf Dunkel oder Dunkel auf Hell
    change = False
    ersteZeichenSchonEmpfangen = False
    letzteZeichenDesPakets = True

    anzeige_empfangsstring_zum_schluss = True

    letzte_zeichen_timer_start()
Exemple #56
0
import http.server
import socketserver
import shutil
import os
import time
import sys
import json

if sys.argv[1] != "dev":
    import RPi.GPIO as GPIO
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(12, GPIO.OUT, initial=GPIO.LOW)

port = 8080

class QuackHandler(http.server.BaseHTTPRequestHandler):
    server_version = "Quack/2.0"

    def do_GET(self):
        f = self.send_head()
        if f:
            try:
                self.copyfile(f, self.wfile)
            finally:
                f.close()

    def do_HEAD(self):
        f = self.send_head()
        if f:
            f.close()
def setup():
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(LED_PIN, GPIO.OUT)
def initialize():
  # Main program block

  GPIO.setmode(GPIO.BCM)       # Use BCM GPIO numbers
  GPIO.setup(LCD_E, GPIO.OUT)  # E
  GPIO.setup(LCD_RS, GPIO.OUT) # RS
  GPIO.setup(LCD_D4, GPIO.OUT) # DB4
  GPIO.setup(LCD_D5, GPIO.OUT) # DB5
  GPIO.setup(LCD_D6, GPIO.OUT) # DB6
  GPIO.setup(LCD_D7, GPIO.OUT) # DB7
  GPIO.setup(LED_ON, GPIO.OUT) # Backlight enable

  # Initialise display
  lcd_init()
  time.sleep(0.2)	
Exemple #59
0
import RPi.GPIO as GPIO
from time import sleep

GPIO.setmode(GPIO.BOARD)

Motor1A = 16
Motor1B = 18
Motor1E = 22

GPIO.setup(Motor1A, GPIO.OUT)
GPIO.setup(Motor1B, GPIO.OUT)
GPIO.setup(Motor1E, GPIO.OUT)

print("Turning motor on")
GPIO.output(Motor1A, GPIO.HIGH)
GPIO.output(Motor1B, GPIO.LOW)
GPIO.output(Motor1E, GPIO.HIGH)

sleep(10)

print("Stopping motor")
GPIO.output(Motor1E, GPIO.LOW)

GPIO.cleanup()
Exemple #60
0
#!/usr/bin/python

import RPi.GPIO as GPIO
import time
from time import gmtime, strftime

# GPIO stuff

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

doorSensor = 4
doorStatus = "Door "

GPIO.setup(doorSensor, GPIO.IN, pull_up_down=GPIO.PUD_UP)

try:
    #while True:
        doorStatus += "open" if GPIO.input(doorSensor) == 1 else "closed"

        #time.sleep(0.1)

        print doorStatus
except (KeyboardInterrupt):
    print "\n CTRL+C"
except Exception as e:
    GPIO.cleanup()
finally:
    GPIO.cleanup()