Exemple #1
0
    def __init__(self, mock=False):
        self.mock = mock
        if not mock:
            from Adafruit_MPR121 import MPR121

            self.sensor = MPR121.MPR121()
            self.sensor.begin()
def setup_capacitive_hat():
    # Create MPR121 instance.
    cap = MPR121.MPR121()

    # Initialize communication with MPR121 using default I2C bus of device, and
    # default I2C address (0x5A).  On BeagleBone Black will default to I2C bus 0.
    if not cap.begin():
        print 'Error initializing MPR121.  Check your wiring!'
        sys.exit(1)

    # Alternatively, specify a custom I2C address such as 0x5B (ADDR tied to 3.3V),
    # 0x5C (ADDR tied to SDA), or 0x5D (ADDR tied to SCL).
    #cap.begin(address=0x5B)

    # Also you can specify an optional I2C bus with the bus keyword parameter.
    #cap.begin(bus=1)

    #Stop the chip to set a new threshold value 0x00 -> ECR
    cap._i2c_retry(cap._device.write8, 0x5E, 0x00)

    #I found this threshold works well with medium fruits (like peaches)
    #Change this for your needs
    cap.set_thresholds(50, 10)

    #I will check if the register are written correctly (debug purposes)
    #tth=cap._i2c_retry(cap._device.readU8,0x41);
    #rth=cap._i2c_retry(cap._device.readU8,0x42);
    #print "Touch TH:" + str(tth) + "Release TH: " +str(rth)

    #Start again the ic
    cap._i2c_retry(cap._device.write8, 0x5E, 0x8F)

    return cap
Exemple #3
0
def touchToneTest():
    print ('Adafruit breakout for 10 channel MPR121 capacitive touch sensor with i2c communication and')
    print ('Adafruit code libraries are used to make a 4 key touch sensor. Each key is used to')
    print ('drive a different tone, played from a Python/C module with independent threads for each tone.')
    print ('enter ctrl-c to return to main menu.')
    global touch_sensor
    global tones
    touch_sensor = MPR121.MPR121()
    touch_sensor.begin()
    touch_sensor.set_thresholds (8,4) # as per dirkjan
    # test tones
    for tone in tones:
        tone.start_train()
        sleep (0.2)
    sleep (0.5)
    for tone in tones:
        tone.stop_train()
    # set up input for IRQ interrupt
    GPIO.setup(touch_IRQ_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.add_event_detect(touch_IRQ_pin, GPIO.FALLING)
    GPIO.add_event_callback (touch_IRQ_pin, touchSensorCallback)
    try:
        while True:
            sleep (0.1)
    except KeyboardInterrupt:
        print ('returning to main menu')
        # turn off all tones
        for tone in tones:
            tone.stop_train()
        GPIO.remove_event_detect(touch_IRQ_pin)
        GPIO.cleanup (touch_IRQ_pin)
        del touch_sensor
Exemple #4
0
 def run(self):
     print "Ο σένσορ άρχισε να λειτουργεί!\n"
     capSensor = MPR121.MPR121()
     if not capSensor.begin():
         print('Error initializing MPR121.  Check your wiring!')
         sys.exit(1)
     last_touched = capSensor.touched()
     self.music = instrumentDynamic()
     self.music.chooseInstrument("piano")  # Choose the instrument
     self.instrument = "piano"  # Set the local variable instrument for later use
     self.lastIntrument = "piano"  # Set the last instrument local variable in order to be able to change the instrument in the while loop
     while True:
         if self.lastInstrument != self.instrument:
             self.music.chooseInstrument(
                 self.instrument)  # Select the instrument the user choose
             self.instrument = self.lastInstrument  # Update the instrument to be the last instrument
         current_touched = capSensor.touched()
         # Check each pin's last and current state to see if it was pressed or released.
         for i in range(12):
             # Each pin is represented by a bit in the touched value.  A value of 1
             # means the pin is being touched, and 0 means it is not being touched.
             pin_bit = 1 << i
             # First check if transitioned from not touched to touched.
             if current_touched & pin_bit and not last_touched & pin_bit:
                 self.dataEmit.emit(i)
                 #instrument.playsound(i)
                 self.music.playsound(i)
         # Update last state and wait a short period before repeating.
         last_touched = current_touched
         time.sleep(0.1)
Exemple #5
0
def record():
    cap = MPR121.MPR121()
    wait_seconds = 1000
    recording = False
    key_lst = ['i', 'k', 'm', 'j', 'u', '7', 'y', 'n', 'h', 'b', 'g', 't']
    last_key = ''
    if not cap.begin():
        print('Error initializing MPR121.  Check your wiring!')
        sys.exit(1)
    last_touched = cap.touched()
    while True:
        data = []
        while True:
            current_touched = cap.touched()
            for i in range(12):
                pin_bit = 1 << i
                if current_touched & pin_bit and not last_touched & pin_bit:
                    if last_key != key_lst[i]:
                        c = key_lst[i]
            last_touched = current_touched
            now = datetime.datetime.now()
            if not recording:
                recording = True
                start_time = datetime.datetime.now()
            ep_time_ms = int((now - start_time).total_seconds() * 1000)
            last_time = now
            if last_time and ep_time_ms > wait_seconds:
                break
            if c == '':
                continue
            else:
                data.append((c, ep_time_ms))
        if len(data) != 1:
            break
    return (data, None)
Exemple #6
0
    def __init__(self, touch, release):
        self._cap_touch = MPR121.MPR121()
        self._touch = touch
        self._release = release

        self._cap_touch.begin()
        self._cap_touch.set_thresholds(self._touch, self._release)
class WaterValve:
    global cap
    cap = MPR121.MPR121()

    def __init__(self, PIN_WATER):
        self.GPIO.setup(PIN_WATER, GPIO.OUT, initial=GPIO.LOW)
        try:
            if not cap.begin():
                raise LickDetectorError("Error initializing MPR121 Lick Detector. Check wiring!")
Exemple #8
0
	def __init__(self):
		# Initialize hardware
		self.cap = MPR121.MPR121()
		if not self.cap.begin():
			print('Error initializing MPR121.  Check your wiring!')
			sys.exit(1)
		# Get last touched
		self.lasttouched = self.cap.touched()
		self.touched = self.lasttouched
def initTouch():
    cap = MPR121.MPR121()
    if not cap.begin():
        print("Error initializing MPR121.  Check your wiring!")
        lcd.clean()
        lcd.message("Touch Sensor \nConnection Error")
        sys.exit(1)
    print("Touch Sensor Started\n")
    return cap
def initTouch():
    cap = MPR121.MPR121()
    if not cap.begin():
        print 'Error initializing MPR121.  Check your wiring!'
        sys.exit(1)


#		cap.set_thresholds(25,25)
    return cap
def InitialDevices(tunnelParams, cameraOn):
    """
    Initializing Devices connected to Raspberry Pi (via GPIO or not?) // todo ask if all devices connected to RP GPIO
    :param tunnelParams: tunnel communication parameters.
    :param cameraOn: boolean - camera is on/off.
    :return: tuple serial_dev, CameraObject // todo don't know, what obj. are: serial_dev, CameraObject
    """
    # camera
    if cameraOn:
        CameraObject = PiCamera()

    # GPIOs
    GPIO.setmode(GPIO.BCM)

    # touch sensor
    cap = MPR121.MPR121()
    if not cap.begin():
        print('Error initializing MPR121 Lick Detector. Check your wiring!')
        sys.exit(1)
    cap = MPR121.MPR121()

    # RFID reader
    serial_dev = serial.Serial(tunnelParams['USB_PORT'], baudrate=9600)

    # water valve
    GPIO.setup(tunnelParams['PIN_WATER'], GPIO.OUT, initial=GPIO.LOW)

    # servo motor
    if 'PIN_SERVO' in tunnelParams:
        wiringpi.wiringPiSetupGpio()
        wiringpi.pinMode(tunnelParams['PIN_SERVO'],
                         wiringpi.GPIO.PWM_OUTPUT)  # PWM output
        # divide down clock: Servo's want 50 Hz frequency output, PWM Frequency in Hz = 19,200,000 Hz / pwmClock / pwmRange
        wiringpi.pwmSetClock(192)
        wiringpi.pwmSetRange(2000)

    # LED
    if 'PIN_LED' in tunnelParams:
        GPIO.setup(tunnelParams['PIN_LED'], GPIO.OUT, initial=GPIO.LOW)

    return serial_dev, CameraObject
Exemple #12
0
    def __init__(self):
        if self.DEBUG:
            print("Debug Mode Initialized")
            print("Use number keys. Press Ctrl-C to quit.")
            return
        print('Initializing TouchSensor...')
        
        self.cap = MPR121.MPR121()

        if not self.cap.begin():
            print('Error initializing MPR121.  Check your wiring!')
            sys.exit(1)

        print('Success! Press Ctrl-C to quit.')

        self.last_touched = self.cap.touched()
Exemple #13
0
    def run(self):

        cap = MPR121.MPR121()
        if not cap.begin():
            print('Error initializing MPR121.  Check your wiring!')
            sys.exit(1)
        cap._i2c_retry(cap._device.write8, 0x5E, 0x00)
        cap.set_thresholds(1, 2)
        cap._i2c_retry(cap._device.write8, 0x5E, 0x8F)

        last_touched = cap.touched()
        global puntaje1
        global puntaje2
        global puntaje3
        global f

        #cont =0
        while stop:

            current_touched = cap.touched()

            for i in range(12):
                # Each pin is represented by a bit in the touched value.  A value of 1
                # means the pin is being touched, and 0 means it is not being touched.
                pin_bit = 1 << i
                # First check if transitioned from not touched to touched.
                if current_touched & pin_bit and not last_touched & pin_bit:
                    #print('{0} touched!'.format(i))
                    if f[i] is True:

                        f[i] = False
                        GPIO.output(pin[i], GPIO.LOW)
                        if i < 4:
                            puntaje1 += 1
                            print puntaje1
                        elif i < 8:
                            puntaje2 += 1
                            print puntaje2
                        else:
                            puntaje3 += 1
                            print puntaje3
                # Next check if transitioned from touched to not touched.
                #if not current_touched & pin_bit and last_touched & pin_bit:
                #print('{0} released!'.format(i))
            # Update last state and wait a short period before repeating.
            last_touched = current_touched
            time.sleep(0.1)
Exemple #14
0
def listen_to_sensors():
    """
    Loads the Adafruit library and starts listening for sensor input
    :return:
    """

    log('Loading Adafruit MPR121 Capacitive Touch Sensor')
    # Create MPR121 instance.
    cap = MPR121.MPR121()

    if not cap.begin():
        log('Error initializing MPR121.  Check your wiring!')
        sys.exit(1)
    log("Initialized sensor")
    cap.set_thresholds(255, 255)
    log("Start listening")
    listen(cap)
Exemple #15
0
    def initialize(self):

        #Pinout
        self.Limit_switch_pin = 26
        self.redPin = 11
        self.greenPin = 13
        self.bluePin = 15
        self.servoPin = 18

        #initialize state
        self.state = State.LOCKED

        #-----Set up keypad-----#
        self.cap = MPR121.MPR121()
        self.correct_combination = '1234'
        self.correct_numbers_entered = 0

        if not self.cap.begin():
            print('Error initializing MPR121.  Check your wiring!')
            sys.exit(1)

        #-----Set up servo-----#
        # use 'GPIO naming'
        wiringpi.wiringPiSetupGpio()

        # set #18 to be a PWM output
        wiringpi.pinMode(18, wiringpi.GPIO.PWM_OUTPUT)

        # set the PWM mode to milliseconds stype
        wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS)

        # divide down clock
        wiringpi.pwmSetClock(192)
        wiringpi.pwmSetRange(2000)

        self.delay_period = 0.01

        #-----Set up limit switch-----#
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(self.Limit_switch_pin, GPIO.IN)

        #-----Set up LED-----#
        GPIO.setup(self.redPin, GPIO.OUT)
        GPIO.setup(self.greenPin, GPIO.OUT)
        GPIO.setup(self.bluePin, GPIO.OUT)
Exemple #16
0
 def __init__(self, channel_numbers, IRQ_PIN, data_logger):
     self.IRQ_PIN = IRQ_PIN
     self.data_logger = data_logger
     global g_licks_detected
     g_licks_detected = 0
     global g_lick_last_data
     g_lick_last_data = 0
     global g_lick_channels
     g_lick_channels = channel_numbers
     global g_licks_logger
     g_licks_logger = data_logger  # data logger is AHF_Datalogger object, or eqivalent
     # initialize capacitive sensor gobal object and start it up
     global gLickDetector
     gLickDetector = MPR121.MPR121()
     gLickDetector.begin()
     gLickDetector.set_thresholds(8, 4)  # as per dirkjan
     # set up IRQ interrupt function. GPIO.setmode should alreay have been called
     GPIO.setup(self.IRQ_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
     self.isLogging = False
Exemple #17
0
    def __init__(self):
        # Temp Sensor.
        self._sensor_temp = MCP9808.MCP9808()
        try:
            self._sensor_temp.begin()
            logging.info('Temperature sensor started.')
        except Exception as err:
            self._sensor_temp = None
            msg = 'An error occured while setting up temperature sensor: {}'
            logging.error(msg.format(str(err)))

        # Color Sensor.
        self._sensor_tcs = None
        try:
            self._sensor_tcs = Adafruit_TCS34725.TCS34725()
            self._sensor_tcs.set_interrupt(True)
            logging.info('Color sensor started.')
        except Exception as err:
            msg = 'An error occured while setting up color sensor: {}'
            logging.error(msg.format(str(err)))

        self._touch_sensor = MPR121.MPR121()
        try:
            self._touch_sensor.begin()
            logging.info('Touch sensor started.')
        except Exception as err:
            self._touch_sensor = None
            msg = 'An error occured while setting up touch sensor: {}'
            logging.error(msg.format(str(err)))

        self.temperature = 0
        self.r, self.g, self.b, self.c = [0, 0, 0, 0]
        self.color_temp = 0
        self.lux = 0
        self.touched_list = []
        self._last_touched_data = 0
        self._collect_touches = False

        self.sensor_read_loop = tornado.ioloop.PeriodicCallback(
            self._update, 1000)
        self.sensor_read_loop.start()
def detect_touch():

    # Create MPR121 instance.
    cap = MPR121.MPR121()

    # Initialize communication with MPR121 using default I2C bus of device, and
    # default I2C address (0x5A).  On BeagleBone Black will default to I2C bus 0.
    if not cap.begin():
        print 'Error initializing MPR121.  Check your wiring!'
        sys.exit(1)

    # Alternatively, specify a custom I2C address such as 0x5B (ADDR tied to 3.3V),
    # 0x5C (ADDR tied to SDA), or 0x5D (ADDR tied to SCL).
    #cap.begin(address=0x5B)

    # Also you can specify an optional I2C bus with the bus keyword parameter.
    #cap.begin(bus=1)

    # Main loop to print a message every time a pin is touched.
    print 'Press Ctrl-C to quit.'
    last_touched = cap.touched()
    while True:
        current_touched = cap.touched()
        # Check each pin's last and current state to see if it was pressed or released.
        for i in range(12):
            # Each pin is represented by a bit in the touched value.  A value of 1
            # means the pin is being touched, and 0 means it is not being touched.
            pin_bit = 1 << i
            # First check if transitioned from not touched to touched.
            if current_touched & pin_bit and not last_touched & pin_bit:
                print '{0} touched!'.format(i)
            # Next check if transitioned from touched to not touched.
            if not current_touched & pin_bit and last_touched & pin_bit:
                print '{0} released!'.format(i)
        # Update last state and wait a short period before repeating.
        last_touched = current_touched
        time.sleep(0.1)
global SteadyState_Angle
SteadyState_Angle = 162

global allRFIDs
allRFIDs = {
}  # dic of all mice to count the blocks, [0] contains # of enteries and [1] contains list of entry times

# activation
global CameraObject
try:
    CameraObject = PiCamera()  # define camera object
except:
    CameraObject = False

global cap
cap = MPR121.MPR121()  # defining lick detector

# initialization
serial_dev = InitialDevices()
print('Initializing devices')
mouseRFID = ''

while True:

    # waiting for a mouse
    RFID_lastChar = serial_dev.read()

    if RFID_lastChar == '\r':  # we have a full RFID, we identified the mouse

        print('a mouse entered tunnel #' + str(tunnelID))
        # record the entry time
Exemple #20
0
    def talkBoxCreate():
        print 'Adafruit MPR121 Capacitive Touch Sensor Test'

        # Create MPR121 instance.
        cap = MPR121.MPR121()

        # Initialize communication with MPR121 using default I2C bus of device, and
        # default I2C address (0x5A).  On BeagleBone Black will default to I2C bus 0.
        if not cap.begin():
            print 'Error initializing MPR121.  Check your wiring!'
            sys.exit(1)

        #Initalize and load the sound module.
        pygame.mixer.init(48000, -16, 1, 1024)
        soundChannelList = [None] * 12
        soundList = [None] * 12

        sound1 = pygame.mixer.Sound("/home/pi/Music/Feeling/happy.wav")
        soundChannel1 = pygame.mixer.Channel(1)
        soundList[0] = sound1
        soundChannelList[0] = soundChannel1
        sound2 = pygame.mixer.Sound("/home/pi/Music/Feeling/excited.wav")
        soundChannel2 = pygame.mixer.Channel(2)
        soundList[1] = sound2
        soundChannelList[1] = soundChannel2
        sound3 = pygame.mixer.Sound("/home/pi/Music/Feeling/feeling.wav")
        soundChannel3 = pygame.mixer.Channel(3)
        soundList[2] = sound3
        soundChannelList[2] = soundChannel3
        sound4 = pygame.mixer.Sound("/home/pi/Music/Feeling/proud.wav")
        soundChannel4 = pygame.mixer.Channel(4)
        soundList[3] = sound4
        soundChannelList[3] = soundChannel4
        sound5 = pygame.mixer.Sound("/home/pi/Music/Feeling/sad.wav")
        soundChannel5 = pygame.mixer.Channel(5)
        soundList[4] = sound5
        soundChannelList[4] = soundChannel5
        sound6 = pygame.mixer.Sound("/home/pi/Music/Feeling/sick.wav")
        soundChannel6 = pygame.mixer.Channel(6)
        soundList[5] = sound6
        soundChannelList[5] = soundChannel6
        sound7 = pygame.mixer.Sound("/home/pi/Music/Feeling/tired.wav")
        soundChannel7 = pygame.mixer.Channel(7)
        soundList[6] = sound7
        soundChannelList[6] = soundChannel7
        sound8 = pygame.mixer.Sound(
            "/home/pi/Music/Feeling/good_morning_f.wav")
        soundChannel8 = pygame.mixer.Channel(1)
        soundList[7] = sound8
        soundChannelList[7] = soundChannel8
        sound9 = pygame.mixer.Sound("/home/pi/Music/Feeling/goodbye_f.wav")
        soundChannel9 = pygame.mixer.Channel(2)
        soundList[8] = sound9
        soundChannelList[8] = soundChannel9
        sound10 = pygame.mixer.Sound("/home/pi/Music/Feeling/need_break.wav")
        soundChannel10 = pygame.mixer.Channel(3)
        soundList[9] = sound10
        soundChannelList[9] = soundChannel10
        sound11 = pygame.mixer.Sound("/home/pi/Music/Feeling/thank_you_f.wav")
        soundChannel11 = pygame.mixer.Channel(4)
        soundList[10] = sound11
        soundChannelList[10] = soundChannel11
        sound12 = pygame.mixer.Sound("/home/pi/Music/Feeling/sunny.wav")
        soundChannel12 = pygame.mixer.Channel(5)
        soundList[11] = sound12
        soundChannelList[11] = soundChannel12
        print "Soundboard Ready."
import sys
import time
import subprocess

import Adafruit_MPR121.MPR121 as TouchSensor

sensor = TouchSensor.MPR121()


def initBluetooth():
    return 0

    # Programatic way of initializing bluetooth in python
    # At the moment we'll use a start script
    onCommand = "sudo hciconfig hci0 up"
    intervalCommand = "sudo hcitool -i hci0 cmd 0x08 0x0006 00 A0 00 FF 03 00 00 00 00 00 00 00 00 07 00"
    startCommand = "sudo hcitool -i hci0 cmd 0x08 0x000a 01"

    assert subprocess.call(onCommand, shell=True) == 0, "on Command Failed"
    assert subprocess.call(intervalCommand,
                           shell=True) == 0, "interval Command Failed"
    assert subprocess.call(startCommand,
                           shell=True) == 0, "start Command Failed"


def advertiseBluetoothSensorError():
    """
    :return:
    """
    command = """sudo hcitool -i hci0 cmd 0x08 0x0008 1c 02 01 06 03 03 aa fe 14 16 aa fe 10 00 03 6d 79 70 2e 6d 65 3f 73 65 6e 73 65 72 72 00 00 00"""
    p1 = subprocess.call(command, shell=True)
Exemple #22
0
sock = BluetoothSocket( RFCOMM )
sock.connect((host, port))

print ("CONNECTED")
'''
BLUETOOTH CONNECTION ESTABLISHED
'''


'''
Setup
'''
threshold = 1015        # Threshold value for pressure to count for step.
step = 0                # Global step count
state = "STANDING"      # Global User State
cap = MPR121.MPR121()   # Initiating Capacitive Touch
cap.begin()
p = Pulsesensor()       # Initiating Heart Rate Sensor
p.startAsyncBPM()

'''
LOOP
'''
while True:
    # Flag for Developer
	print("Loop Begins")
    
	adc = MCP3008(0, 0)
	
    # Channel 1 for velostat reading. 
    velostat = adc.read(1)
Exemple #23
0
def main():
    mapping = {
        0: 'a',
        1: 'w',
        2: 's',
        3: 'd',
        4: Key.space,
        5: Key.shift,
        6: Key.left,
        7: Key.up,
        8: Key.down,
        9: Key.right
    }
    #mapping = {0:'a',1:'w',2:'s',3:'d',4:Key.space,5:Key.shift,6:'e',7:Key.esc,8:Key.down,9:Key.right}
    #mapping = {0:'a',1:'w',2:'s',3:'d',4:Key.space,5:'c',6:Key.left,7:Key.up,8:Key.down,9:Key.right,10:'c',11:'c'}

    keyboard = Controller()
    cap = sensor.MPR121()
    if not cap.begin():
        print '???'

    pygame.init()

    gamepad_image = pygame.transform.scale(pygame.image.load('gamepadgui.png'),
                                           (800, 230))
    screen = pygame.display.set_mode((800, 230))
    t = pygame.time.Clock()

    last_touched = cap.touched()

    global last_touched
    while True:
        whattouched = ''
        current_touched = cap.touched()
        for i in range(12):
            pin_bit = 1 << i
            if current_touched & pin_bit and not last_touched & pin_bit:
                print('{0} touched!'.format(i))
                if i in mapping:
                    keyboard.press(mapping[i])
            if not current_touched & pin_bit and last_touched & pin_bit:
                print('{0} released!'.format(i))
                keyboard.release(mapping[i])
        last_touched = current_touched

        screen.blit(gamepad_image, (0, 0))
        #keyboard.press(Key.space)
        #keyboard.release(Key.space)
        screen.blit(gamepad_image, (0, 0))
        '''detection_results = kmodule.constdetect()
        #print detection_results
        if detection_results != '':
            #try:
            if detection_results-1 in mapping:
                keyboard.press(mapping[detection_results-1])
                #keyboard.release(mapping[detection_results])
                print mapping[detection_results-1]
                #except:
                #pass
        else:
            for i in mapping:
                keyboard.release(mapping[i])'''

        for event in pygame.event.get():
            if event.type == QUIT:
                import Mainmenu
                Mainmenu.main()
        pygame.display.flip()
        t.tick(20)
        time.sleep(0.1)
Exemple #24
0
#mapping = {0:'a',1:'w',2:'s',3:'d',4:Key.space,5:'c',6:Key.left,7:Key.up,8:Key.down,9:Key.right,10:'c',11:'c'}

mapping = {
    0: 'a',
    1: 'w',
    2: 's',
    3: 'd',
    5: Key.space,
    4: Key.shift,
    6: 'e',
    7: Key.esc,
    8: Key.down,
    9: Key.right
}
keyboard = Controller()
cap = sensor.MPR121()
if not cap.begin():
    print '???'

pygame.init()
'''gamepad_image = pygame.transform.scale(pygame.image.load('gamepadgui.png'),(800,230))'''
screen = pygame.display.set_mode((300, 80))
t = pygame.time.Clock()

last_touched = cap.touched()
'''def detect():
    global cap
    global last_touched
    whattouched = ''
    current_touched = cap.touched()
    for i in range(12):
Exemple #25
0
def PiPiano(instrument_map, a, b, c, d):
    if a:
        click.echo("Attempting to register MPR121 on address 0x5A")
        TouchSensors[0] = MPR121.MPR121()
        if not (TouchSensors[0].begin(address=0x5A)):
            click.echo("*********************")
            click.echo("ERROR initializing MPR121 on address 0x5A")
            sys.exit(1)
        else:
            TouchSensors[0].set_thresholds(14, 8)
            click.echo("MPR121 on 0x5A initialized")
    if b:
        click.echo("Attempting to register MPR121 on address 0x5B")
        TouchSensors[1] = MPR121.MPR121()
        if not (TouchSensors[1].begin(address=0x5B)):
            click.echo("*********************")
            click.echo("ERROR initializing MPR121 on address 0x5B")
            sys.exit(1)
        else:
            TouchSensors[1].set_thresholds(14, 8)
            click.echo("MPR121 on 0x5B initialized")
    if c:
        click.echo("Attempting to register MPR121 on address 0x5C")
        TouchSensors[2] = MPR121.MPR121()
        if not (TouchSensors[2].begin(address=0x5C)):
            click.echo("*********************")
            click.echo("ERROR initializing MPR121 on address 0x5C")
            sys.exit(1)
        else:
            TouchSensors[2].set_thresholds(14, 8)
            click.echo("MPR121 on 0x5C initialized")
    if d:
        click.echo("Attempting to register MPR121 on address 0x5D")
        TouchSensors[3] = MPR121.MPR121()
        if not (TouchSensors[3].begin(address=0x5D)):
            click.echo("*********************")
            click.echo("ERROR initializing MPR121 on address 0x5D")
            sys.exit(1)
        else:
            TouchSensors[3].set_thresholds(14, 8)
            click.echo("MPR121 on 0x5D initialized")

    #initialize pygame mixer
    pygame.mixer.pre_init(
        44100, -16, 48,
        512)  #44.1khz, 16bit signed value, 12 channel, 512 bit biffer
    pygame.init()
    pygame.mixer.set_num_channels(48)  # doesn't seem to stick in pre_init
    click.echo("Mixer setup.  Number of channels = " +
               str(pygame.mixer.get_num_channels()))

    click.echo("\nInstrument map file:")
    click.echo(str(instrument_map))
    LoadSoundFiles(instrument_map)
    InitSoundChannel()

    #print(SOUND_MAPPING) #DEBUG verify variable scope worked correctly

    click.echo("\nMPR List:")
    click.echo(str(TouchSensors))

    #initialize previous state of sensors
    click.echo("\nInitializing Touch memory.")
    last_touched = [0, 0, 0, 0]
    current_touched = [0, 0, 0, 0]
    for boardNum, MPR in TouchSensors.items():
        last_touched[boardNum] = MPR.touched()
        #print(last_touched[boardNum])

    click.echo("Memory initialized.  Starting main loop...")
    click.echo("Press Ctrl-C to quit.")
    #start main loop
    while True:

        for boardNum, MPR in TouchSensors.items():

            current_touched[boardNum] = MPR.touched()

            CurStat = "Board " + str(boardNum) + " status = " + str(
                current_touched[boardNum])
            LastStat = "  Last touched = " + str(last_touched[boardNum])
            #click.echo(CurStat + LastStat)

            #click.echo("Board " + str(boardNum) + " touched: " + str(current_touched))
            for pinNum in range(12):
                pin_bit = 1 << pinNum

                #click.echo("Checking pin " + str(pinNum) + " on board " + str(boardNum))

                #get boolean-compatible values for current& last state
                CurState = current_touched[boardNum] & pin_bit
                LastState = last_touched[boardNum] & pin_bit

                #if now touching
                if (current_touched[boardNum] & pin_bit
                        and not last_touched[boardNum] & pin_bit):
                    click.echo("Board " + str(boardNum) + " pin " +
                               str(pinNum) + " is touching.")
                    #play sound
                    PlaySound(boardNum, pinNum)
                #if now releasing
                if (not current_touched[boardNum] & pin_bit
                        and last_touched[boardNum] & pin_bit):
                    click.echo("Board " + str(boardNum) + " pin " +
                               str(pinNum) + " is released.")
                    #stop sound
                    StopSound(boardNum, pinNum)

            #remember touched value for next time
            last_touched[boardNum] = current_touched[boardNum]
        #end for loop

        #delay loop
        time.sleep(0.1)
    #end main loop

    click.echo("\nEnd of PiPiano Program.\n")
def collector(addr,filename,i2cbus=None):

	# Create MPR121 instance
	cap = MPR121.MPR121()
	if not cap.begin(addr,i2cbus):
		print 'Error initializing MPR121. Check your wiring!'
		sys.exit(1)

	# Get filename
	filename = re.split('\.py',filename)
	filename = filename[0]

	# Open csv data dump files
	writer_filt = open('../data/{0}_filt.csv'.format(filename),'w')
	writer_base = open('../data/{0}_base.csv'.format(filename),'w')

	# Remind user how to exit program
	print 'Controller ' + filename + ': Press Ctl-C to exit'

	# Set device ID
	if addr == 0x5A:
		id = 1
	elif addr == 0x5B:
		id = 2
	elif addr == 0x5C:
		id = 3
	else:
		id = 4

	# Main loop
	last_touched = cap.touched()
	count = 0
	buffer = []

	while True:
		current_touched = cap.touched()
		# Check each pin's last and current state to see if it was pressed or released.

		for i in range(12):

			# Each pin is represented by a bit in the touched value.  A value of 1
			# means the pin is being touched, and 0 means it is not being touched.
			pin_bit = 1 << i

			# First check if transitioned from not touched to touched.
			if current_touched & pin_bit and not last_touched & pin_bit:
				print '{0} touched!'.format(i)

			# Next check if transitioned from touched to not touched.
			if not current_touched & pin_bit and last_touched & pin_bit:
				print '{0} released!'.format(i)

		# Update last state and wait a short period before repeating.
		last_touched = current_touched

		# Get raw data
		filtered = [cap.filtered_data(i) for i in range(12)]
		base = [cap.baseline_data(i) for i in range(12)]

		# Optionally print all data to console
		#print '\t\t\t\t\t\t\t\t\t\t\t\t\t 0x{0:0X}'.format(cap.touched())
		#print 'Filt:', '\t,'.join(map(str, filtered))
		#print 'Base:', '\t,'.join(map(str, base))

		# Dump data into csv files
		data_filt = (','.join(map(str, filtered))) + '\n'
		writer_filt.write(data_filt)

		data_base = (','.join(map(str, base))) + '\n'
		writer_base.write(data_base)

		# Transmit data to serial mux server
		data_filt = str(id) + ',' + str(count) + ',' + data_filt
		buffer.append(data_filt)

		try:
			port = serial.Serial(
						port = '/dev/ttyAMA0',
						baudrate = 9600,
						parity = serial.PARITY_NONE,
						stopbits = serial.STOPBITS_ONE,
						bytesize = serial.EIGHTBITS,
						timeout = 1
						)

			#if port.isOpen():
				#try:
					#fcntl.flock(port.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
				#except IOError:
					#count = count + 1
					#continue
				#else:
					#yield port
		except serial.SerialException as ex:
			print 'Port /dev/ttyAMA0  is unavailable: {0}:'.format(ex)
		else:
			port.write(buffer[0])
			del buffer[0]
			#fcntl.flock(port.fileno(), fcntl.LOCK_UN)
		
		count = count + 1
		time.sleep(0.1)
Exemple #27
0
    # Set other configuration registers.
    cap._i2c_retry(cap._device.write8, MPR121.MPR121_DEBOUNCE, 3)
    cap._i2c_retry(cap._device.write8, MPR121.MPR121_CONFIG1, 0x3F) # default, 16uA charge current
    cap._i2c_retry(cap._device.write8, MPR121.MPR121_CONFIG2, 0x20) # 0.5uS encoding, 1ms period
    # Enable all electrodes.
    cap._i2c_retry(cap._device.write8, MPR121.MPR121_ECR, 0x8F) # start with first 5 bits of baseline tracking
    
    # Setup the autoconfig
    cap1._i2c_retry(cap1._device.write8, MPR121.MPR121_AUTOCONFIG0, 0b10101110)
    cap1._i2c_retry(cap1._device.write8, MPR121.MPR121_AUTOCONFIG1, 0)

    last_reset = time.time()

# Create MPR121 instance
cap1 = MPR121.MPR121()

# Initialize communication with MPR121
cap1.begin( 0x5a )
init(cap1)

#logFile = open('singing_plants.log', 'a')

ccount = 0
avg = 0
buffer = [0, 0, 0, 0]
pState = 0
bs = 5
mavg = [MovingAvg(bs), MovingAvg(bs), MovingAvg(bs), MovingAvg(bs)]
sounds_playing = [False,False,False,False]
is_loop = [True,True,True,True]
import sys
import time
import pygame
import Adafruit_MPR121.MPR121 as MPR121

cap1 = MPR121.MPR121()
cap2 = MPR121.MPR121()
pygame.mixer.init()
pygame.mixer.set_num_channels(24)
soundFiles = [[
    'moods', 'coralreef', 'birdsong', 'thunder', 'moods2', 'birdsong',
    'stones', 'birdsong', 'process', 'navy', 'godrevy', 'stream'
],
              [
                  'noelectric', 'quarryfields', 'lochness', 'stream',
                  'birdsong', 'allotment', 'imaginaryflower', 'porthleven',
                  ' ', ' ', ' ', ' '
              ]]

print('Loaded Sounds')
if not cap1.begin(0x5a):
    print('Error initializing MPR121 No1. Check your wiring!')
    sys.exit(1)
if not cap2.begin(0x5b):
    print('Error initializing MPR121 No2. Check your wiring!')
    sys.exit(1)
print('Initialised Touch boards')


def handleSound(pin, board, trigger):
    channelNo = pin + (board * 12)
Exemple #29
0
print('Adafruit MPR121 Capacitive Touch Sensor Test')

c = OSCClient()
c.connect(('192.168.1.2', 57120))
print c

#m = OSCMessage("/test")
#m += [44, 11, 4.5, "the white cliffs of dover"]

#c.send(m)

#c.close()

# Create MPR121 instance.
cap = MPR121.MPR121()

# Initialize communication with MPR121 using default I2C bus of device, and
# default I2C address (0x5A).  On BeagleBone Black will default to I2C bus 0.
if not cap.begin():
    print('Error initializing MPR121.  Check your wiring!')
    sys.exit(1)

# Alternatively, specify a custom I2C address such as 0x5B (ADDR tied to 3.3V),
# 0x5C (ADDR tied to SDA), or 0x5D (ADDR tied to SCL).
#cap.begin(address=0x5B)

# Also you can specify an optional I2C bus with the bus keyword parameter.
#cap.begin(busnum=1)

# Main loop to print a message every time a pin is touched.
Exemple #30
0
import Adafruit_MPR121.MPR121 as MPR121

GPIO.setmode(GPIO.BOARD)

videoSource = 'src/videos/centaur_1.mpg'  # set initial video source
capVideo = cv2.VideoCapture(videoSource)
playingVideo = True

FPS = 24.0  # mostly use 24 i guess
currentFrame = 0  # remember which frame we are at
videoFilter = ''
# dont apply any filter in the beginning?

# capavative touch sensor
capTouch = MPR121.MPR121()

if not capTouch.begin():
    print('Error initializing MPR121.  Check your wiring!')
    sys.exit(1)

# Raspberry pi setup

# LED PINS
GREEN_1 = 40
RED_1 = 37
BLUE_1 = 38
GPIO.setup(RED_1, GPIO.OUT)
GPIO.setup(GREEN_1, GPIO.OUT)
GPIO.setup(BLUE_1, GPIO.OUT)
GREEN_2 = 31