Пример #1
0
class FirmataThread(threading.Thread):
     def __init__(self,widget):
         super(FirmataThread, self).__init__()
         self.board = ArduinoMega('/dev/ttyACM0')
         self.it = util.Iterator(self.board)
         self.it.start()
         self.board.analog[0].enable_reporting()
         self.board.analog[1].enable_reporting()
         self.board.analog[2].enable_reporting()
         self.board.analog[3].enable_reporting()
         self.board.analog[4].enable_reporting()
         self.board.analog[5].enable_reporting()
         self.stopNow = False
         self.ws = 0
         self.widget = widget
         print "ArduinoMEGA ready to operate"
         #self.connectWS()
         #self.max1 = 0.2
         #self.min1 = 0.1
         #self.max2 = 0.2
         #self.min2 = 0.1
     
     def connectWS(self):
		try:
			self.ws = create_connection("ws://192.168.1.220:33033/ws")
			print "Websocket created"
		except:
			print "Could not create connection"
			self.ws = 0
			
     
     def run(self):
         oldValue = [-10,-10,-10,-10,-10,-10]
         while ( not self.stopNow) :
			
			for sensor in range(6):
				value = self.board.analog[sensor].read()
				if (value==None):
					print "Coulde not read value form sensor ",sensor
					return
				value = (float(value) - 0.5) * 2  # - 0.5)*2 # to -1..1; for sensor 0.5 is neutral neutral now inhaling positive, exhaling negative
				value = int(value *100) / 100.0 # leave just 2 decimals
				#TODO: ümarda nii, et suurus oleks 1 komakoht (-10..10)? , saada ws ainult, kui on muutunud
				#print value, float(value), v1
				
				if (value!=oldValue[sensor] ):
					oldValue[sensor] = value
					valueLabel[sensor].setText(str(value))
					if (self.ws!=0):
						self.ws.send("blower,"+str(sensor+1)+ "," + str(value) )
				
			time.sleep(0.25)   
     
     def stop(self):
		 self.stopNow = True
		 self.board.exit()
		 if (self.ws!=0):
			self.ws.close
Пример #2
0
class FirmataThread(threading.Thread):
    def __init__(self, widget):
        super(FirmataThread, self).__init__()
        self.board = ArduinoMega('/dev/ttyACM0')
        self.it = util.Iterator(self.board)
        self.it.start()
        self.board.analog[0].enable_reporting()
        self.board.analog[1].enable_reporting()
        self.stopNow = False
        self.widget = widget
        print "ArduinoMEGA ready to operate"
        #self.max1 = 0.2
        #self.min1 = 0.1
        #self.max2 = 0.2
        #self.min2 = 0.1

    def run(self):
        while (not self.stopNow):
            v1 = self.board.analog[0].read()
            v2 = self.board.analog[1].read()
            #if (v1>self.max1 and v1<1): # find relative value between max and min of the session bit interesting
            #self.max1 = v1
            #if (v1<self.min1 and v1>0):
            #self.min1 = v1

            #if (v2>self.max2 and v2<1):
            #self.max2 = v2
            #if (v1<self.min2 and v2>0):
            #self.min2 = v2
            max = 0.6
            min = 0.2
            if (v1 < min):
                v1 = min
            if (v1 > max):
                v1 = max
            if (v2 < min):
                v2 = min
            if (v2 > max):
                v2 = max
            rel1 = (v1 - min) / (max - min)
            rel2 = (v2 - min) / (max - min)
            #print rel1,rel2
            valueLabel1.setText(str(rel1))
            valueLabel2.setText(str(rel2))
            sendUdpMessage("sensor,skin1," + str(rel1))
            sendUdpMessage("sensor,skin2," + str(rel2))
            time.sleep(0.25)

    def stop(self):
        self.stopNow = True
        self.board.exit()
Пример #3
0
class FirmataThread(threading.Thread):
     def __init__(self,widget):
         super(FirmataThread, self).__init__()
         self.board = ArduinoMega('/dev/ttyACM0')
         self.it = util.Iterator(self.board)
         self.it.start()
         self.board.analog[0].enable_reporting()
         self.board.analog[1].enable_reporting()
         self.stopNow = False
         self.widget = widget
         print "ArduinoMEGA ready to operate"
         #self.max1 = 0.2
         #self.min1 = 0.1
         #self.max2 = 0.2
         #self.min2 = 0.1
	
     def run(self):
         while ( not self.stopNow) :
			v1 = self.board.analog[0].read()
			v2 = self.board.analog[1].read()
			#if (v1>self.max1 and v1<1): # find relative value between max and min of the session bit interesting
				#self.max1 = v1
			#if (v1<self.min1 and v1>0):
				#self.min1 = v1
			
			#if (v2>self.max2 and v2<1):
				#self.max2 = v2
			#if (v1<self.min2 and v2>0):
				#self.min2 = v2
			max = 0.6
			min = 0.2
			if (v1<min):
				v1 = min
			if (v1>max):
				v1 = max
			if (v2<min):
				v2 = min
			if (v2>max):
				v2 = max	
			rel1 = (v1-min) / (max-min)
			rel2 = (v2-min) / (max-min)
			#print rel1,rel2
			valueLabel1.setText(str(rel1))
			valueLabel2.setText(str(rel2))
			sendUdpMessage("sensor,skin1,"+str(rel1))
			sendUdpMessage("sensor,skin2,"+str(rel2))
			time.sleep(0.25)   
     
     def stop(self):
		 self.stopNow = True
		 self.board.exit()
Пример #4
0
class FirmataThread(threading.Thread):
     def __init__(self,widget):
         super(FirmataThread, self).__init__()
         self.board = ArduinoMega('/dev/ttyACM0')
         self.it = util.Iterator(self.board)
         self.it.start()
         self.board.analog[0].enable_reporting()
         self.board.analog[1].enable_reporting()
         self.stopNow = False
         self.widget = widget
	
     def run(self):
         while ( not self.stopNow) :
			v1 = self.board.analog[0].read()
			v2 = self.board.analog[1].read()
			#print v1,v2
			valueLabel1.setText(str(v1))
			valueLabel2.setText(str(v2))
			time.sleep(0.1)    
     
     def stop(self):
		 self.stopNow = True
		 self.board.exit()
Пример #5
0
def ir_mux(ir_name):
    logging.debug('Starting')

    # ------- connect to IR hardwares --------
    board_port = ir_port  # The port is from the USB port
    ir_board = ArduinoMega(
        board_port)  # Creat the Serial port for ArduinoMega board
    # first multiplexer, define switch and signal pins on boards
    PinS, PinSig = mux.DefinePin(ir_board, [30, 31, 32, 33], 3)
    # second multiplexer, define switch and signal pins on boards
    PinS2, PinSig2 = mux.DefinePin(ir_board, [40, 41, 42, 43], 4)
    logging.debug('connected to IR board')

    # ------- initialize hardwares and variables ------
    # start switches with connectin to channel 0
    mux.SwitchMUX(PinS, 0)
    mux.SwitchMUX(PinS2, 0)
    Data = {}  # Creat an empty dictionary
    num_of_data = 2000

    # ------ start Iterator to avoid serial overflow -----
    it = util.Iterator(
        ir_board)  # need this iteration otherwise pin just reporting 'None'
    it.start()
    time.sleep(0.5)

    # ------ start collect data ------
    for n in range(32):
        # logging.debug('IR channel '+str(n+1)+'...')
        print("IR channel " + str(n + 1) + "...")
        t = []
        v = []
        t0 = time.time()
        if n < 16:  # It's on the first mutiplexer
            mux.SwitchMUX(PinS, n)
            time.sleep(0.1)
            for m in range(num_of_data):
                t.append(time.time() - t0)
                v.append(
                    float(mux.Read(PinSig))
                )  # mux returns a string, need to transfer to float number
                time.sleep(0.000001)
            Data['Time' + str(n + 1)] = t
            Data['Chan' + str(n + 1)] = v

        else:  # switch to the second mutiplexer, need to re-define channel number
            m = n - 16
            mux.SwitchMUX(PinS2, m)
            time.sleep(0.1)
            for m in range(num_of_data):
                t.append(time.time() - t0)
                v.append(
                    float(mux.Read(PinSig2))
                )  # MUX returns a string, need to transfer to float number
                time.sleep(0.000001)
            Data['Time' + str(n + 1)] = t
            Data['Chan' + str(n + 1)] = v

    ir_board.exit()
    np.save(
        os.path.join(file_dir, ir_name), Data
    )  # use np.load(filename) to read data, and dict will be in .item()

    freq = []
    drops = []
    for i in range(32):
        time_title = 'Time' + str(i + 1)
        chan_title = 'Chan' + str(i + 1)
        time_stamp = Data[time_title]
        ir = Data[chan_title]
        ir = np.array(ir)  # convert list to array, for the following process

        rel_ir = -1 * ir + max(ir)
        cut_height = 0.3 * max(rel_ir)
        spec_cut_half = rel_ir - cut_height
        fwhm_index = np.where(np.diff(np.sign(spec_cut_half)))[0]
        peak_numbs = len(fwhm_index) / 2
        # time lapse between reading is 1ms, the unit below is ms
        liq_total_time = sum(counter > cut_height for counter in rel_ir)

        freq.append(peak_numbs / (time_stamp[-1] - time_stamp[0]))  # unit Hz
        drops.append(liq_total_time / peak_numbs)  # unit: ms/drop

    print('########### Droplet frequency is  ' + str(np.mean(freq)) +
          '  Hz ##############')
    print('########### Droplet size is  ' + str(np.mean(drops)) +
          '  ms/drop ##############')

    logging.debug('Exiting')
Пример #6
0
class Mux():
    muxChannel = [[0, 0, 0, 0], # channel 1
                  [1, 0, 0, 0], # channel 2
                  [0, 1, 0, 0], # channel 3
                  [1, 1, 0, 0], # channel 4
                  [0, 0, 1, 0], # channel 5
                  [1, 0, 1, 0], # channel 6
                  [0, 1, 1, 0], # channel 7
                  [1, 1, 1, 0], # channel 8
                  [0, 0, 0, 1], # channel 9
                  [1, 0, 0, 1], # channel 10
                  [0, 1, 0, 1], # channel 11
                  [1, 1, 0, 1], # channel 12
                  [0, 0, 1, 1], # channel 13
                  [1, 0, 1, 1], # channel 14
                  [0, 1, 1, 1], # channel 15
                  [1, 1, 1, 1]] # channel 16

    def __init__(self, cfg):
        # load the config
        self.cfg = cfg
        self.board = ArduinoMega(cfg['ARDUINO_PORT'])

        # iterator thread for reading analog pins
        # self.iter = util.Iterator(self.board)
        # self.iter.start()
        # print("iterator running.")

        # set the select pins as arduino digital pins
        self.s_pin_num = cfg['MUX_SELECT_PINS']
        self.s_pins = [self.board.get_pin('d:' + str(self.s_pin_num[0]) + ':o'),
                       self.board.get_pin('d:' + str(self.s_pin_num[1]) + ':o'),
                       self.board.get_pin('d:' + str(self.s_pin_num[2]) + ':o'),
                       self.board.get_pin('d:' + str(self.s_pin_num[3]) + ':o')]
        # set the signal pin
        # self.sig_pin = self.board.get_pin('d:' + str(cfg['MUX_SIG_PIN']) + ':o')

        # TODO: add some stuff to separate digital and analog pins
        self.sig_pin = self.board.get_pin('a:0:i')

        print("Mux connected.")

    def run(self):
        # TODO: Debugging
        for j in range(0, 5):
            for i in range(0, 3):
                print("channel: " + str(i))
                self.switch_mux(i, 1)

        # exit cleanly
        self.shutdown()

        return 0

    def switch_mux(self, channel, wait_s):
        """
        @about: switch mux signal pin to specified channel for specified time.
        @param: channel to switch the multiplexer to
        @param: wait_s delay time to stay at channel. sometimes the readings
                would take longer to "switch"
        """
        # write to selecter pins to specify the mux output channel
        for i in range(0, 4):
            self.s_pins[i].write(self.muxChannel[channel][i])

        time.sleep(wait_s)

        return 0

    def write_mux(self, channel, wait_s, pin_value):
        """
        @about: call switch mux to switch mux channel. Write to signal pin with
                pin_value.
        # TODO: used for debugging
        """
        # call switch_mux to change the mux channel
        self.switch_mux(channel, wait_s)

        # do something with the LED's
        self.sig_pin.write(pin_value)
        time.sleep(wait_s)
        self.sig_pin.write(0)

        return 0

    def read_analog_resistance(self):
        """
        @brief: (FOR DEBUGGING) read the analog input pin and calculate the resistance
                using a voltage divider
        """
        R_IN = 220.0
        V_IN = 5.0
        V_out = self.sig_pin.read() * V_IN # rescale it to the 5V bar
        R_out = (R_IN * V_out/V_IN) / (1.0 - (V_out/V_IN))
        print('R = %.2f' % R_out)

        return R_out

    def shutdown(self):
        """
        @brief: close connection to board.
        """
        self.board.exit()
        print('Closed connection to mux.')

        return 0
Пример #7
0
# vim:fenc=utf-8
#
# Copyright © 2015 cameron <cameron@Megatron-Virtual>
#
# Distributed under terms of the MIT license.

"""
This is a second attempt to reading analog
"""

from pyfirmata import ArduinoMega, util
import time
import os

port = '/dev/ttyACM0'
board = ArduinoMega(port)
time.sleep(5)
it = util.Iterator(board)
it.start()
sensor = board.get_pin('a:0:i')

try:
    while True:
        value = sensor.read()
        print value
        print(type(value))
        time.sleep(1)
except KeyboardInterrupt:
    board.exit()
    os._exit()
Пример #8
0
    if pygame.mixer.music.get_busy() == False:
        board.digital[numeroled].write(0)


# Main

while True:

    randomtrigger = str(botonrandom.read())
    if randomtrigger == 'True':
        activarrandom()
        randomtrigger == False
    activaboton(button2, led_pin3, "3.aiff")
    activaboton(button4, led_pin5, "5.aiff")
    activaboton(button6, led_pin7, "7.aiff")
    activaboton(button8, led_pin9, "9.aiff")
    activaboton(button10, led_pin11, "11.aiff")
    activaboton(button12, led_pin13, "13.aiff")
    activaboton(button30, led_pin31, "31.aiff")
    activaboton(button32, led_pin33, "33.aiff")
    activaboton(button34, led_pin35, "35.aiff")
    activaboton(button36, led_pin37, "37.aiff")
    activaboton(button38, led_pin39, "39.aiff")
    activaboton(button40, led_pin41, "41.aiff")
    activaboton(button42, led_pin43, "43.aiff")
    activaboton(button45, led_pin45, "45.aiff")
    activaboton(button47, led_pin47, "47.aiff")
    activaboton(button49, led_pin49, "49.aiff")

board.exit()