예제 #1
0
import time
import math
import pyaudio
from numpy import linspace, sin, pi, int16
from gpiozero import MCP3008


def proper_round(num, dec=0):
    num = str(num)[:str(num).index('.') + dec + 2]
    if num[-1] >= '5':
        return float(num[:-2 - (not dec)] + str(int(num[-2 - (not dec)]) + 1))
    return float(num[:-1])


# Get readings from MCP3008 channels
pot_1 = MCP3008(channel=0)
pot_2 = MCP3008(channel=1)
pot_3 = MCP3008(channel=2)
pot_4 = MCP3008(channel=4)

pa = None
s = None


def init_audio(rate=8000):
    global pa, s
    print "init_audio: Create PyAudio object"
    pa = pyaudio.PyAudio()
    print "init_audio: Open stream"
    s = pa.open(output=True,
                channels=1,
예제 #2
0
from gpiozero import RGBLED, MCP3008
from gpiozero.tools import zip_values
from signal import pause

led = RGBLED(2, 3, 4)
red_pot = MCP3008(0)
green_pot = MCP3008(1)
blue_pot = MCP3008(2)

led.source = zip_values(red_pot, green_pot, blue_pot)

pause()
예제 #3
0
from gpiozero import MCP3008
from time import sleep

if __name__ == "__main__":
    channel0 = MCP3008(0)
    while (True):
        value = channel0.value
        print("now value:{}".format(value))
        sleep(1)
예제 #4
0
#!/usr/bin/env python

from gpiozero import MCP3008, PWMLED
from time import sleep
pot = MCP3008(0)
ldr = MCP3008(1)
temp1 = MCP3008(2)
temp2 = MCP3008(3)

led = PWMLED(21)
while True:
    T = 15 * temp1.raw_value - 2048
    T2 = 15 * temp2.raw_value - 2048

    whole = T / 100
    fract = T % 100
    whole2 = (T2 / 100) + 5
    fract2 = T2 % 100

    if (fract < 10):
        print("Temp1: {}.{}".format(whole, 0))
    else:
        print("Temp1: {}.{}".format(whole, fract))

    if (fract2 < 10):
        print("Temp2: {}.{}".format(whole2, 0))
    else:
        print("Temp2: {}.{}".format(whole2, fract2))

    print("pot:{:.2f} ldr:{:.2f} temp1:{:.2f}".format(pot.raw_value, ldr.value,
                                                      T))
예제 #5
0
 def __init__(self) -> None:
     try:
         self._adc = MCP3008(channel=0, max_voltage=5)
     except BadPinFactory:
         self._adc = None
         logger.warning("No spi device found in gpio")
예제 #6
0
import sys
from gpiozero import MCP3008
import time

threshold = 0.6
source = sys.argv[1]

def check(pinList):
  for i, p in enumerate(pinList):
    if p.value > threshold:
      return i
  return len(pinList)

if source == "usb":
  pList = [MCP3008(0), MCP3008(1), MCP3008(2)]
else:
  pList = [MCP3008(3), MCP3008(4), MCP3008(5), MCP3008(6)]

time.sleep(1)
print(check(pList))



예제 #7
0
middle_finger = Button(19)
ring_finger = Button(20)
pinky_finger = Button(21)

# Test procedure for the keyboard buttons
test_buttons = False
if test_buttons:
    while True:
        print("Tbot:{}/Ttop:{}/Trih:{}/Idx:{}/Mid:{}/Rng:{}/Pnk:{}".format(
            thumb_bottom.value, thumb_top.value, thumb_right.value,
            index_finger.value, middle_finger.value, ring_finger.value,
            pinky_finger.value))
        time.sleep(0.2)

# Define potentiometers
pot0 = MCP3008(channel=2)
pot1 = MCP3008(channel=1)
pot2 = MCP3008(channel=0)

# Turn the light on
led_purple = LED(24)
led_purple.on()


def play_note(note):
    fs.noteon(0, note, 60)


def shutdown():
    global stop_main_loop
#based on Tony DiCola's NeoPixel library strandtest example

#import necessary libraries
from rpi_ws281x import *
from time import sleep
from gpiozero import Button, MCP3008

# LED strip configuration
LED_COUNT = 20  #number of LED pixels
LED_PIN = 18  #GPIO pin connected to the pixels (must support PWM!)
LED_FREQ_HZ = 800000  #LED signal frequency in hertz (usually 800khz)
LED_DMA = 5  #DMA channel to use for generating signal (try 5)
LED_INVERT = False  #set True to invert the signal

#create pot objects to refer to MCP3008 channel 0 and 1
pot_brightness = MCP3008(0)
pot_speed = MCP3008(1)

#connect pushbutton to GPIO pin 2, pull-up
button_start = Button(2)

#animation running control variable
running_animation = False


#generate rainbow colors across 0-255 positions
def wheel(pos):
    if pos < 85:
        return Color(pos * 3, 255 - pos * 3, 0)
    elif pos < 170:
        pos -= 85
예제 #9
0
#!/usr/bin/python3
from gpiozero import MCP3008
import time
import urllib3

# The LED Strip server
LEDStripServer = '192.168.13.181'
LEDStripPort = '5000'
LEDStripColourURL = "http://%s:%s/colour" % (LEDStripServer, LEDStripPort)

http = urllib3.PoolManager()

red = MCP3008(channel=0, device=0)
green = MCP3008(channel=1, device=0)
blue = MCP3008(channel=2, device=0)

while True:
    r = int(red.value * 255)
    g = int(green.value * 255)
    b = int(blue.value * 255)

    print('Red: ', r)
    print('Green: ', g)
    print('Blue: ', b)
    req = http.request('GET',
                       LEDStripColourURL,
                       fields={
                           'r': r,
                           'g': g,
                           'b': b
                       })
예제 #10
0
from gpiozero import MCP3008, PWMOutputDevice
from time import sleep
from signal import pause

pot = MCP3008(channel=0, clock_pin=11, mosi_pin=10, miso_pin=9, select_pin=8)

led_pin = PWMOutputDevice(7)

while True:
    pot_value = pot.raw_value / 1023
    led_pin.value = pot_value

    print(pot_value)

    sleep(0.1)
예제 #11
0
from gpiozero import MCP3008
from time import sleep
import numpy as np

pot = MCP3008(channel=0)
pot1 = MCP3008(channel=1)

arc = open("integrado.txt", "w")

while True:
    print(pot.value)
    print(pot1.value)
    arc.write(str(pot.value) + '\n')
    arc.write(str(pot1.value))
    arc.write(", ")
    print("")
    sleep(0.5)

arc.close()
예제 #12
0
import argparse
import RPi.GPIO as GPIO
from gpiozero import MCP3008
from time import sleep

parser = argparse.ArgumentParser(description='Read values from MCP3008 chip')
parser.add_argument('channels',
                    metavar='N',
                    type=int,
                    nargs='+',
                    help='the channels to read')
args = parser.parse_args()

values = []
# retrieve each value from the required ADC pins
# for each pin, read 50 values then get the average of the range
# without the first and last 10 values
for c in args.channels:
    dev = MCP3008(c)
    a = []
    for i in range(0, 50):
        a.append(dev.value * 100)
    s = sorted(a)[10:41]
    av = sum(s) / float(len(s))
    values.append(av)

# return the values to the calling function
print("\t".join(map(str, values)))
예제 #13
0
    1.10: 90.0,
    1.36: 157.5,
    1.73: 135.0,
    2.02: 202.5,
    2.18: 180.0,
    2.53: 22.5,
    2.65: 45.0,
    2.89: 247.5,
    2.93: 225.0,
    3.02: 337.5,
    3.11: 0.0,
    3.15: 292.5,
    3.20: 315.0,
    3.25: 270.0,
}
adc_0 = MCP3008(channel=0)
wind = round(adc_0.value * 3.3, 2)
if wind < 0.7 and wind >= 3.3:
    wind_dir = None
else:
    wind_dir = volts.get(wind) or volts[min(volts.keys(),
                                            key=lambda k: abs(k - wind))]

adc_1 = MCP3008(channel=1)
uv = adc_1.value * 3.3

(pm25, aqi25), (pm10, aqi10) = get_particle_measure()

date = datetime.datetime.utcnow()
json_body = {
    "measurement": "sensores",
예제 #14
0
from gpiozero import MCP3008
import time

ldr = MCP3008(channel=5)
ldb = MCP3008(channel=4)

while True:
    val1 = int((ldr.raw_value / 1023) * 1000)
    val2 = int((ldb.raw_value / 1023) * 1000)
    print("Value: ", val1, "|", val2)
    volt1 = ldr.voltage
    volt2 = ldb.voltage
    print("Volta: %.2f | %.2f" % (volt1, volt2))
    wert1 = int(ldr.value * 100)
    wert2 = int(ldb.value * 100)
    print("Perce: ", wert1, " | ", wert2)
    time.sleep(.5)
    print()
def turn(mode, delay, del2):

    sensitivity = 0.9

    steps = 200
    DIR = 20  #GPIO pin DIR
    STEP = 21  #GPIO pin STEP
    STATE = 16  #GPIO pin SLEEP
    SLEEP = 0
    WORK = 1
    CW = 1
    CCW = 0
    steps *= mode
    GPIO.setwarnings(False)
    GPIO.cleanup()
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(DIR, GPIO.OUT)
    GPIO.setup(STEP, GPIO.OUT)
    GPIO.setup(STATE, GPIO.OUT)
    GPIO.output(DIR, CW)
    GPIO.output(STATE, WORK)

    MODE = (17, 27, 22)
    GPIO.setup(MODE, GPIO.OUT)

    RESOLUTION = {
        1: (0, 0, 0),
        2: (1, 0, 0),
        4: (0, 1, 0),
        8: (1, 1, 0),
        16: (0, 0, 1),
        32: (1, 0, 1)
    }
    GPIO.output(MODE, RESOLUTION[mode])
    res = MCP3008(0)

    points = list()
    for x in range(steps):
        GPIO.output(STEP, GPIO.HIGH)
        sleep(delay)
        GPIO.output(STEP, GPIO.LOW)
        sleep(delay)
        sleep(del2)
        print(x)

    sleep(0.5)

    str = res.value
    calibrate = True
    if str > sensitivity:
        calibrate = False

    lost_steps = 0

    while calibrate:
        lost_steps += 1
        GPIO.output(STEP, GPIO.HIGH)
        sleep(delay)
        GPIO.output(STEP, GPIO.LOW)
        sleep(delay)
        sleep(del2)
        str = res.value
        if str > sensitivity:
            print("zgubiono %d moc %f" % (lost_steps, str))
            break
        lost_steps += 1

    sleep(0.5)

    GPIO.output(DIR, CCW)
    for x in range(steps):
        GPIO.output(STEP, GPIO.HIGH)
        sleep(delay)
        GPIO.output(STEP, GPIO.LOW)
        sleep(delay)

    GPIO.output(STATE, SLEEP)
    GPIO.cleanup()
    return points
예제 #16
0
from gpiozero import MCP3008
from time import sleep

pot1 = MCP3008(channel=0)
pot2 = MCP3008(channel=1)
pot3 = MCP3008(channel=2)
pot4 = MCP3008(channel=3)

while True:
    print("Pot1:{:.2f} Pot2:{:.2f} Pot3:{:.2f} Pot4:{:.2f}".format(pot1.value,pot2.value,pot3.value,pot4.value))
    sleep(1.0)
        
예제 #17
0
 def __init__(self):
     super(Signal2Rpi, self).__init__()
     self.GPIOPinNumber = 0
     self.SamplePeriod = float(1.0 / self.SamplingFrequency)
     self.GPIOPin = MCP3008(self.GPIOPinNumber)
예제 #18
0
from gpiozero import MCP3008, LED
from time import sleep

pot = MCP3008(0)  # Pot is connected to CH0
ldr = MCP3008(1)  # LDR is connected to CH1
led1 = LED(21)

thresh = 0.5  # set threshold level to differentiate between light and dark

while True:
    print("Pot:{:.2f}  LDR:{:.2f}".format(pot.value, ldr.value))
    sleep(0.5)
    if ldr.value < thresh:
        led1.on()
    else:
        led1.off()
예제 #19
0
from gpiozero import MCP3008
from time import sleep
from neopixel import Adafruit_NeoPixel

r = MCP3008(channel=0)
g = MCP3008(channel=1)
b = MCP3008(channel=2)
LEDS = 12
PIN = 18

strip = Adafruit_NeoPixel(LEDS, PIN)
strip.begin()

while True:
    red = round(r.value * 255)
    green = round(g.value * 255)
    blue = round(b.value * 255)
    print(red, green, blue)
    for i in range(LEDS):
        strip.setPixelColorRGB(i, red, green, blue)
        strip.show()
    sleep(0.1)
예제 #20
0
파일: RTD.py 프로젝트: gcfc/wafersat-public
Note that this file assumes that all 8 channels are functioning and connected 
to RTDs. If not all channels are being used, specify how many channels are 
being used in the plot_temp function and make sure your circuit is only using 
the first i channels on the MCP3008, where i is the number of desired channels.
"""

from gpiozero import LED, MCP3008
from time import sleep
import csv
import pylab as plt

led = LED(15)

RTD0 = MCP3008(channel=0,
               clock_pin=18,
               mosi_pin=24,
               miso_pin=23,
               select_pin=25)
RTD1 = MCP3008(channel=1,
               clock_pin=18,
               mosi_pin=24,
               miso_pin=23,
               select_pin=25)
RTD2 = MCP3008(channel=2,
               clock_pin=18,
               mosi_pin=24,
               miso_pin=23,
               select_pin=25)
RTD3 = MCP3008(channel=3,
               clock_pin=18,
               mosi_pin=24,
예제 #21
0
import time, socket, pickle
from gpiozero import MCP3008, Servo, MotionSensor
import sys


divider = MCP3008(0)
servo = Servo(17,1)
pir = MotionSensor(13)


close_state=True
print("done")

try:
    while True:
        print(divider.value)
        if pir.motion_detected:
            
            print("Motion detected!")
            if close_state:
                print("Close State = True")
                close_state=False
                servo.min()
                time.sleep(4.5)
            else:
                print("Close State = False")
                close_state=True
                servo.max()
                time.sleep(4.5)
            
        time.sleep(0.5)
예제 #22
0
#!/usr/bin/env python

import time
from gpiozero import MCP3008

ai0 = MCP3008(0)
#ai1 = MCP3008(1)

while True:
    #print("Resistive Sensor: ",  ai1.value)
    print("Capacitive Sensor: ", ai0.value)
    print('\n')
    time.sleep(1)
예제 #23
0
# -*- coding: utf-8 -*-
from gpiozero import MCP3008
from time import sleep
higro = MCP3008(1) # Atribui o canal 1 para esta leitura

while True:
      # Normalizei a escala onde 0 é completamente seco 
      # e 100 é completamente molhado
      higro_perc = (1 - higro.value) * 100
      tensao = (higro.value * 5.0) / 255.0
      print('Valor lido:', higro.value)
      print('Tensao no pino:', tensao)
      print('Umidade do Solo {0}%',higro_perc)
      sleep(1)   # executa 1 leitura nova a cada segundo


예제 #24
0
from gpiozero import Servo, MCP3008
import board
import neopixel
from time import sleep
from colorwheel import wheel

# Set up potentiometer
pot = MCP3008(channel=0)

# Set up servo
servo = Servo(21)

# Set up NeoPixel
pixel_pin = board.D18
num_pixels = 1

pixels = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.2)


def map_values(x, a, b, c, d):
    """Maps value range from input to output."""
    y = (x - a) / (b - a) * (d - c) + c
    return y


while True:
    potReading = pot.value
    servoSetting = map_values(potReading, 0.0, 1.0, -1.0, 1.0)

    ########
    # Calculate hue here
예제 #25
0
from __future__ import division
import pygame
import time
import os
import sys
from gpiozero import MCP3008
import RPi.GPIO as GPIO

#GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

#sensoren
sL = MCP3008(1)
sR = MCP3008(3)

#pygame en screen init
pygame.init()
windowInfo = pygame.display.Info()
screen_size = (windowInfo.current_w,windowInfo.current_h)
screen_w = windowInfo.current_w
screen_h = windowInfo.current_h
screen_ratio = int(screen_w / screen_h)
#screen_size = (1920,800)            #voor testen met andere schermresolutie
#screen_w = 1920                     #voor testen met andere schermresolutie
#screen_h = 800                      #voor testen met andere schermresolutie
myfont = pygame.font.SysFont("monospace", int(screen_h/25))

#vaste variable
stap_lock = "Rechts"
key_Check= True
예제 #26
0
from gpiozero import MCP3008
from smbus import SMBus

from modules.pwm import PWM_led
from modules.rgb import RGB_led
#from modules.lcd import LCD


spi = spidev.SpiDev()
btn = 9 #pinnummer aanpassen
rgbled = RGB_led(5, 6, 13)

spi.open(0, 0)  # BUS SPI0, slave on CE 0
spi.max_speed_hz = 10 ** 5  # 100 KHz

potX = MCP3008(0)
potY = MCP3008(1)
i2c = SMBus(1)

btnAmt = 0
lcdStat = 1


#functions --------------------------------------------------------------------------------------------------------------------

def setupGPIO():
    GPIO.setmode(GPIO.BCM)

    GPIO.setup(btn, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.add_event_detect(btn, GPIO.FALLING, callback=btn_handler, bouncetime=50)
    GPIO.add_event_callback(btn, btn_handler)
예제 #27
0
from gpiozero import MCP3008
from time import sleep


def convert_temp(gen):
    for value in gen:
        yield (value * 3.3) * 100


adc = MCP3008(channel=0)

for temp in convert_temp(adc.values):
    print('The temperature is', temp, 'C')
    sleep(0.4)
import RPi.GPIO as GPIO
import time
from gpiozero import MCP3008

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
red = 23
GPIO.setup(red, GPIO.OUT)

mcp3008_channel_0 = MCP3008(channel=0, device=0)
p = GPIO.PWM(red, 50)  # channel=23 frequency=50Hz
p.start(0)  # dc=0

while True:
    potmeter = int(mcp3008_channel_0.value *100)
    print(potmeter) 
    p.ChangeDutyCycle(potmeter)
    time.sleep(0.250)
예제 #29
0
from gpiozero import PWMLED, MCP3008
from time import sleep

pot = MCP3008(0)
led = PWMLED(17)

while True:
   print(pot.value)
   print("-------")
   if (pot.value < 0.002):
      led.value = 0
   else:
      led.value = pot.value

print(pot.value)
sleep(0.1)
예제 #30
0
from common import config
from common.logs import MAIN as logger
from pigpio_dht import DHT11
from gpiozero import MCP3008, DigitalOutputDevice

try:
    TEMP_HUMD_SENSOR = DHT11(config.DHT11_PIN)
    MOISTURE_SENSOR = MCP3008(channel=config.MCP3008_CHANNEL)
    MOISTURE_SENSOR_POWER = DigitalOutputDevice(config.MCP3008_POWER_PIN)

    FAN_RELAY = DigitalOutputDevice(config.FAN_RELAY_PIN,
                                    active_high=False,
                                    initial_value=False)
    LIGHT_RELAY = DigitalOutputDevice(config.LIGHT_RELAY_PIN,
                                      active_high=False,
                                      initial_value=False)
    WATER_RELAY = DigitalOutputDevice(config.WATER_RELAY_PIN,
                                      active_high=False,
                                      initial_value=False)
except Exception as e:
    logger.error("Hardware doesn't start properly: %s", e)