コード例 #1
0
def get_mcp():
    """
    Instanziiert ein MCP-Objekt (Analog-Digital-Konverter)
    """
    return Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))
コード例 #2
0
code_time = [1.0433349609375, 1.035263967514038, 1.5382449626922607
             ]  #timing requiredments for thw above hardcoded combination
Lock_state = 1  #used to track where the lock is locked or unlocked -> at startup its locked
sline_pressed = 0
###############################################################################################
#					SPI SETUP					      #
###############################################################################################
#Set pin definitions for SPI								      #
SPICLK = 11  #
SPIMISO = 9  #
SPIMOSI = 10  #
SPICS = 8  #
#
#
mcp = Adafruit_MCP3008.MCP3008(clk=SPICLK,
                               cs=SPICS,
                               mosi=SPIMOSI,
                               miso=SPIMISO)  #

#
###############################################################################################


###############################################################################################
#                                       	MAIN					      #
###############################################################################################
def main():
    try:
        # initialization of ADC and pushbuttons
        GPIO.setmode(GPIO.BCM)
        init_pushbuttons()  #intialize pushbuttons
        init_event_detect()  #intialize interuppts for pushbuttons
コード例 #3
0
ファイル: V18Tja.py プロジェクト: paloskar/RIMEPHAS_test
#import picamera
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008

from irSensorClass import irSensor

# Software SPI configuration:
CLK = 18
MISO = 23
MOSI = 24
CS = 25

numSensors = 3
sensorThreshold = 1.5

ADC = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI)

irSensors = irSensor(ADC, numSensors, sensorThreshold)

thresholdValue = irSensors.initSensors()

##########  Settings  ##########
wizardOfOz = True
largeScreen = True
size = (800, 480)
largeSize = (800, 1280)
if largeScreen:
    screenSize = largeSize
    moveScreen = (largeSize[0] - size[0]) / 2
else:
    screenSize = size
コード例 #4
0
 def __init__(self, clock, d_out, d_in, cs):
     self.mcp = Adafruit_MCP3008.MCP3008(clk=clock,
                                         cs=cs,
                                         miso=d_out,
                                         mosi=d_in)
コード例 #5
0
#Constants for voltage estimate
railVoltage = 3.325
adcQuantizations = 2**10  #10 Bit Chip
convFactor = railVoltage / adcQuantizations

# Software SPI configuration:
#CLK  = 18
#MISO = 23
#MOSI = 24
#CS   = 25
#mcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI)

# Hardware SPI configuration:
SPI_PORT = 0
SPI_DEVICE = 0
mcp = Adafruit_MCP3008.MCP3008(
    spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=3900000))
#Note that we have set the clock speed higher than the stock examples.
#The ADC chip datasheet quotes a 3.9MHz Clock speed if Vdd is set to 5V.
#The closest convenient SPI frequency is 3.9MHz

#Lists keeping track of data coming from ADC as well as time stamps
graph_t, graph_y = [], []

#Start time
t0 = time.time()

print('Reading MCP3008 values, press Ctrl-C to quit...')

# Main program loop.

try:
コード例 #6
0
import RPi.GPIO as GPIO
import time
from random import randint
# next two libraries must be installed IAW appendix instructions
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008
global pwmL, pwmR, fitA, fitB, fitC, pwrThreshold, mcp
# Hardware SPI configuration:
SPI_PORT   = 0
SPI_DEVICE = 0
mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))
# initial fitness values for each of the 3 activities
fitA = 20
fitB = 20
fitC = 20
#initial pwrThreshold
pwrThreshold = 500 # units of milliwatts
# use the BCM pin numbers
GPIO.setmode(GPIO.BCM)
# setup the motor control pins
GPIO.setup(18, GPIO.OUT)
GPIO.setup(19, GPIO.OUT)
pwmL = GPIO.PWM(18,20) # pin 18 is left wheel pwm
pwmR = GPIO.PWM(19,20) # pin 19 is right wheel pwm
# must 'start' the motors with 0 rotation speeds
pwmL.start(2.8)
pwmR.start(2.8)
 
# ultrasonic sensor pins
TRIG = 23 # an output
コード例 #7
0
import RPi.GPIO as GPIO
コード例 #8
0
ファイル: py_component.py プロジェクト: Tubbz-alt/Cubium
import sys
sys.path.insert(0, 'Cubium/drivers/PythonDrivers')

import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008
import time
import math

SPI_PORT = 0
SPI_DEVICE = 0

analogTempFloor = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))

A = 0.002197222470870
B = 0.000161097632222
C = 0.000000125008328

PIN = 5

#implementation found here: https://bitbucket.org/pschow/rpiadctherm/src/dbfe8101eeb4/basiclogmcp.py?at=master&fileviewer=file-view-default

def handleSpaData():
    pass

def sendData():
    time.sleep(1)
    
    value = analogTempFloor.read_adc(PIN)
    volts = (value*3.3)/1024
    ohms = ((1/volts)*3300)-1000
コード例 #9
0
    def start(self):
        global adc_results
        date_time = datetime.datetime.now()
        self.mcp = Adafruit_MCP3008.MCP3008(clk=CLK,
                                            cs=CS,
                                            miso=MISO,
                                            mosi=MOSI)

        # Read all the ADC channel values in a list.
        values = [0] * 8
        try:
            for i in range(8):
                # The read_adc function will get the value of the specified channel (0-7).
                values[i] = self.mcp.read_adc(i)
            # Print the ADC values.
            # print('| {0:>4} | {1:>4} | {2:>4} | {3:>4} | {4:>4} | {5:>4} | {6:>4} | {7:>4} |'.format(*values))
            #print('| {0:>4} | {1:>4} |'.format(values[0],values[7]))
            concentration = 5000 / 496 * values[0] - 1250
            print("|{}|\n".format(concentration))
            # Pause for half a second.
            uv_index = values[7]
            results = []
            results.append(date_time)
            results.append(concentration)
            # results.append(uv_index)

            adc_results.writerow(results[:])

            self.merge_test = False
            self.add_data(self.CO2_queue, self.CO2_error, self.CO2_list,
                          concentration)
            #self.add_data(self.UV_queue,self.UV_list,uv_index)
            self.add_time(self.time_queue, self.time_list, date_time)

            if self.merge_test == True:
                self.CO2_list = []
                #self.UV_list=[]
                self.time_list = []
            if self.first_data and len(self.CO2_queue) != 0:
                for i in range(len(self.CO2_queue)):
                    data = []
                    data.append(self.time_queue[i])
                    data.append(self.CO2_queue[i])
                    data.append(self.CO2_err[i])
                    results.writerow(data)

                self.last_time = data[0]
                self.first_data = False
            elif not self.first_data:
                try:
                    print(self.last_time)
                    if self.time_queue[-1] != self.last_time:
                        data = []
                        data.append(self.time_queue[-1])
                        data.append(self.CO2_queue[-1])
                        data.append(self.CO2_err[-1])
                        results.writerow(data)

                        self.last_time = self.time_queue[-1]
                    else:
                        print('duplicated data.')
                except IndexError:
                    print('No new data being written.')
            else:
                print('No data acquired yet.')

        except:
            print("CO2 sensor error\n\n")
コード例 #10
0
 def __init__(self):
     self.o_AdcDevice = Adafruit_MCP3008.MCP3008(
         spi=SPI.SpiDev(configs.i_SPIDevice, configs.i_SPIPort))
コード例 #11
0
    ##PWM output configuration
GPIO.setmode(GPIO.BOARD)
GPIO.setup(18, GPIO.OUT)
pwm = GPIO.PWM(18, 50)  ##Pin 18, 50Hz
dc = 6.4 ##Leveled
pwm.start(dc)

    ##Debugging LED configuration
GPIO.setup(7, GPIO.OUT)
GPIO.output(7, GPIO.HIGH) ##LED
time.sleep(0.5)

   ## Hardware SPI configuration:
SPI_PORT   = 0
SPI_DEVICE = 0
mcp3008 = MCP3008lib.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))
    #---------------------------#

###########GLOBAL VARIABLES##########
   ## ADC analog channel. From 0 to 7
ch = 0
   ## Sample time (in seconds)
Ts = 0.06
   ## Posizio kontsigna (cm)
kontsigna = 25

dc=6.4
   ## PID balioak
global Kp
Kp=15
global Ki
コード例 #12
0
DEFAULT_PROTOCOL = 'new'

DEFAULT_INTERVAL_NORMAL = 300
DEFAULT_INTERVAL_TEST = 30
DEFAULT_MAX_ACCUM_TIME = 3600
FLUSH_PAUSE_S = 2

DEFAULT_INTERVAL_NORMAL_D3S = 300
DEFAULT_INTERVAL_TEST_D3S = 30
DEFAULT_D3STEST_TIME = 5
D3S_LED_BLINK_PERIOD_INITIAL = 0.75
D3S_LED_BLINK_PERIOD_DEVICE_FOUND = 0.325

CLK, MISO, MOSI, CS = 18, 23, 24, 25
try:
    DEFAULT_CO2_PORT = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI)
except:
    print("No CO2 Sensor setup, proceeding without initializing CO2 Port.")
DEFAULT_INTERVAL_NORMAL_CO2 = 300
DEFAULT_INTERVAL_TEST_CO2 = 30
CO2_VARIABLES = ['CO2 Concentration in ppm', 'UV index']

try:
    DEFAULT_WEATHER_PORT = BME280(t_mode=BME280_OSAMPLE_8, p_mode=BME280_OSAMPLE_8, h_mode=BME280_OSAMPLE_8)
except:
    print("No Weather Sensor setup, proceeding without initializing Weather Port.")
DEFAULT_INTERVAL_NORMAL_WEATHER = 300
DEFAULT_INTERVAL_TEST_WEATHER = 30
WEATHER_VARIABLES = ['temperature', 'pressure', 'humidity']
WEATHER_VARIABLES_UNITS = ['deg C', 'hPa', '%']
コード例 #13
0
ファイル: ada.py プロジェクト: mukaddim98/water-me-device
import RPi.GPIO as GPIO
from time import sleep
import Adafruit_MCP3008

am = Adafruit_MCP3008.MCP3008(clk = 11, cs = 8, miso = 9, mosi = 10)

while True:
  maxVal = 838  
  moisture_value = am.read_adc(0) # Get the analog reading from the soil moist sensor
  per = moisture_value * 100 / maxVal  # Converting the moisture value to percentage
  print("Moisture Value: "+str(moisture_value));
  print("Recorded moisture value is %s percentage" % per)
  if per >= 70:
    print("Stop! I will vomit.")
  elif per < 70 and per >= 30:
      print("Hey, I'm full :D")
  elif per < 30 :
    print("Yo, I'm thirsty!")
  sleep(1.5)
コード例 #14
0
ファイル: main.py プロジェクト: ro-ka/retro-radio
from radio import Radio
from bluetooth import Bluetooth
# from subprocess import call
from time import sleep
import Adafruit_MCP3008

try:
    from gpiozero import Button
    runningOnRaspi = True
except:
    runningOnRaspi = False

VOLUME_CHANNEL = 0
mcp = Adafruit_MCP3008.MCP3008(clk=13, cs=26, miso=25, mosi=9)

mode = None
radio = Radio()
bluetooth = Bluetooth()


def switchToBluetooth():
    global mode
    if mode == "bluetooth":
        return
    mode = "bluetooth"

    print("Load Bluetooth")

    nextButton.when_pressed = None
    prevButton.when_pressed = None
コード例 #15
0
import Adafruit_MCP3008 as MCP
import send_mail

CLK = 18
MISO = 23
MOSI = 24
CS = 25
mcp = MCP.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI)


class Plant:
    def __init__(self, name, recommended_moisture_level,
                 current_moisture_level):
        self.name = name
        self.recommended_moisture_level = recommended_moisture_level
        self.current_moisture_level = current_moisture_level

    def summary(self):
        return ("Your " + self.name + " has a water level of " +
                str(self.current_moisture_level))


plant_ports = {5: "Dill"}


def main():
    port_readings = {5: .2}
    plants = []
    for p in port_readings:
        plant = Plant(plant_ports[p], port_readings[p], mcp.read_adc(p))
        plants.append(plant)
コード例 #16
0
                        metavar='ADCCHANNEL',
                        type=int,
                        help='channel to read from the ADC (0 - 7)',
                        required=False,
                        choices=range(0, 8))
    return parser.parse_args()


if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='MCP3008 Analog-to-Digital Converter Read Test Script')
    args = parse_args(parser)

    # Example Software SPI pins: CLK = 18, MISO = 23, MOSI = 24, CS = 25
    mcp = Adafruit_MCP3008.MCP3008(clk=args.clockpin,
                                   cs=args.cspin,
                                   miso=args.misopin,
                                   mosi=args.mosipin)

    if -1 < args.adcchannel < 8:
        # Read the specified channel
        value = mcp.read_adc(args.adcchannel)
        print("ADC Channel: {chan}, Output: {out}".format(chan=args.adcchannel,
                                                          out=value))
    else:
        # Create a list for the ADC channel values
        values = [0] * 8

        # Conduct measurements of channels 0 - 7, add them to the list
        for i in range(8):
            values[i] = mcp.read_adc(i)
コード例 #17
0
def setupSystem():
    # Setup SPI for Data Collection
    SPI_PORT = 0
    SPI_DEVICE = 0
    mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))
    return mcp
コード例 #18
0
    def __init__(self):
        super(self.__class__, self).__init__()

        self.setupUi(self)  # gets defined in the UI file
        self.threadpool = QThreadPool()
        print("Multithreading with maximum %d threads" % self.threadpool.maxThreadCount())
        #Initial State
        self.manualButton.setChecked(False)
        
        #Listeners
        self.manualButton.toggled.connect(lambda:self.oh_no())
        self.pshBut2.clicked.connect(lambda: self.oh_no())
        self.cSlider.valueChanged.connect(lambda:self.cSliderMoved(self.cSlider.value()))
        self.hSlider.valueChanged.connect(lambda:self.hSliderMoved(self.hSlider.value()))
        self.txtTemp.returnPressed.connect(lambda:self.txtTempChanged(self.txtTemp.text()))
        self.txtFlow.returnPressed.connect(lambda:self.txtFlowChanged(self.txtFlow.text()))
        self.c0.clicked.connect(lambda: self.c0Clicked())
        self.c1.clicked.connect(lambda: self.c1Clicked())
        self.c2.clicked.connect(lambda: self.c2Clicked())
        self.c3.clicked.connect(lambda: self.c3Clicked())
        self.c4.clicked.connect(lambda: self.c4Clicked())
        self.c5.clicked.connect(lambda: self.c5Clicked())
        self.c6.clicked.connect(lambda: self.c6Clicked())
        self.c7.clicked.connect(lambda: self.c7Clicked())
        self.c8.clicked.connect(lambda: self.c8Clicked())
        self.h0.clicked.connect(lambda: self.h0Clicked())
        self.h1.clicked.connect(lambda: self.h1Clicked())
        self.h2.clicked.connect(lambda: self.h2Clicked())
        self.h3.clicked.connect(lambda: self.h3Clicked())
        self.h4.clicked.connect(lambda: self.h4Clicked())
        self.h5.clicked.connect(lambda: self.h5Clicked())
        self.h6.clicked.connect(lambda: self.h6Clicked())
        self.h7.clicked.connect(lambda: self.h7Clicked())
        self.h8.clicked.connect(lambda: self.h8Clicked())
        self.b11.clicked.connect(lambda: self.b11Clicked())
        self.b12.clicked.connect(lambda: self.b12Clicked())
        self.b13.clicked.connect(lambda: self.b13Clicked())
        self.b14.clicked.connect(lambda: self.b14Clicked())
        self.b15.clicked.connect(lambda: self.b15Clicked())
        self.b16.clicked.connect(lambda: self.b16Clicked())
        self.b17.clicked.connect(lambda: self.b17Clicked())
        self.b18.clicked.connect(lambda: self.b18Clicked())
        self.b21.clicked.connect(lambda: self.b21Clicked())
        self.b22.clicked.connect(lambda: self.b22Clicked())
        self.b23.clicked.connect(lambda: self.b23Clicked())
        self.b24.clicked.connect(lambda: self.b24Clicked())
        self.b25.clicked.connect(lambda: self.b25Clicked())
        self.b26.clicked.connect(lambda: self.b26Clicked())
        self.b27.clicked.connect(lambda: self.b27Clicked())
        self.b28.clicked.connect(lambda: self.b28Clicked())
        self.b31.clicked.connect(lambda: self.b31Clicked())
        self.b32.clicked.connect(lambda: self.b32Clicked())
        self.b33.clicked.connect(lambda: self.b33Clicked())
        self.b34.clicked.connect(lambda: self.b34Clicked())
        self.b35.clicked.connect(lambda: self.b35Clicked())
        self.b36.clicked.connect(lambda: self.b36Clicked())
        self.b37.clicked.connect(lambda: self.b37Clicked())
        self.b38.clicked.connect(lambda: self.b38Clicked())
        self.b41.clicked.connect(lambda: self.b41Clicked())
        self.b42.clicked.connect(lambda: self.b42Clicked())
        self.b43.clicked.connect(lambda: self.b43Clicked())
        self.b44.clicked.connect(lambda: self.b44Clicked())
        self.b45.clicked.connect(lambda: self.b45Clicked())
        self.b46.clicked.connect(lambda: self.b46Clicked())
        self.b47.clicked.connect(lambda: self.b47Clicked())
        self.b48.clicked.connect(lambda: self.b48Clicked())
        self.b51.clicked.connect(lambda: self.b51Clicked())
        self.b52.clicked.connect(lambda: self.b52Clicked())
        self.b53.clicked.connect(lambda: self.b53Clicked())
        self.b54.clicked.connect(lambda: self.b54Clicked())
        self.b55.clicked.connect(lambda: self.b55Clicked())
        self.b56.clicked.connect(lambda: self.b56Clicked())
        self.b57.clicked.connect(lambda: self.b57Clicked())
        self.b58.clicked.connect(lambda: self.b58Clicked())
        self.b61.clicked.connect(lambda: self.b61Clicked())
        self.b62.clicked.connect(lambda: self.b62Clicked())
        self.b63.clicked.connect(lambda: self.b63Clicked())
        self.b64.clicked.connect(lambda: self.b64Clicked())
        self.b65.clicked.connect(lambda: self.b65Clicked())
        self.b66.clicked.connect(lambda: self.b66Clicked())
        self.b67.clicked.connect(lambda: self.b67Clicked())
        self.b68.clicked.connect(lambda: self.b68Clicked())
        self.b71.clicked.connect(lambda: self.b71Clicked())
        self.b72.clicked.connect(lambda: self.b72Clicked())
        self.b73.clicked.connect(lambda: self.b73Clicked())
        self.b74.clicked.connect(lambda: self.b74Clicked())
        self.b75.clicked.connect(lambda: self.b75Clicked())
        self.b76.clicked.connect(lambda: self.b76Clicked())
        self.b77.clicked.connect(lambda: self.b77Clicked())
        self.b78.clicked.connect(lambda: self.b78Clicked())
        self.b81.clicked.connect(lambda: self.b81Clicked())
        self.b82.clicked.connect(lambda: self.b82Clicked())
        self.b83.clicked.connect(lambda: self.b83Clicked())
        self.b84.clicked.connect(lambda: self.b84Clicked())
        self.b85.clicked.connect(lambda: self.b85Clicked())
        self.b86.clicked.connect(lambda: self.b86Clicked())
        self.b87.clicked.connect(lambda: self.b87Clicked())
        self.b88.clicked.connect(lambda: self.b88Clicked())
        self.channel = [6,7]
        CLK  = 23
        MISO = 10
        MOSI = 9
        CS   = 11
        self.mcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI)
        #self.potRange = [[65,480],[10,480]]
        self.potRange = [[100,400],[0,204]]
        #180 --> 90
        self.prevPot = [self.scale(self.constrain(self.mcp.read_adc(self.channel[0]),self.potRange[0][0], self.potRange[0][1]), self.potRange[0][0], self.potRange[0][1] ,0, 90),
                        self.scale(self.constrain(self.mcp.read_adc(self.channel[1]),self.potRange[1][0], self.potRange[1][1]), self.potRange[1][0], self.potRange[1][1] ,0, 90)]
        settings.servos[0].movePWM(settings.servos[0].min+1)
        settings.servos[1].movePWM(settings.servos[1].min+1)
コード例 #19
0
 def __init__(self):
     SPI_PORT = 0
     SPI_DEVICE = 0
     self.mcp = Adafruit_MCP3008.MCP3008(
         spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))
コード例 #20
0
class gameController():
    target_state = [
        0
    ] * targetCount  #0=round start, 1 = target ready, 2 =target hit
    prevBtnState = []

    def __init__(self):
        pass

    if (gv.debug):
        playerOneReady = True
        playerTwoReady = True
        targetOne = pygame.K_1
        targetTwo = pygame.K_2
        targetThree = pygame.K_3
        targetFour = pygame.K_4
        targetFive = pygame.K_5
        targetSix = pygame.K_6
    else:
        #Setup the analog reader here
        CLK = 18
        MISO = 23
        MOSI = 24
        CS = 25
        mcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI)
        print("mcp initalized")
        pass
    readyBtn = pygame.K_SPACE
    quitBtn = pygame.K_ESCAPE
    anim_cleared = False

    def continueCheck(self, state):
        keys = pygame.key.get_pressed()
        values = gameController.pollAdc()

        if keys[gameController.readyBtn]:
            changeState(state)
        elif keys[gameController.quitBtn]:
            pygame.quit()
        elif keys[pygame.K_RALT] and keys[pygame.K_RETURN]:
            pygame.display.toggle_fullscreen()

    def checkReady(self, multiPlayerState, singlePlayerState):
        #Get the currently pressed keys
        keys = pygame.key.get_pressed()
        values = gameController.pollAdc()

        #TODO do not start game immediately. show animation like Death Stranding UI for selection structure option
        curBtnState = gameController.getBtnState(values)

        #this is not used
        #deltaBtnState = curBtnState ==  gameController.prevBtnState

        print(curBtnState, gameController.prevBtnState)
        # if prevBtnState is not the same as current

        #increment readystates via detection methods
        if curBtnState == [True, True]:
            #both button pressed
            gv.lightController._pixels.fill((0, 0, 0))
            gameController.anim_cleared = True
            for light in gv.lightsObject.lights:
                light.clearAnim()

            #increment counter and make sure other one is 0'd out
            gv.multiPlayerReadyCount = gv.multiPlayerReadyCount + 1
            gv.singlePlayerReadyCount = 0

            #change player 2 tower to increment lights
            gv.lightController._lights[0].changeInPercSeq(
                Color(255, 0, 0), (gv.multiPlayerReadyCount / waitTime),
                gv.lightController._lights[0], gv.lightController._lights[2])

            #change player 1 tower to increment lights
            gv.lightController._lights[0].changeInPercSeq(
                Color(255, 0, 0), (gv.singlePlayerReadyCount / waitTime),
                gv.lightController._lights[3], gv.lightController._lights[5])

        elif curBtnState == [True, False]:
            #player one button pressed
            gv.lightController._pixels.fill((0, 0, 0))
            gameController.anim_cleared = True
            for light in gv.lightsObject.lights:
                light.clearAnim()
            gv.singlePlayerReadyCount = gv.singlePlayerReadyCount + 1
            gv.multiPlayerReadyCount = 0
            gv.lightController._lights[0].changeInPercSeq(
                Color(0, 255, 40), (gv.singlePlayerReadyCount / waitTime),
                gv.lightController._lights[3], gv.lightController._lights[5])
        elif curBtnState == [False, False] or curBtnState == [False, True]:
            #neutral or 2nd player only button pressed
            gv.singlePlayerReadyCount = 0
            gv.multiPlayerReadyCount = 0
            if gameController.anim_cleared == True:
                gameController.anim_cleared = False
                gv.lightsObject.lights[0].setGlow(500, Color(255, 0, 0),
                                                  'GlowFadeIn')

        #Check for ready button, or ready counts to a specific value
        if keys[gameController.readyBtn]:
            changeState(multiPlayerState)
            gv.next_round_state = "MULTIPLAYER_STATE"
        elif gv.multiPlayerReadyCount >= waitTime:
            gv.multiPlayerReadyCount = 0
            gv.next_round_state = "MULTIPLAYER_STATE"
            changeState(multiPlayerState)
        elif gv.singlePlayerReadyCount >= waitTime:
            gv.singlePlayerReadyCount = 0
            gv.next_round_state = "SINGLE_PLAYER_STATE"
            changeState(singlePlayerState)
        elif keys[gameController.quitBtn]:
            pygame.quit()
        elif keys[pygame.K_RALT] and keys[pygame.K_RETURN]:
            pygame.display.toggle_fullscreen()
        gameController.prevBtnState = curBtnState

    def getBtnState(values):
        retlist = []
        for i in range(6, 8):
            if values[i] < 1015.0 and values[i] > 10.0:
                retlist.append(False)
            else:
                retlist.append(True)
        return retlist

    def readyToHit():
        #1 = target ready
        for i in range(0, targetCount):
            gameController.target_state[i] = 1
            # change target color to hit me mode
            for light in gv.lightController.getLights():
                light.changeAll(0, 255, 0, 1, False)
            gv.lightController._pixels.show()

    def pollAdc():
        #poll the MCP3008 for the actual target readouts
        # signal_reads is # of read cycles to average output
        # sums read values from each channnel on 8pins
        # return is an average read value for each channel
        signal_reads = 1
        values = [0] * 8
        for j in range(0, signal_reads):
            for i in range(8):
                values[i] += gameController.mcp.read_adc(i)
            for i in range(0, 8):
                values[i] = values[i] / (signal_reads * 1.0)
            return values

    #Check to see if any of the targets have been hit
    def checkTargets():
        if (gv.debug):
            #Get the currently pressed keys
            keys = pygame.key.get_pressed()

            if (keys[gameController.targetOne] | keys[gameController.targetTwo]
                    | keys[gameController.targetThree]):
                gv.winner = 1
                return True
            elif (keys[gameController.targetFour]
                  | keys[gameController.targetFive]
                  | keys[gameController.targetSix]):
                gv.winner = 2
                return True
            else:
                # logic for reading signals and toggling target changes
                values = gameController.pollAdc()
                for i in range(0, targetCount):
                    if values[i] > impactThreshold and target_state[i] is 1:
                        target_state[i] = 2
                        # TODO: code to change target color
                        # TODO: check if winner
                        if sum(target_state[0:3]) is 6:
                            gv.winner = 2
                        elif sum(target_state[3:6]) is 6:
                            gv.winner = 1
                return False
        else:
            #setup the system to return true or false based on analog reader
            # logic for reading signals and toggling target changes
            values = gameController.pollAdc()
            #print('| {0:>4} | {1:>4} | {2:>4} | {3:>4} | {4:>4} | {5:>4} | {6:>4} | {7:>4} |'.format(*values))
            #print(gameController.target_state)
            for i in range(0, targetCount):
                if values[i] > impactThreshold and gameController.target_state[
                        i] is 1:
                    gameController.target_state[i] = 2
                    # TODO: code to change target color
                    gv.lightController.getLights()[i].changeAll(
                        0, 0, 255, 1, True)
                    # TODO: check if winner
                    if sum(gameController.target_state[0:3]) is 6:
                        gv.winner = 2
                        return True
                    elif sum(gameController.target_state[3:6]) is 6:
                        gv.winner = 1
                        return True
            pass

    def checkTargetsSingle():
        values = gameController.pollAdc()
        for i in range(0, targetCount):
            if values[i] > impactThreshold and gameController.target_state[
                    i] is 1:
                gameController.target_state[i] = 2

                gv.lightController.getLights()[i].changeAll(0, 0, 255, 1, True)

                if sum(gameController.target_state[0:6]) is 12:
                    gv.winner = 1
                    return True
        pass

    #Check if the players hands are on the button and return true if they remove it early
    def checkHands():
        if (gv.debug):
            keys = pygame.key.get_pressed()
            if (keys[pygame.K_a]):
                gv.penalty = 1
                return True
            if (keys[pygame.K_s]):
                gv.penalty = 2
                return True
        else:
            retVal = gameController.checkLift()
            if retVal > 0:
                gv.penalty = retVal
                if retVal == 1:
                    return True
                else:
                    if gv.next_round_state == "MULTIPLAYER_STATE":
                        return True

            #setup button press monitoring here
            pass

    def checkLift():
        values = gameController.pollAdc()
        for i in range(6, 8):
            if values[i] > 10.0 and values[i] < 1010.0:
                print("returning ", i - 5, values[i])
                return i - 5
        return 0
コード例 #21
0
import sys
sys.path.insert(0, 'Cubium/drivers/PythonDrivers')

import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008

import time

SPI_PORT = 0
SPI_DEVICE = 0
uv_internal = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))
ADC_PIN = 0


def handleSpaData():
    pass


def sendData():
    value = uv_internal.read_adc(ADC_PIN)
    return value


def init():
    pass
コード例 #22
0
ファイル: SWSPI.py プロジェクト: Chris-Dodd/SPI
dly = .6  # Delay of 1000ms (1 second)

# Software SPI Configuration
CLK = 18  # Set the Serial Clock pin
MISO = 23  # Set the Master Input/Slave Output pin
MOSI = 24  # Set the Master Output/Slave Input pin
CS = 25  # Set the Slave Select

# Hardware SPI Configuration
#HW_SPI_PORT = 0 # Set the SPI Port. Raspi has two.
#HW_SPI_DEV  = 0 # Set the SPI Device

# Instantiate the mcp class from Adafruit_MCP3008 module and set it to 'mcp'.
if (SPI_TYPE == 'HW'):
    # Use this for Hardware SPI
    mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(HW_SPI_PORT, HW_SPI_DEV))
elif (SPI_TYPE == 'SW'):
    # Use this for Software SPI
    mcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI)

# Check to see if we have input from command line. Bail if we dont.
if (len(sys.argv) <= 1):
    print "Usage: MCP3008-example.py <Analog Port>"
    sys.exit(1)
else:
    analogPort = int(sys.argv[1])

print 'Reading MCP3008 values on pin: %d' % analogPort

try:
    while True:
コード例 #23
0
 def __init__(self):
     # Hardware SPI configuration:
     SPI_PORT = 0
     SPI_DEVICE = 0
     self.mcp = Adafruit_MCP3008.MCP3008(
         spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))
    def read(MCP3008, pin):
        mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(0, 0)).read_adc(pin)

        return mcp
コード例 #25
0
ファイル: adc_data.py プロジェクト: javier2828/wheelchairDyno
import csv
import subprocess
import pigpio

# information for local server
THINGSBOARD_HOST = '0.0.0.0'
ACCESS_TOKEN = 'GQvSluZPK8UXJHA4NMPv' 
# channels from ADC pins
leftSpeedChannel = 0;
rightSpeedChannel = 1;
leftTorqueChannel = 2;
rightTorqueChannel = 3;
leftVoltage = 5;
rightVoltage = 6;
# communicate adc via spi
mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(0,0))
# initialize some parameters
max_speed = 0
max_torque = 0
gain = 0;
torqueGain = 0;
calories = 0
distance = 0
tau = 6.28
timer = '00:00:00'
level = 0
currentLevel = 0
buttonState = 1
data = []
l_speed = []
r_speed = []
コード例 #26
0
ファイル: pulseSensor.py プロジェクト: samry/NagSensor
 def __init__(self, channel=0, bus=0, device=0):
     self.channel = channel
     self.BPM = 0
     self.adc = Adafruit_MCP3008.MCP3008(
         spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))
コード例 #27
0
 def __init__(self, spiport, spidevice):
     # Hardware SPI configuration:
     self._mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(spiport, spidevice))
コード例 #28
0
# Create and configure the BNO sensor connection.  Make sure only ONE of the
# below 'bno = ...' lines is uncommented:
# Raspberry Pi configuration with serial UART and RST connected to GPIO 18:
bno = BNO055.BNO055(serial_port='/dev/ttyAMA0', rst=18)

# Initialize the BNO055 and stop if something went wrong.
if not bno.begin():
    raise RuntimeError('Failed to initialize BNO055! Is the sensor connected?')

# Software SPI configuration:
CLK = 18
MISO = 23
MOSI = 24
CS = 25
mcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI)

# Added to get 10 total FSR on additional SPI channels
CLK2 = 12
MISO2 = 16
MOSI2 = 20
CS2 = 21
mcp2 = Adafruit_MCP3008.MCP3008(clk=CLK2, cs=CS2, miso=MISO2, mosi=MOSI2)

ser = serial.Serial(port="/dev/ttyUSB0", baudrate=115200, timeout=0)


## FOOT_ID - print FOOT_ID once.
def sensorDump():
    print('RIGHTFOOT ', end="", flush=True)
    a = 1
コード例 #29
0
# Motor B, Right Side GPIO CONSTANTS
PWM_DRIVE_RIGHT = 5  # ENB - H-Bridge enable pin
FORWARD_RIGHT_PIN = 13  # IN1 - Forward Drive
REVERSE_RIGHT_PIN = 6  # IN2 - Reverse Drive
SPI_PORT = 0
SPI_DEVICE = 0

driveLeft = PWMOutputDevice(PWM_DRIVE_LEFT, True, 0, 1000)
driveRight = PWMOutputDevice(PWM_DRIVE_RIGHT, True, 0, 1000)

forwardLeft = DigitalOutputDevice(FORWARD_LEFT_PIN)
reverseLeft = DigitalOutputDevice(REVERSE_LEFT_PIN)
forwardRight = DigitalOutputDevice(FORWARD_RIGHT_PIN)
reverseRight = DigitalOutputDevice(REVERSE_RIGHT_PIN)
io.setwarnings(False)
mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))

io.setmode(io.BCM)
io.setup(12, io.OUT)
io.setup(4, io.OUT)
io.setup(3, io.OUT)
pressed = 1
var = 1
"""

Functions

"""


def stop():
コード例 #30
0
 def __init__(self):
     self.mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(0, 0))