Exemplo n.º 1
0
	def __init__(self, pin_rs=7, pin_e=8, pins_db=[25, 24, 23, 18]):
		self.pin_rs=pin_rs
		self.pin_e=pin_e
		self.pins_db=pins_db
		self.contrast = PWMLED(15,frequency=25)
		self.contrast.on()
		self.contrast.value=.55
		self.Contrastbutton = Button(14)
		self.Contrastbutton.when_pressed = self.ContrastPressed
		
		self.brightness = PWMLED(20,frequency=60)
		self.brightness.on()
		self.brightness.value=.95
		self.Brightnessbutton = Button(21)	
		self.Brightnessbutton.when_pressed = self.BrightnessPressed

		GPIO.setmode(GPIO.BCM)
		GPIO.setup(self.pin_e, GPIO.OUT)
		GPIO.setup(self.pin_rs, GPIO.OUT)
		for pin in self.pins_db:
			GPIO.setup(pin, GPIO.OUT)
		self.clear()
Exemplo n.º 2
0
from gpiozero import PWMLED, Button
import time
from threading import Thread, Lock
import random
import logging

press = Button(20)
led = PWMLED(21)
zmacknuto: bool = press.value
inp = input("Name of the file to save data into: ")
time_pressed = 0
casy = []
pressed = False

logger = logging.getLogger(__name__)
handler = logging.StreamHandler()
formatter = logging.Formatter(
    '%(asctime)s - %(levelname)s - %(threadName)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)


def button_press():
    global time_pressed, zmacknuto, lock
    while True:
        lock.acquire(
        )  # locks here so main thread has to wait until button is pressed
        logger.debug("Locked")
        press.wait_for_inactive(
        )  # wait for inactive button to not spam console
Exemplo n.º 3
0
#!/usr/bin/python

# Importation des librairies pythons
from gpiozero import MotionSensor
from gpiozero import PWMLED
import random
import pygame

#GPIO utilise
GPIO_PIR = 4
GPIO_LED1 = 13
GPIO_LED2 = 19

pir = MotionSensor(GPIO_PIR)
ledG = PWMLED(GPIO_LED1)
ledD = PWMLED(GPIO_LED2)

ledG.value = 0
ledD.value = 0

pygame.init()


def playSound(_son, _repeat=0):
    pygame.mixer.init()
    pygame.mixer.music.load(_son)
    pygame.mixer.music.play(loops=_repeat)


def waitSound():
    while pygame.mixer.music.get_busy() == True:
Exemplo n.º 4
0
#!/usr/bin/python

from gpiozero import PWMLED
from time import sleep

led = PWMLED(4)

lvl = input("Input brightness (.1-1): ")

while True:
    led.value = lvl
Exemplo n.º 5
0
#!/bin/python3

from gpiozero import PWMLED
from time import sleep
from subprocess import PIPE, Popen
import subprocess

fan = PWMLED(22)
flag = 0
min = 42
coff = 0.5
dcmin = 0.25
max = 60


def get_cpu_temp():
    #tempFile = open( '/sys/class/thermal/thermal_zone0/temp' )
    #cpu_temp = tempFile.read()
    #tempFile.close()
    #return float(cpu_temp)/1000
    cpu_temp = subprocess.check_output(
        ["/opt/vc/bin/vcgencmd", "measure_temp"])
    t = str(cpu_temp)[7:-5]
    return float(t)


while True:
    #print("\033c")
    cpu = get_cpu_temp()
    var = cpu - min
    var = var / (max - min)
Exemplo n.º 6
0
#   limitations under the License.
#
# Python script to turn on the IR LED

from gpiozero import PWMLED
from signal import pause
from optparse import OptionParser

DEFAULT_VALUE = 0.7

#add command line options

parser = OptionParser()

parser.add_option("-v", "--vaule", dest="value", help=" use -v ? to set value of irLED PWM, valid values are 0 through to 1" )


options, arguments = parser.parse_args()
if options.value:
	value = float(options.value)
	print("Using specified value =",options.value)

else:
	print("No value was given")
	value = DEFAULT_VALUE
	print("Using default value =",value)
ir = PWMLED(22)
ir.frequency = 25 # Set frequency stream frame rate
ir.value = value
pause()
Exemplo n.º 7
0
from gpiozero import PWMLED, Button
from signal import pause


red_led = PWMLED(17)
button = Button(2)

red_led.source = button.values

pause()
Exemplo n.º 8
0
# Choose a gain of 1 for reading voltages from 0 to 4.09V.
# Or pick a different gain to change the range of voltages that are read:
#  - 2/3 = +/-6.144V
#  -   1 = +/-4.096V
#  -   2 = +/-2.048V
#  -   4 = +/-1.024V
#  -   8 = +/-0.512V
#  -  16 = +/-0.256V
# See table 3 in the ADS1015/ADS1115 datasheet for more info on gain.
GAIN = 2

# @@@@ Hardware init @@@@
#
adc = PiIO_Analog(GAIN)
run = LED(adc.RUN)
PWM1 = PWMLED(adc.PWM1)
PWM2 = PWMLED(adc.PWM2)
IN1 = Button(adc.I1, pull_up=False)
IN2 = Button(adc.I2, pull_up=False)
IN3 = Button(adc.I3, pull_up=False)
IN4 = Button(adc.I4, pull_up=False)
O1 = LED(adc.O1)
O2 = LED(adc.O2)
O3 = LED(adc.O3)
O4 = LED(adc.O4)
O5 = LED(adc.O5)
O6 = LED(adc.O6)
O7 = LED(adc.O7)
O8 = LED(adc.O8)
OE = LED(adc.OE)
# @@@@ Example code here @@@@
from gpiozero import PWMLED

r = PWMLED(23)
r.pulse(fade_in_time=1.0, fade_out_time=1.0)
y = PWMLED(12)
y.pulse(fade_in_time=1.0, fade_out_time=1.0)
g = PWMLED(21)
g.pulse(fade_in_time=1.0, fade_out_time=1.0, background=False)
Exemplo n.º 10
0
    ecodes.KEY_8,
    ecodes.KEY_9,
    ecodes.KEY_0,
)

evdev_device = 0
try:
    evdev_device = int(sys.argv[1])
except IndexError:
    pass
except ValueError:
    pass


print("Almost there, pulse the eyes to let the user know")
eyes = PWMLED(21)
eyes.blink(0.5, 0.25, 0.25, 0.25, 3, False)
eyes.on()

print("Initialised, now handling events")
try:
    # Only run the motors at 50% initially
    power = 0.5
 
    # Process the (lirc-spawned) events
    device = InputDevice("/dev/input/event" + str(evdev_device))
    for event in device.read_loop():
        if event.type == ecodes.EV_KEY:
            if event.value == 1: # key down
                if event.code in robot_movement:
                    robot_movement[event.code](power)
Exemplo n.º 11
0
from services.spin_motors import spin_motors
from services.logs_after import logs_after
from services.check_wifi import check_wifi

try:
    from gpiozero import PWMLED
except:
    print('gpiozero module is not available')

    class PWMLED:
        value = 0

        def __init__(self, x):
            pass

servo = PWMLED(13)
servo_center = 0.125
servo_span = 0.045
servo_min = servo_center-servo_span
servo_max = servo_center+servo_span

LEFT = +1
RIGHT = -1

motor1 = PWMLED(6)


def motor(speed=0.1, delay=0.2, eternal=False):
    motor1.value = abs(speed)
    if not eternal:
        sleep(delay)
Exemplo n.º 12
0
from gpiozero import PWMLED
from gpiozero.tools import random_values
from signal import pause

led = PWMLED(4)
led.source = random_values()
led.source_delay = 0.1

pause()
Exemplo n.º 13
0
from gpiozero import PWMLED
from signal import pause
from connect import open_worksheet, read_cell_continuous

wks = open_worksheet("GPIO Zero")

led = PWMLED(2)

led.source = read_cell_continuous(wks, 1, 1)

pause()
Exemplo n.º 14
0
class HD44780:
	
	  

	def __init__(self, pin_rs=7, pin_e=8, pins_db=[25, 24, 23, 18]):
		self.pin_rs=pin_rs
		self.pin_e=pin_e
		self.pins_db=pins_db
		self.contrast = PWMLED(15,frequency=25)
		self.contrast.on()
		self.contrast.value=.55
		self.Contrastbutton = Button(14)
		self.Contrastbutton.when_pressed = self.ContrastPressed
		
		self.brightness = PWMLED(20,frequency=60)
		self.brightness.on()
		self.brightness.value=.95
		self.Brightnessbutton = Button(21)	
		self.Brightnessbutton.when_pressed = self.BrightnessPressed

		GPIO.setmode(GPIO.BCM)
		GPIO.setup(self.pin_e, GPIO.OUT)
		GPIO.setup(self.pin_rs, GPIO.OUT)
		for pin in self.pins_db:
			GPIO.setup(pin, GPIO.OUT)
		self.clear()
		
        
	def ContrastPressed(self):
		nCurrentContrastValue = self.contrast.values.next() + .1
		self.contrast.value = nCurrentContrastValue if nCurrentContrastValue < 1 else .05
		self.clear()
		self.message("Contrast: " + str(self.contrast.values.next()))
		
	def BrightnessPressed(self):
		nCurrentBrightnessValue = self.brightness.values.next() + .1
		self.brightness.value = nCurrentBrightnessValue if nCurrentBrightnessValue < 1.01 else .10
		self.clear()
		self.message("Brightness: " + str(self.brightness.values.next()))	

	def clear(self):
		""" Blank / Reset LCD """

		self.cmd(0x33) # $33 8-bit mode
		self.cmd(0x32) # $32 8-bit mode
		self.cmd(0x28) # $28 8-bit mode
		self.cmd(0x0C) # $0C 8-bit mode
		self.cmd(0x06) # $06 8-bit mode
		self.cmd(0x01) # $01 8-bit mode

	def cmd(self, bits, char_mode=False):
		""" Send command to LCD """

		sleep(0.001)
		bits=bin(bits)[2:].zfill(8)

		GPIO.output(self.pin_rs, char_mode)

		for pin in self.pins_db:
			GPIO.output(pin, False)

		for i in range(4):
			if bits[i] == "1":
				GPIO.output(self.pins_db[::-1][i], True)

		GPIO.output(self.pin_e, True)
		GPIO.output(self.pin_e, False)

		for pin in self.pins_db:
			GPIO.output(pin, False)

		for i in range(4,8):
			if bits[i] == "1":
				GPIO.output(self.pins_db[::-1][i-4], True)


		GPIO.output(self.pin_e, True)
		GPIO.output(self.pin_e, False)

	def message(self, text):
		""" Send string to LCD. Newline wraps to second line"""

		for char in text:
			if char == '\n':
				self.cmd(0xC0) # next line
			else:
				self.cmd(ord(char),True)
from gpiozero import Button
from subprocess import check_call
from gpiozero.tools import random_values
from random import *
import time

# set up various delay values
delay = 0.05  # used in spiral function
delay2 = 0.03  # used in spiral function
on_delay = 0.01  # used in random_led function
top_down_delay = 0.125  # used in top_down function
top_down_delay2 = 0.05  # used in top_down function
sides_delay = 0.075  # used in the sides function

# Just flicker the star led
star = PWMLED(2)
star.source = random_values()


# define the shutdown sequence for the shutdown button
def shutdown():
    check_call(['sudo', 'poweroff'])


shutdown_btn = Button(3)

period_min = 3  # base number of seconds for each function
period_max = 10  # maximum number of seconds for each function


def spiral():
Exemplo n.º 16
0
#! venv/bin/python

from gpiozero import MotionSensor, LED, PWMLED, Button
from picamera import PiCamera
from datetime import datetime
from subprocess import run
from threading import Thread
from time import sleep
import os
import warnings

camera = PiCamera()
pir = MotionSensor(4)
standbyLight = LED(27)
armingLight = PWMLED(22)
armedLight = LED(18)
recordingLight = PWMLED(23)
startButton = Button(24)
stopButton = Button(25, hold_time=5)
VIDEOS_DIR = os.path.expanduser(os.path.join('~', 'Videos'))
os.chdir(VIDEOS_DIR)
idCounter = 0
exitFlag = 0
running = 0
initialized = 0


class DropboxThread(Thread):
    def __init__(self, threadID, name, videoFilePath, dropboxSavePath):
        Thread.__init__(self)
        self.threadID = threadID
Exemplo n.º 17
0
from gpiozero import LED
from signal import pause
from signal import alarm
import signal
from datetime import datetime
import tornado.web
import tornado.ioloop
import tornado.websocket
import json
from uuid import uuid4
import sys
from w1thermsensor import W1ThermSensor as w1bus
import git

button = Button(3, True, None, 0.05, 0)
led = PWMLED(22, False)
state = 0
stateName = {0: "Off", 1: "On"}
WebSocketConnections = set()

# Dictionary of DS18S20 temperature sensors
sensors = {}
ds_sensors = {}

# Dictionary contains scheduled events (on, off, bitwise days - Monday = 1, Sunday = 64)
schedule = {}

version = "Unversioned"


# Activate timer if within a timer window
Exemplo n.º 18
0
from gpiozero import PWMLED
from signal import pause

red = PWMLED(4)
yellow = PWMLED(17)
green = PWMLED(23)

red.pulse()
yellow.pulse()
green.pulse()

pause()
Exemplo n.º 19
0
# This code is to demonstrate a PWM signal generation
# With PWM, intensity of an LED is varied.
# LED is connected to pin 11 as usual (GPIO 17) 
# Setting the value to 0 sets ON time as zero so turning off the LED
# Similarly, a value of 1 turns on the LED in full intensity

from gpiozero import PWMLED
from time import sleep

led = PWMLED(17)

while 1:
    led.value=0		# LED is turned off
    sleep(1)

    led.value=0.5	# LED glows in half brightness
    sleep(1)

    led.value=(1)	# LED turns on in full intensity
    sleep(1)
Exemplo n.º 20
0
    check_call(['sudo', 'poweroff'])


def low_battery():
    file = open(
        '/mnt/camera.log', 'a'
    )  # automatically stop recording and shut down when the low battery signal is received
    file.write(datetime.now().strftime('%d/%m/%Y, %H:%M:%S') +
               '\tBattery is low\n')
    file.close()
    shutdown


# make the activity LED pulse to show the camera is working
# This script makes use of the green led which is already present in the raspberry pi zero and pi zero W
activity = PWMLED(47)  # /sys/class/leds/led0
activity.pulse()

# shut down the pi if the button is held down for >2 seconds
shutdown_btn = Button(22, hold_time=2)
shutdown_btn.when_held = shutdown
print('activated shutdown button')

# automatically stop recording and shut down when the low battery signal is received
low_batt_signal = DigitalInputDevice(4, pull_up=True, bounce_time=2)
low_batt_signal.when_activated = low_battery
print('activated the low battery detection')

with picamera.PiCamera() as camera:
    start_time = datetime.now()
    camera.resolution = (
from gpiozero import PWMLED
from time import sleep

led = PWMLED(17)

while True:
    led.value = 0  # off
    sleep(1)
    led.value = 0.5  # half brightness
    sleep(1)
    led.value = 1  # full brightness
    sleep(1)
Exemplo n.º 22
0
from gpiozero import PWMLED
from signal import pause

led = PWMLED(17)

led.pulse()

pause()
Exemplo n.º 23
0
forwardBack = Motor(17, 27)
leftRight = Motor(22, 23)
upDown = Motor(24, 25)

#Init Stop Switches
leftRightStop = Button(4)
forwardBackStop = Button(3)
upStop = Button(2)
downStop = Button(5)

#Init Buttons
forwardButton = Button(7)
rightButton = Button(6)

#Init Claw Electromagnet
clawMagnet = PWMLED(18, frequency=100)

moveMusic = "musicFiles/movement.ogg"
clawMusic = "musicFiles/clawLonger.ogg"

while True:
    print("Press enter to start game")

    print("Waiting for right button")
    rightButton.wait_for_press()
    pygame.mixer.music.load(moveMusic)
    pygame.mixer.music.play()
    leftRight.backward()
    sleep(0.3)
    while (rightButton.is_pressed) and (leftRightStop.is_pressed != 1):
        pass
from gpiozero import LED
from gpiozero import PWMLED
from gpiozero import Button
from time import sleep

#setup the LEDs
led = []
sleeptime = .01

for i in range(0, 10):
    led.append(LED(i + 2))

sololed = PWMLED(17)


# define a function to run the LEDs up
def race_up():
    for i in range(0, 10):
        print("{} on".format(i))
        led[i].on()
        sleep(sleeptime)
        print("  off")
        led[i].off()
        sleep(sleeptime)


#define a function to run the LEDs down
def race_down():
    for i in range(9, -1, -1):
        print("{} on".format(i))
        led[i].on()
Exemplo n.º 25
0
#!/usr/bin/env python
import sys, errno
from gpiozero import PWMLED
import OSC
import binascii
import struct
import time
import OSC
import os
from bluepy.btle import *

led = PWMLED(13)

ESP_MAC_ADDR = "a4:cf:12:02:c3:6e"
adc_uuid = UUID(0x2A58)
p = Peripheral()

#-------------- init puredata stuff ------------------
os.system('puredata -nogui -audiodev 3 perky-recv-data.pd &')
print "=============="
print "starting PD!!!"
print "=============="
time.sleep(3)
send_address = '127.0.0.1', 9001
c = OSC.OSCClient()
c.connect(send_address)   # localhost, port 9001
oscmsg = OSC.OSCMessage()
oscmsg.setAddress("/pdRecv") #address name is declared in pd patch
sensorVals = [0,0] #X and Y values from fusioned mpu9250

def sendMsg(goData):
Exemplo n.º 26
0
from gpiozero import PWMLED
import time

buzzer = PWMLED(24)
buzzer.value = 0.5
time.sleep(0.02)
buzzer.value = 0
Exemplo n.º 27
0
import threading
from threading import Thread
import Queue 
import datetime

run_on_remote = False
remote_host = '192.168.2.209'
_stop_flag = object()
print("this is being run by ~/.config/autostart/pycar.desktop")



if(run_on_remote):
	print("connecting with remote ... ")
	remote_factory = PiGPIOFactory(host=remote_host)
	left = PWMLED(27, pin_factory=remote_factory) 
	right = PWMLED(22, pin_factory=remote_factory)
	vor = PWMLED(13, pin_factory=remote_factory) 
	back = PWMLED(19, pin_factory=remote_factory) 
	print("connected")
else:
	left = PWMLED(13) 
	right = PWMLED(19)
	vor = PWMLED(22) 
	back = PWMLED(27) 
	control_led = PWMLED(17)
	control_led.on()


#home = 192.168.2.205
#svenja = 192.168.178.41
Exemplo n.º 28
0
from gpiozero import Button, PWMLED
from signal import pause


def say_hello():
    led.pulse()


def say_goodbye():
    led.off()


button = Button(18)
led = PWMLED(17)

button.when_pressed = say_hello
button.when_released = say_goodbye

pause()
Exemplo n.º 29
0
from gpiozero import PWMLED
from time import sleep


led = PWMLED(17)


while True:
    led.value = 0 # off
    sleep(1)
    led.value = 0.5 # half brightness
    sleep(1)
    led.value = 1 # full brightness
    sleep(1)


''' connect BCM-17 to LED positive and -ve to Rapsberri GND [Board pin 3]  '''
Exemplo n.º 30
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from gpiozero import PWMLED
from time import sleep

LED = 4
WAIT_TIME = 1

led = PWMLED(LED)
v = 0.0
dv = 0.1
try:
    for i in range(30):
        led.value = v
        v += dv
        if v > 1.0:
            print('max')
            v = 1.0
            dv = -0.1
        elif v < 0.0:
            print('min')
            v = 0.0
            dv = 0.1
        sleep(WAIT_TIME)
except KeyboardInterrupt:
    print('キャンセルしました')
finally:
    for i in range(3):
        led.value = 1
        sleep(WAIT_TIME / 6)
        led.value = 0
Exemplo n.º 31
0
from gpiozero import PWMLED

ledR = PWMLED(16)
ledG = PWMLED(20)
ledB = PWMLED(21)

# 0 > 0
# 1 > 255

ledR.value = 1  # off
ledG.value = 0.1  # off
ledB.value = 0.5  # off
Exemplo n.º 32
0
class PomodoroTimer(object):
    def __init__(self):
        self.timer = None
        self.led = PWMLED(LIGHT_PIN)
        self.buzzer = TonalBuzzer(BUZZER_PIN)

    def times_up(self):
        print("Time's up")
        self.fin()

    def start_pomodoro(self, channel):
        print("Start Pomodoro")
        self.led.blink(on_time=0.3, off_time=0.3, n=5, background=True)

        if (self.timer != None):
            print("Pomodoro was re-started")
            self.timer.cancel()

        self.timer = Timer(5, self.times_up)
        self.timer.start()

    def play_note(self, note, duration=0.04):
        self.buzzer.play(Tone.from_note(note))
        sleep(duration)
        self.buzzer.stop()

    def ending_music(self):
        # Available Range
        # A3, B3, C4, D4, E4, F4, G4, A4, B4
        arpeggio = [
            "A#3",
            "C#4",
            "E#4",
            "A#3",
            "C#4",
            "E#4",
            "A#3",
            "C#4",
            "E#4",
            "A#3",
            "C#4",
            "E#4",
            "A3",
            "C4",
            "E4",
            "A3",
            "C4",
            "E4",
            "A3",
            "C4",
            "E4",
            "A3",
            "C4",
            "E4",
            "C4",
            "E4",
            "G4",
            "C4",
            "E4",
            "G4",
            "C4",
            "E4",
            "G4",
            "C4",
            "E4",
            "G4",
            "Cb4",
            "Eb4",
            "Gb4",
            "Cb4",
            "Eb4",
            "Gb4",
            "Cb4",
            "Eb4",
            "Gb4",
            "Cb4",
            "Eb4",
            "Gb4",
            "A#3",
            "C#4",
            "E#4",
            "A#3",
            "C#4",
            "E#4",
            "A#3",
            "C#4",
            "E#4",
            "A#3",
            "C#4",
            "E#4",
            "A3",
            "C4",
            "E4",
            "A3",
            "C4",
            "E4",
            "A3",
            "C4",
            "E4",
            "A3",
            "C4",
            "E4",
        ]

        for note in arpeggio:
            self.play_note(note)

        self.play_note("A3", duration=0.2)

    def fin(self):
        self.led.pulse()
        self.ending_music()
        self.led.off()

    def run(self):
        self.button = Button(BUTTON_PIN, pull_up=False)
        self.button.when_pressed = self.start_pomodoro

        pause()
Exemplo n.º 33
0
#!/usr/bin/python3

from os import open, read, close, O_RDONLY
from gpiozero import PWMLED
from signal import pause
from time import sleep

directorio='/tmp/miriadax/'
archivo=directorio+'led.state'


#RGB led with pwm values
rojo=PWMLED(27,active_high=False)
verde=PWMLED(18,active_high=False)
azul=PWMLED(23,active_high=False)

while True:
    # open the file with the led state // abre el fichero con el estado del led
    file=open(archivo,O_RDONLY)
    # read the file with the led state and save it in var 'state'
    # lee el fichero con el estado del led y lo almacena en 'state'
    # *****
    # value is stored as 3 number from 000 to 255 for R G B
    # el valor esta almacenado en 3 numero de 000 a 255 para los valores de R G B
    for i in range(3):
        state=read(file,3) # read 3 char from file from the las position //leemos 3 caracteres del fichero desde la ultima posicion
        state=int(state) # pasamos a entero el numero
        if i==0:
            #red led value
            rojo.value=state/1020
        elif i==1:
Exemplo n.º 34
0
 def __init__(self):
     self.timer = None
     self.led = PWMLED(LIGHT_PIN)
     self.buzzer = TonalBuzzer(BUZZER_PIN)
Exemplo n.º 35
0
from gpiozero import LightSensor, PWMLED
from signal import pause
sensor = LightSensor(18)
led = PWMLED(16)
led.source = sensor
pause()
Exemplo n.º 36
0
def main():
    arduino = initialize_arduino()
    socket = initialize_socket_connection(5000)
    mfc1 = PWMLED(4)
    mfc2 = PWMLED(27)
    mfc3 = PWMLED(22)
    mfc1.value = 0.0
    mfc2.value = 0.0
    mfc3.value = 0.0

    led1, led2 = initialize_led()
    lastLED1sp, lastLED2sp = 0.0, 0.0
    lastMFC1sp, lastMFC2sp, lastMFC3sp = 0.0, 0.0, 0.0
    last_motor_target = 800000
    runstate = 1
    try:
        while True:
            item = poll_socket(socket)
            print(item)
            runstate, setpoints = split_data(item)
            if runstate == 0:
                kill_arduino(arduino)
                led1.value = 0.0
                led2.value = 0.0
                mfc1.value = 0.0
                mfc2.value = 0.0
                mfc3.value = 0.0
                break
            else:
                [motor_target, mfc1_sp, mfc2_sp, mfc3_sp, led1_sp,
                 led2_sp] = setpoints
                if (led1_sp != lastLED1sp) or (led2_sp != lastLED2sp):
                    #led1.value = led1_sp
                    #led2.value = led2_sp
                    lastLED1sp = led1_sp
                    lastLED2sp = led2_sp

                if (mfc1_sp != lastMFC1sp) or (mfc2_sp != lastMFC2sp) or (
                        mfc3_sp != lastMFC3sp):
                    mfc1.value = mfc1_sp
                    mfc2.value = mfc2_sp
                    mfc3.value = mfc3_sp
                    lastMFC1sp = mfc1_sp
                    lastMFC2sp = mfc2_sp
                    lastMFC3sp = mfc3_sp
                if abs(motor_target - last_motor_target) >= 4:
                    print("-")
                    send_to_arduino(arduino, motor_target)
                    last_motor_target = motor_target
    except KeyboardInterrupt:
        kill_arduino(arduino)
        led1.value = 0.0
        led2.value = 0.0
        mfc1.value = 0.0
        mfc2.value = 0.0
        mfc3.value = 0.0
Exemplo n.º 37
0
from gpiozero import LightSensor, PWMLED
from signal import pause

sensor = LightSensor(18)
led = PWMLED(16)

led.source = sensor.values

pause()
Exemplo n.º 38
0
# GPIO pints are digital, so you can only set outputs to high or low, or read inputs as high or low
# using an ADC chip (Analogue-to-Digital converter) you can read the value of analogue input devices like potentiometers

# analogue values are communicated to the Pi using the SPI protocol

# open a terminal window and install spidev package

### sudo apt-get install python3-spidev python-spidev

### open Raspberry Pi Configuration from main menu and enable "SPI" in the Interfaces tab

from gpiozero import MCP3008

pot = MCP3008(0)

# print(pot.value) # try to read potentiometer's value

### next, add an LED to your breadboard and wire it to the Pi, connecting it to GPIO pin 21

from gpiozero import PWMLED  # lets you control the brightness of an LED using PWM (pulse-width modulation)

led = PWMLED(21)

led.source = pot.values  # turn the dial to change the LED brightness!
Exemplo n.º 39
0
Arquivo: led.py Projeto: Kasamens/GPIO
from gpiozero import PWMLED
from signal import pause
from time import sleep

red_led = PWMLED(17)

amber_led = PWMLED(22)

green_led = PWMLED(27)

while True:
	red_led.value = 1
	sleep(1)
	red_led.value = 0
	green_led.value = 1
	sleep(3)
	green_led.value = 0
	amber_led.value = 1
	sleep(1)
	amber_led.value = 0

Exemplo n.º 40
0
#旋转编码器

import time
import datetime
import RPi.GPIO
from gpiozero import PWMLED

#接受编码器针脚编号设置
encoderOUTA=27
encoderOUTB=17
encoderOUTZ=26

# LED0 指示灯 
LED0=10
led0=PWMLED(LED0) 

# setup GPIO triggered  记录按钮输入状态(是否按下)
eA_triggered= False
eB_triggered= False
eZ_triggered= False

#设置针脚编号方式
RPi.GPIO.setmode(RPi.GPIO.BCM)

#设置输入针脚
RPi.GPIO.setup(encoderOUTA, RPi.GPIO.IN,pull_up_down=RPi.GPIO.PUD_DOWN)
RPi.GPIO.setup(encoderOUTB, RPi.GPIO.IN,pull_up_down=RPi.GPIO.PUD_DOWN)
RPi.GPIO.setup(encoderOUTZ, RPi.GPIO.IN,pull_up_down=RPi.GPIO.PUD_DOWN)

#设置输出针脚
Exemplo n.º 41
0
from gpiozero import PWMLED
from time import sleep
red = PWMLED(5)
while True:
    for x in range(101):
        red.value = x * 0.01
        sleep(0.02)
    for x in range(100, -1, -1):
        red.value = x * 0.01
        sleep(0.02)
Exemplo n.º 42
0
from gpiozero import PWMLED
from signal import pause
from time import sleep
import random

led_blue = PWMLED(5)
led_yellow = PWMLED(6)
led_red = PWMLED(13)
led_white = PWMLED(19)
led_green = PWMLED(26)

led_blue.pulse()
sleep(random.uniform(.1, 1.))
led_yellow.pulse()
sleep(random.uniform(0.1, 1.0))
led_red.pulse()
sleep(random.uniform(0.1, 1.0))
led_white.pulse()
sleep(random.uniform(0.1, 1.0))
led_green.pulse()
sleep(random.uniform(0.1, 1.0))

pause()
Exemplo n.º 43
0
from gpiozero import PWMLED, MCP3008
from signal import pause

led = PWMLED(17)
pot = MCP3008()

led.source = pot.values

pause()
Exemplo n.º 44
0
#sudo pip install gpiozero

from gpiozero import LED
from gpiozero import PWMLED
from time import sleep

l1 = LED(17)
l2 = LED(18)
l3 = PWMLED(19)
l4 = LED(20)

l4.on()

l1.on()
sleep(1)

l2.on()
sleep(1)

l3.pulse()
sleep(1)

l1.off()
sleep(1)

l1.off()
sleep(1)

#l3.off()
#sleep(1)