Example #1
0
	def __init__(self,valveP=6,valveS1=2,valveS2=3,valveS3=4,valveS4=5,pump1D=8,pump1S=9,pump2D=12,pump2S=11):#the defaults are the pins that I assume will be connected to the valves
		try:
			Arduino.__init__(self) #connect to arduino REMOVE THE PORT!!
		except ValueError:
			logging.warning('Error! Arduino was not found')
			return
		self.valveP=valveP
		self.valveS1=valveS1
		self.valveS2=valveS2
		self.valveS3=valveS3
		self.valveS4=valveS4#
		self.valveList=[self.valveP,self.valveS1,self.valveS2,self.valveS3,self.valveS4]
		self.pump1D=pump1D#
		self.pump1S=pump1S
		self.pump2D=pump2D
		self.pump2S=pump2S
		self.pinMode(self.valveP,'Output')#
		self.digitalWrite(self.valveP,'HIGH')
		self.pinMode(self.valveS1,'Output')
		self.digitalWrite(self.valveS1,'HIGH')
		self.pinMode(self.valveS2,'Output')
		self.digitalWrite(self.valveS2,'HIGH')
		self.pinMode(self.valveS3,'Output')
		self.digitalWrite(self.valveS3,'HIGH')
		self.pinMode(self.valveS4,'Output')
		self.digitalWrite(self.valveS4,'HIGH')
		self.pinMode(self.pump1D,'Output')#
		self.pinMode(self.pump1S,'Output')
		self.pinMode(self.pump2D,'Output')
		self.pinMode(self.pump2S,'Output')
    def __init__(self):
        #Connect to Arduino, Algo and Android
        self.arduino = Arduino()
        self.algorithm = Algorithm()
        self.android = Android()

        self.manager = Manager()
        self.MDF_LIST = self.manager.list([0])
        self.IMAGE_LIST = self.manager.list()

        #Messages from various modules are placed in this queue before being read
        self.message_queue = self.manager.Queue()

        #Messages to android are placed in this queue
        self.to_android_message_queue = self.manager.Queue()

        self.read_arduino_process = Process(target=self._read_arduino)
        self.read_algorithm_process = Process(target=self._read_algorithm)
        self.read_android_process = Process(target=self._read_android)

        self.write_process = Process(target=self._write_target)
        self.write_android_process = Process(target=self._write_android)
        print('Multi Process initialized')

        self.dropped_connection = Value('i', 0)

        #For image rec
        self.image_process = Process(target=self._process_pic)

        #Pictures taken by RPICAM put in this queue to avoid sending all at once
        self.image_queue = self.manager.Queue()
Example #3
0
def ButtonTry():
    currPin = 0
    board = Arduino(9600, "")
    board.pinMode(8, "INPUT")
    i = 0
    Counter = 7
    while True:
        inp = board.analogRead(0)
        i = i + 1
        print "[" + str(i) + "]\t" + str(inp)
        if inp > 0:
            Counter = Counter - 1
            if Counter <= 1:
                message = client.messages.create(body="'Hey there! Looks like your medication needs to be restocked! We have taken care of that for you! Ready to be picked up whenever you are ready :)", 
                to="+19737234645", 
                from_="+12677133663")
                #print message.sid
                #Counter = 7
            elif Counter < (7 / 2):
                message = client.messages.create(body="'Hey there! Looks like your doing okay there friend! Make sure your taking your medication on time!", 
                to="+19737234645", 
                from_="+12677133663")
        else:
           print "YOU ARE GOOD TO GO"
        #print board.digitalRead(led_pin)  # confirm HIGH (1)
        time.sleep(0.2)
Example #4
0
def ButtonTry():
    currPin = 0
    board = Arduino(9600, "")
    board.pinMode(8, "INPUT")
    i = 0
    Counter = 7
    while True:
        inp = board.analogRead(0)
        i = i + 1
        print "[" + str(i) + "]\t" + str(inp)
        if inp > 0:
            Counter = Counter - 1
            if Counter <= 1:
                message = client.messages.create(
                    body=
                    "'Hey there! Looks like your medication needs to be restocked! We have taken care of that for you! Ready to be picked up whenever you are ready :)",
                    to="+19737234645",
                    from_="+12677133663")
                #print message.sid
                #Counter = 7
            elif Counter < (7 / 2):
                message = client.messages.create(
                    body=
                    "'Hey there! Looks like your doing okay there friend! Make sure your taking your medication on time!",
                    to="+19737234645",
                    from_="+12677133663")
        else:
            print "YOU ARE GOOD TO GO"
        #print board.digitalRead(led_pin)  # confirm HIGH (1)
        time.sleep(0.2)
Example #5
0
	def __init__(self,valve1=2,valve2=4,pump1D=8,pump1S=9,pump2D=12,pump2S=11,led1=5,led2=10,sensor='A05'):#the defaults are the pins that I assume will be connected to the valves
		try:
			Arduino.__init__(self) #connect to arduino REMOVE THE PORT!!
		except ValueError:
			logging.warning('Error! Arduino was not found')
			return
		self.valve1=valve1
		self.valve2=valve2
		#self.valve3=valve3
		self.pump1D=pump1D
		self.pump1S=pump1S
		self.pump2D=pump2D
		self.pump2S=pump2S
		self.led1=led1
		self.led2=led2
		self.pinMode(self.valve1,'Output')
		self.digitalWrite(self.valve1,'HIGH')
		self.pinMode(self.valve2,'Output')
		self.digitalWrite(self.valve2,'HIGH')
		#self.pinMode(self.valve3,'Output')
		#self.digitalWrite(self.valve3,'HIGH')
		self.pinMode(self.pump1D,'Output')
		self.pinMode(self.pump1S,'Output')
		self.pinMode(self.pump2D,'Output')
		self.pinMode(self.pump2S,'Output')
		self.pinMode(self.led1,'Output')
		self.pinMode(self.led2,'Output')
		self.sensor=sensor
Example #6
0
def Blink(led_pin, baud, port=""):
    board = Arduino(baud, port=port)
    board.pinMode(led_pin, "OUTPUT")
    while True:

        board.digitalWrite(led_pin, "HIGH")
        #print board.digitalRead(led_pin)  # confirm HIGH (1)
        time.sleep(1)
Example #7
0
	def __init__(self, *args, **kwargs):
		Thread.__init__(self)
		Arduino.__init__(self, *args, **kwargs)
		
		self.lock = Lock()
		
		self._kill = False
		self.start()
Example #8
0
 def __init__(self):
     GPIO.setmode(GPIO.BCM)
     self.sensor_x = UltrasonicSensor(18, 24, GPIO)
     self.sensor_z = UltrasonicSensor(17, 23, GPIO)
     self.arduino = Arduino(arduino_device)
     self.server = TcpServer()
     self.eye = TargetDetection(True)
     self.end_switch = EndSwitch(GPIO)
     self.logger = Log.instance('Brain')
     self.initial_distance_mm, _ = self.distances(z=False)
Example #9
0
def Lighting():
    currPin = 0
    board = Arduino(9600, "")
    board.pinMode(0, "OUTPUT")
    i = 0
    while True:
        #board.analogWrite(0,65)
        i = i + 1
        print "[" + str(i) + "]\t" 
        #print board.digitalRead(led_pin)  # confirm HIGH (1)
        time.sleep(0.1)
Example #10
0
def Lighting():
    currPin = 0
    board = Arduino(9600, "")
    board.pinMode(0, "OUTPUT")
    i = 0
    while True:
        #board.analogWrite(0,65)
        i = i + 1
        print "[" + str(i) + "]\t"
        #print board.digitalRead(led_pin)  # confirm HIGH (1)
        time.sleep(0.1)
Example #11
0
def main():
    db = DatabaseInterface("riddell.dev")
    arduino = Arduino()

    data = arduino.read_sensors_with_retry()

    db.log_atmosphere(data["temperature"], data["humidity"])

    db.log_environmental(data["light"])

    db.log_soil(data["moisture"])
def adjustBrightness(pot_pin, led_pin, baud, port=""):
    """
    Adjusts brightness of an LED using a
    potentiometer.
    """
    board = Arduino(baud, port=port)
    while True:
        time.sleep(0.01)
        val = board.analogRead(pot_pin) / 4
        print val
        board.analogWrite(led_pin, val)
Example #13
0
def adjustBrightness(pot_pin, led_pin, baud, port=""):
    """
    Adjusts brightness of an LED using a
    potentiometer.
    """
    board = Arduino(baud, port=port)
    while True:
        time.sleep(0.01)
        val = board.analogRead(pot_pin) / 4
        print val
        board.analogWrite(led_pin, val)
Example #14
0
def Button():
    currPin = 0
    board = Arduino(9600, "")
    board.pinMode(8, "INPUT")
    i = 0
    while True:
        inp = board.analogRead(0)
        i = i + 1
        print "[" + str(i) + "]\t" + str(inp)

        #print board.digitalRead(led_pin)  # confirm HIGH (1)
        time.sleep(0.1)
Example #15
0
def Button():
    currPin = 0
    board = Arduino(9600, "")
    board.pinMode(8, "INPUT")
    i = 0
    while True:
        inp = board.analogRead(0)
        i = i + 1
        print "[" + str(i) + "]\t" + str(inp)

        #print board.digitalRead(led_pin)  # confirm HIGH (1)
        time.sleep(0.1)
Example #16
0
 def test_find(self):
     """ Tests auto-connection/board detection. """
     input(
         'Plug in Arduino board w/LED at pin 13, reset, then press enter')
     from Arduino import Arduino
     board = None
     try:
         # This will trigger automatic port resolution.
         board = Arduino(9600)
     finally:
         if board:
             board.close()
def Blink(led_pin,baud, port = ""):
    """
    Blinks an LED in 1 sec intervals
    """
    board = Arduino(baud, port=port)
    while True:
        board.digitalWrite(led_pin,"LOW")
        print board.digitalRead(led_pin) #confirm LOW (0)
        time.sleep(1)
        board.digitalWrite(led_pin,"HIGH")
        print board.digitalRead(led_pin) #confirm HIGH (1)
        time.sleep(1)
 def test_find(self):
     """ Tests auto-connection/board detection. """
     raw_input(
         'Plug in Arduino board w/LED at pin 13, reset, then press enter')
     from Arduino import Arduino
     board = None
     try:
         # This will trigger automatic port resolution.
         board = Arduino(9600)
     finally:
         if board:
             board.close()
def Stepper(baud, port, steps, pin1, pin2, pin3=0, pin4=0, speed=120):
    """
    Steps
    """
    board = Arduino(baud, port=port)
    board.pinMode(13, "OUTPUT")
    board.Stepper.attach(steps,pin1, pin2, pin3, pin4)
    board.Stepper.speed(pin1, speed)
    while True:
        board.Stepper.step(pin1, steps)
        time.sleep(1)
        board.Stepper.step(pin1, -steps)
        time.sleep(1)
def PingSonar(pw_pin, baud, port=""):
    """
    Gets distance measurement from Ping)))
    ultrasonic rangefinder connected to pw_pin
    """
    board = Arduino(baud, port=port)
    pingPin = pw_pin
    while True:
        duration = board.pulseIn(pingPin, "HIGH")
        inches = duration / 72. / 2.
        # cent = duration / 29. / 2.
        print inches, "inches"
        time.sleep(0.1)
Example #21
0
def PingSonar(pw_pin, baud, port=""):
    """
    Gets distance measurement from Ping)))
    ultrasonic rangefinder connected to pw_pin
    """
    board = Arduino(baud, port=port)
    pingPin = pw_pin
    while True:
        duration = board.pulseIn(pingPin, "HIGH")
        inches = duration / 72. / 2.
        # cent = duration / 29. / 2.
        print inches, "inches"
        time.sleep(0.1)
Example #22
0
def softBlink(led_pin, baud, port=""):
    """
    Fades an LED off and on, using
    Arduino's analogWrite (PWM) function
    """
    board = Arduino(baud, port=port)
    i = 0
    while True:
        i += 1
        k = i % 510
        if k % 5 == 0:
            if k > 255:
                k = 510 - k
            board.analogWrite(led_pin, k)
def softBlink(led_pin, baud, port=""):
    """
    Fades an LED off and on, using
    Arduino's analogWrite (PWM) function
    """
    board = Arduino(baud, port=port)
    i = 0
    while True:
        i += 1
        k = i % 510
        if k % 5 == 0:
            if k > 255:
                k = 510 - k
            board.analogWrite(led_pin, k)
Example #24
0
def adjustServoAngle(pot_pin, servo_pin):
    """
    使用电位计调整伺服角度
    Adjusts adjustServoAngle using a
    potentiometer.
    """
    board = Arduino(port=port)
    while True:
        val = board.analogRead(pot_pin)
        val = my_map(val, 0, 1023, 0,
                     180)  #Map potentiometer values to 0-180 degree
        print(val)
        board.Servos.attach(servo_pin)  #attach the servo pin
        board.Servos.write(servo_pin, val)  #write (servoPin,Angle)
Example #25
0
def Count_time(start_time):
    # board = Arduino()
    global i
    global last_beep
    global last_space
    global random_int
    global beep_start_time
    global processed_output
    global interval
    global letter_list
    global osc_client
    global MORSE_CODE_DICT
    processed_output = ""
    letter_list = ""
    board = Arduino("115200", port="/dev/cu.SLAB_USBtoUART")
    output_list = [1]
    interval = 100  #miliseconds
    time_since_last = 0
    is_beep = 0

    while True:
        with open("morse_photo2.txt", "a+") as binary_file:
            val = board.analogRead(4)
            osc_client = udp_client.SimpleUDPClient("127.0.0.1", 5005)
            current_time = time() - start_time
            current_ms = s_to_ms(current_time)
            # print(val)
            if (current_ms > interval * time_since_last):
                # print("computing window")
                val_sum = 0
                for val in output_list:
                    val_sum += val
                mean_value = val_sum / (len(output_list))
                # print(mean_value)
                if mean_value < 10:

                    is_beep = 0
                else:

                    is_beep = 1
                parse_window(is_beep, binary_file)
                parse_gap_window(is_beep, binary_file)
                last_beep = is_beep
                output_list = [0]
                time_since_last += 1
            else:
                # return False
                output_list.append(val)
Example #26
0
 def __init__(self, baud=9600, port=None, init=False):
     if not self._init and not init:
         mensaje = "Arudino no fue inicializado usar la funcion iniciar_arduino()!"
         raise Exception(mensaje)
     if self._init and init:
         mensaje = "Arudino ya fue inicializado anteriormente!"
         raise Exception(mensaje)
     if init:
         self._init = True
     if not self._setted:
         try:
             Arduino.__init__(self, baud, port)
         except:
             mock_serial = ArduinoFalso(baud, '/dev/ttyACM0')
             Arduino.__init__(self, sr=mock_serial)
         self._setted = True
def softBlink(led_pin,port="COM14"):
    """
    Fades an LED off and on, using
    Arduino's analogWrite (PWM) function
    """
    board = Arduino(port=port)
    while board.pinMode(led_pin, "OUTPUT")!=1:#定义13脚为输出,控制LED亮灭
          board.pinMode(led_pin, "OUTPUT") 
    i = 0
    while True:
        i += 1
        k = i % 510
        if k % 5 == 0:
            if k > 255:
                k = 510 - k
            board.analogWrite(led_pin, k)
Example #28
0
 def test_open(self):
     """ Tests connecting to an explicit port. """
     port = None
     while not port:
         port = input(
             'Plug in Arduino board w/LED at pin 13, reset.\n'\
             'Enter the port where the Arduino is connected, then press enter:')
         if not port:
             print('You must enter a port.')
     from Arduino import Arduino
     board = None
     try:
         board = Arduino(9600, port=port)
     finally:
         if board:
             board.close()
Example #29
0
 def __init__(self):
     self.drive_mag = 0
     self.min_val = -60
     self.max_val = 30
     self.steps_beyond_done = None
     self.state = None
     self.board = Arduino()
 def test_open(self):
     """ Tests connecting to an explicit port. """
     port = None
     while not port:
         port = raw_input(
             'Plug in Arduino board w/LED at pin 13, reset.\n'\
             'Enter the port where the Arduino is connected, then press enter:')
         if not port:
             print 'You must enter a port.'
     from Arduino import Arduino
     board = None
     try:
         board = Arduino(9600, port=port)
     finally:
         if board:
             board.close()
class CommonHardwareArduino(object):
    """
    Class for interfacing with arduino device over usb
    """

    def __init__(self, baud_rate='9600', device_port="/dev/ttyACM0"):
        self.arduino_device = Arduino(baud_rate, port=device_port)

    # 'LOW'
    def com_arduino_usb_serial_digitalwrite(self, pin_number, pin_high_low='HIGH'):
        self.arduino_device.digitalWrite(pin_number, pin_high_low)

    def com_arduino_usb_serial_writestring(self, serial_string):
        self.arduino_device.SoftwareSerial.write(serial_string)

    def com_arduino_usb_serial_receivestring(self):
        pass
Example #32
0
    def on_activate(self):
        self._min = int(self._deg0)
        self._max = self._min + (int(self._deg90) - self._min) * 2

        self._board = Arduino(baud=self._baud,
                              port=self._arduino_port[0],
                              timeout=self._timeout)
        self._attach()
Example #33
0
def LCD(tx, baud, ssbaud, message, port=""):
    """
    Prints to two-line LCD connected to
    pin tx
    """
    board = Arduino(baud, port=port)
    board.SoftwareSerial.begin(0, tx, ssbaud)
    while True:
        board.SoftwareSerial.write(" test ")
Example #34
0
    def initDevices(self, config):
        """
        Prepare the arduino, the LED, the motor, and the composite mars object with corresponding VALMAR and devicehash
        for jetson.
        :param config:
        :return:
        """

        #self._arduino.arduinoPowerOn()
        logger.info("Connecting arduino...")
        myArduino = Arduino(config)
        time.sleep(.5)

        #Flush buffers
        myArduino.flushBuffers()

        logger.info("Starting Mars...")
        myPinHash = {
            'resetArduino': GpioPin(57),
            'connectionLED': GpioPin(163),
            'warningLED': GpioPin(164),
            'batteryLED': GpioPin(165),
            'motorRelay': GpioPin(166),
            'ledRelay': GpioPin(160),
            'laserRelay': GpioPin(161),
            'relay4': GpioPin(162)
        }
        myLED = LED()
        myMotor = Motor()
        myMars = Mars(myArduino, config, myLED, myMotor, myPinHash,
                      self._watchdogQueue, self._marsOnlineQueue)
        time.sleep(.5)
        myValmar = Valmar(config)
        myValmar.enable()

        devices = {
            'Motor': myMotor,
            'LED': myLED,
            'Mars': myMars,
            'Arduino': myArduino,
            'Valmar': myValmar,
            'pinHash': myPinHash
        }
        return devices
Example #35
0
    def _update_ports(self, delay):
        while not self._stop:
            if DEBUG:
                pass

            # Get all ports
            ports = list(serial.tools.list_ports.comports())

            # Check all ports
            for p in ports:
                if not p[0] in self._available_ports:
                    self._available_ports.append(p[0])  # Set port to in-use
                    arduino = Arduino(p[0], self._model)
                    self._available_arduinos.append(
                        arduino)  # Add a new arduino to our list
                    arduino.start()
                    if DEBUG:
                        print('Added new Arduino on port: {0}'.format(
                            color(p[0], COLORS.CYAN, TextStyle.HIGHLIGHT)))

            # Remove inactive ports
            for k in self._available_ports:
                r = 1
                for p in ports:
                    if k == p[0]:
                        r = 0
                        break
                if r:
                    self._available_ports.remove(
                        k)  # Remove this port from our active list
                    if DEBUG:
                        print('Removed inactive port: {0}'.format(
                            color(k, COLORS.YELLOW, TextStyle.HIGHLIGHT)))

            # Update our actual list
            for ard in self._available_arduinos:
                if not ard.get_port() in self._available_ports:
                    ard.stop()
                    self._available_arduinos.remove(
                        ard
                    )  # Remove the reference to this arduino from our active list

            time.sleep(delay)
Example #36
0
def ButtonPill():

    board = Arduino(9600, "")
    i = 0
    Counter = 10
    CounterCopy = Counter

    while True:

        inp = board.analogRead(0)
        i = i + 1
        print "[" + str(i) + "]\t" + str(inp)
        if inp > 0:

            Counter = Counter - 1

            if Counter <= 2:

                message = client.messages.create(
                body="Hey there!\n" +
                "Looks like your medication needs to be restocked!\n" +
                "We have taken care of that for you! Ready to be picked up whenever you are ready :)", 
                to="+19737234645", 
                from_="+12677133663")

                message = client.messages.create(
                body="Hey there!\n" +
                "Looks like Ankita''s medication needs to be restocked!\n" +
                "We have taken informed her as well!", 
                to="+14702633590", 
                from_="+12677133663")
            
            elif Counter < (CounterCopy/2):

                message = client.messages.create(
                body="Hey there!\n" +
                "Looks like your doing well there friend!\n" +
                "Make sure your taking your medication on time!", 
                to="+19737234645", 
                from_="+12677133663")

        time.sleep(0.3)
Example #37
0
def ButtonPill():

    board = Arduino(9600, "")
    i = 0
    Counter = 10
    CounterCopy = Counter

    while True:

        inp = board.analogRead(0)
        i = i + 1
        print "[" + str(i) + "]\t" + str(inp)
        if inp > 0:

            Counter = Counter - 1

            if Counter <= 2:

                message = client.messages.create(
                    body="Hey there!\n" +
                    "Looks like your medication needs to be restocked!\n" +
                    "We have taken care of that for you! Ready to be picked up whenever you are ready :)",
                    to="+19737234645",
                    from_="+12677133663")

                message = client.messages.create(
                    body="Hey there!\n" +
                    "Looks like Ankita''s medication needs to be restocked!\n"
                    + "We have taken informed her as well!",
                    to="+14702633590",
                    from_="+12677133663")

            elif Counter < (CounterCopy / 2):

                message = client.messages.create(
                    body="Hey there!\n" +
                    "Looks like your doing well there friend!\n" +
                    "Make sure your taking your medication on time!",
                    to="+19737234645",
                    from_="+12677133663")

        time.sleep(0.3)
Example #38
0
    def __init__(self):
        """
        Sets up program variables, resets files, does not tell arduino to start
        """
        GPIO.setmode(GPIO.BCM)
        self.ei = ErrorIndicator(False)
        self.ih = ImageHandler(False, self.ei)
        self.processor = ImageProcessor(self.ih, self.ei)
        self.arduino = Arduino(self.ei)
        GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.setup(25, GPIO.IN)
        GPIO.setwarnings(False)

        if os.path.exists("out/"):
            shutil.rmtree("out")
        os.makedirs("out")
        if os.path.exists("log.txt"):
            os.remove("log.txt")

        Log.setup_log()
Example #39
0
def run():
    arduino = Arduino(testMotor=(-100, 100), steering=(0, 179), button=None)

    count = 5
    for _ in xrange(count):
        for value in xrange(0, 180):
            arduino['steering'] = value
            time.sleep(0.005)

        for value in xrange(179, -1, -1):
            arduino['steering'] = value
            time.sleep(0.005)
def softBlink(led_pin, baud, port=""):
    """
    Fades an LED off and on, using
    Arduino's analogWrite (PWM) function
    """
    board = Arduino(baud, port=port)
    board.pinMode(led_pin, "OUTPUT")

    step = 4
    while True:
        for k in range(0, 256, step):
            board.analogWrite(led_pin, k)
        for k in range(k - step, -1, -step):
            board.analogWrite(led_pin, k)
Example #41
0
def init():
    global board
    global pin
    pin = 13
    board = Arduino('9600')
    board.pinMode(pin, "OUTPUT")
    board.digitalWrite(pin, "LOW")
Example #42
0
def AccelRead():
    board = Arduino(9600, "")
    board.pinMode(13, "OUTPUT")

    cX = 0
    cY = 0
    cZ = 0

    while True:
        analogX = board.analogRead(2)
        analogY = board.analogRead(1)
        analogZ = board.analogRead(0)

        if abs(analogX - cX) > 5:
            #abs(analogX - cX) > 5 | abs(analogY - cY) > 5 |
            print "X:" + str(analogX) + "Y:" + str(analogY) + "Z:" + str(
                analogZ)
            cX = analogX
            cY = analogY
            #print "X:" + str(analogX)
            cX = analogX

        #board.digitalWrite(13, "HIGH")
        #print board.digitalRead(led_pin)  # confirm HIGH (1)
        time.sleep(0.01)
Example #43
0
def Blink(led_pin, baud, port=""):
    board = Arduino(baud, port=port)
    board.pinMode(led_pin, "OUTPUT")
    while True:

        board.digitalWrite(led_pin, "HIGH")
        #print board.digitalRead(led_pin)  # confirm HIGH (1)
        time.sleep(1)
Example #44
0
def Blink(led_pin, baud, port=""):
    """
    Blinks an LED in 1 sec intervals
    """
    board = Arduino(baud, port=port)
    board.pinMode(13, "INPUT")
    while True:
        board.digitalWrite(led_pin, "LOW")
        #print(board.digitalRead(led_pin))  # confirm LOW (0)
        print("OFF")
        time.sleep(1)
        board.digitalWrite(led_pin, "HIGH")
        #print(board.digitalRead(led_pin))  # confirm HIGH (1)
        print("ON")
        time.sleep(1)
Example #45
0
class vacuum:
    def __init__(self):
        self.board=Arduino('9600');
        self.board.pinMode(13, "OUTPUT")

    def on(self):
        self.board.digitalWrite(13,"HIGH");
    def off(self):
        self.board.digitalWrite(13,"LOW");
Example #46
0
def AccelRead():
    board = Arduino(9600, "")
    board.pinMode(13, "OUTPUT")

    cX = 0
    cY = 0
    cZ = 0

    while True:
        analogX = board.analogRead(2)
        analogY = board.analogRead(1)
        analogZ = board.analogRead(0)

        if abs(analogX - cX) > 5:
            #abs(analogX - cX) > 5 | abs(analogY - cY) > 5 | 
            print "X:" + str(analogX) + "Y:" + str(analogY) +"Z:" + str(analogZ)
            cX = analogX
            cY = analogY
            #print "X:" + str(analogX)
            cX = analogX
            
        #board.digitalWrite(13, "HIGH")
        #print board.digitalRead(led_pin)  # confirm HIGH (1)
        time.sleep(0.01)
Example #47
0
def Blink(led_pin, baud, port=""):
    """
    Blinks an LED in 1 sec intervals
    """
    board = Arduino(baud, port=port)
    board.pinMode(13, "INPUT")
    while True:
        board.digitalWrite(led_pin, "LOW")
        #print(board.digitalRead(led_pin))  # confirm LOW (0)
        print("OFF")
        time.sleep(1)
        board.digitalWrite(led_pin, "HIGH")
        #print(board.digitalRead(led_pin))  # confirm HIGH (1)
        print("ON")
        time.sleep(1)   
Example #48
0
    def __init__(self, parent=None):
        super(mainApp, self).__init__(parent)
        self.setupUi(self)

        # Load configuration file
        cfgpath = os.path.split(os.path.abspath(sys.argv[0]))[0]
        #if sys.argv[0] in dir():
        #    cfgpath=os.path.split(os.path.abspath(__file__))[0]
        #else: # fix for py2exe
        #    cfgpath=sys.prefix
        cfgpath=os.path.join(cfgpath, "cfg.txt")
        self.cfg=ConfigParser.ConfigParser()
        self.cfg.readfp(open(cfgpath))

        # Detect number of laser lines
        sections = self.cfg.sections()
        if "serial port" not in sections:
            raise Exception, "invalid configuration file"
        self.laserlabels = sections
        self.laserlabels.remove("serial port")
        self.laserlabels.sort()
        self.nlines=len(self.laserlabels)
        self._power=[0]*self.nlines
        self._shutter=[0]*self.nlines
        # Detect arduino board
        if "arduino port" in sections:
            self.arduinoPort = self.cfg.getint("arduino port", "number") - 1
            self.arduinoPin  = self.cfg.getint("arduino pin", "pin")
            self.board = Arduino(9600, port=self.arduinoPort)
            self.board.pinMode(self.arduinoPin, "OUTPUT")

        # define close event
        QtCore.QObject.connect(self, QtCore.SIGNAL('triggered()'), self.closeEvent)

        # bind signal and slot
        for n in xrange(5):
            if n == 0:
                QtCore.QObject.connect(self.laserLine1Shutter,
                QtCore.SIGNAL(_fromUtf8("stateChanged(int)")),
                self.actionShutterLaserLine1)
                QtCore.QObject.connect(self.laserLine1PowerSlider,
                QtCore.SIGNAL(_fromUtf8("valueChanged(int)")),
                self.actionPowerSliderLaserLine1)
                QtCore.QObject.connect(self.laserLine1PowerEdit,
                QtCore.SIGNAL(_fromUtf8("returnPressed()")),
                self.actionPowerEditLaserLine1)
                QtCore.QObject.connect(self.laserLine1Pulse,
                QtCore.SIGNAL(_fromUtf8("clicked()")),
                self.actionPulseLaserLine1)
            elif n == 1:
                QtCore.QObject.connect(self.laserLine2Shutter,
                QtCore.SIGNAL(_fromUtf8("stateChanged(int)")),
                self.actionShutterLaserLine2)
                QtCore.QObject.connect(self.laserLine2PowerSlider,
                QtCore.SIGNAL(_fromUtf8("valueChanged(int)")),
                self.actionPowerSliderLaserLine2)
                QtCore.QObject.connect(self.laserLine2PowerEdit,
                QtCore.SIGNAL(_fromUtf8("returnPressed()")),
                self.actionPowerEditLaserLine2)
                QtCore.QObject.connect(self.laserLine2Pulse,
                QtCore.SIGNAL(_fromUtf8("clicked()")),
                self.actionPulseLaserLine2)
            elif n == 2:
                QtCore.QObject.connect(self.laserLine3Shutter,
                QtCore.SIGNAL(_fromUtf8("stateChanged(int)")),
                self.actionShutterLaserLine3)
                QtCore.QObject.connect(self.laserLine3PowerSlider,
                QtCore.SIGNAL(_fromUtf8("valueChanged(int)")),
                self.actionPowerSliderLaserLine3)
                QtCore.QObject.connect(self.laserLine3PowerEdit,
                QtCore.SIGNAL(_fromUtf8("returnPressed()")),
                self.actionPowerEditLaserLine3)
                QtCore.QObject.connect(self.laserLine3Pulse,
                QtCore.SIGNAL(_fromUtf8("clicked()")),
                self.actionPulseLaserLine3)
            elif n == 3:
                QtCore.QObject.connect(self.laserLine4Shutter,
                QtCore.SIGNAL(_fromUtf8("stateChanged(int)")),
                self.actionShutterLaserLine4)
                QtCore.QObject.connect(self.laserLine4PowerSlider,
                QtCore.SIGNAL(_fromUtf8("valueChanged(int)")),
                self.actionPowerSliderLaserLine4)
                QtCore.QObject.connect(self.laserLine4PowerEdit,
                QtCore.SIGNAL(_fromUtf8("returnPressed()")),
                self.actionPowerEditLaserLine4)
                QtCore.QObject.connect(self.laserLine4Pulse,
                QtCore.SIGNAL(_fromUtf8("clicked()")),
                self.actionPulseLaserLine4)
            elif n == 4:
                QtCore.QObject.connect(self.laserLine5Shutter,
                QtCore.SIGNAL(_fromUtf8("stateChanged(int)")),
                self.actionShutterLaserLine5)
                QtCore.QObject.connect(self.laserLine5PowerSlider,
                QtCore.SIGNAL(_fromUtf8("valueChanged(int)")),
                self.actionPowerSliderLaserLine5)
                QtCore.QObject.connect(self.laserLine5PowerEdit,
                QtCore.SIGNAL(_fromUtf8("returnPressed()")),
                self.actionPowerEditLaserLine5)
                QtCore.QObject.connect(self.laserLine5Pulse,
                QtCore.SIGNAL(_fromUtf8("clicked()")),
                self.actionPulseLaserLine5)
        #QtCore.QObject.connect(self.startRepeatPulse,
        #        QtCore.SIGNAL(_fromUtf8("clicked()")),
        #        self.actionStartPulsing)
        QtCore.QObject.connect(self.seq1Action,
                QtCore.SIGNAL(_fromUtf8("clicked()")),
                self.seq1ActionFcnThread)
        QtCore.QObject.connect(self.seq1Stop,
                QtCore.SIGNAL(_fromUtf8("clicked()")),
                self.seq1ActionFcnThreadTerminater)
        QtCore.QObject.connect(self.repeatPulseIndicator,
                QtCore.SIGNAL(_fromUtf8("stateChanged(int)")),
                self.repeatPulsingThread)
        # Prepare threads and initialize AOTF connection
        self.lock=thread.allocate_lock()
        #   note, on PySerial lib the serial ports are N-1, so serial 2 will be represented by 1
        self.nserial=self.cfg.getint("serial port", "number")-1
        if self.nserial == -1: # Emulation omde
            self.aotfcmd_ = lambda cmd: 1
        else: # Not emulating
            self.aotf=serial.Serial(self.nserial, 19200, timeout=1)
            atexit.register(self.aotf.close)
            self.aotfcmd_('i0')
        self._lastcmd_=time.strftime('%X')
        for n in xrange(5):
            self._shutter[n] = 1
            self.power(n+1, 0)
            self.shutter(n+1, 0)     
            time.sleep(0.01)

        # try statusBar     
        self.statusBar().showMessage('Ready')
        # try menuBar
        #self.menuBar = QtGui.QMenuBar()
        self.menuOperation = QtGui.QMenu()
        self.menuOperation.setTitle('Operation')
        self.actionReset = QtGui.QAction(self)
        self.actionReset.setText('Reset')

        self.menuOperation.addAction(self.actionReset)
        self.menubar.addMenu(self.menuOperation)
        QtCore.QObject.connect(self.actionReset,
                QtCore.SIGNAL('triggered()'),
                self.resetLaser)
Example #49
0
class mainApp(QtGui.QMainWindow, Ui_MainWindow):
    logfile = None
    """docstring for mainApp"""
    def __init__(self, parent=None):
        super(mainApp, self).__init__(parent)
        self.setupUi(self)

        # Load configuration file
        cfgpath = os.path.split(os.path.abspath(sys.argv[0]))[0]
        #if sys.argv[0] in dir():
        #    cfgpath=os.path.split(os.path.abspath(__file__))[0]
        #else: # fix for py2exe
        #    cfgpath=sys.prefix
        cfgpath=os.path.join(cfgpath, "cfg.txt")
        self.cfg=ConfigParser.ConfigParser()
        self.cfg.readfp(open(cfgpath))

        # Detect number of laser lines
        sections = self.cfg.sections()
        if "serial port" not in sections:
            raise Exception, "invalid configuration file"
        self.laserlabels = sections
        self.laserlabels.remove("serial port")
        self.laserlabels.sort()
        self.nlines=len(self.laserlabels)
        self._power=[0]*self.nlines
        self._shutter=[0]*self.nlines
        # Detect arduino board
        if "arduino port" in sections:
            self.arduinoPort = self.cfg.getint("arduino port", "number") - 1
            self.arduinoPin  = self.cfg.getint("arduino pin", "pin")
            self.board = Arduino(9600, port=self.arduinoPort)
            self.board.pinMode(self.arduinoPin, "OUTPUT")

        # define close event
        QtCore.QObject.connect(self, QtCore.SIGNAL('triggered()'), self.closeEvent)

        # bind signal and slot
        for n in xrange(5):
            if n == 0:
                QtCore.QObject.connect(self.laserLine1Shutter,
                QtCore.SIGNAL(_fromUtf8("stateChanged(int)")),
                self.actionShutterLaserLine1)
                QtCore.QObject.connect(self.laserLine1PowerSlider,
                QtCore.SIGNAL(_fromUtf8("valueChanged(int)")),
                self.actionPowerSliderLaserLine1)
                QtCore.QObject.connect(self.laserLine1PowerEdit,
                QtCore.SIGNAL(_fromUtf8("returnPressed()")),
                self.actionPowerEditLaserLine1)
                QtCore.QObject.connect(self.laserLine1Pulse,
                QtCore.SIGNAL(_fromUtf8("clicked()")),
                self.actionPulseLaserLine1)
            elif n == 1:
                QtCore.QObject.connect(self.laserLine2Shutter,
                QtCore.SIGNAL(_fromUtf8("stateChanged(int)")),
                self.actionShutterLaserLine2)
                QtCore.QObject.connect(self.laserLine2PowerSlider,
                QtCore.SIGNAL(_fromUtf8("valueChanged(int)")),
                self.actionPowerSliderLaserLine2)
                QtCore.QObject.connect(self.laserLine2PowerEdit,
                QtCore.SIGNAL(_fromUtf8("returnPressed()")),
                self.actionPowerEditLaserLine2)
                QtCore.QObject.connect(self.laserLine2Pulse,
                QtCore.SIGNAL(_fromUtf8("clicked()")),
                self.actionPulseLaserLine2)
            elif n == 2:
                QtCore.QObject.connect(self.laserLine3Shutter,
                QtCore.SIGNAL(_fromUtf8("stateChanged(int)")),
                self.actionShutterLaserLine3)
                QtCore.QObject.connect(self.laserLine3PowerSlider,
                QtCore.SIGNAL(_fromUtf8("valueChanged(int)")),
                self.actionPowerSliderLaserLine3)
                QtCore.QObject.connect(self.laserLine3PowerEdit,
                QtCore.SIGNAL(_fromUtf8("returnPressed()")),
                self.actionPowerEditLaserLine3)
                QtCore.QObject.connect(self.laserLine3Pulse,
                QtCore.SIGNAL(_fromUtf8("clicked()")),
                self.actionPulseLaserLine3)
            elif n == 3:
                QtCore.QObject.connect(self.laserLine4Shutter,
                QtCore.SIGNAL(_fromUtf8("stateChanged(int)")),
                self.actionShutterLaserLine4)
                QtCore.QObject.connect(self.laserLine4PowerSlider,
                QtCore.SIGNAL(_fromUtf8("valueChanged(int)")),
                self.actionPowerSliderLaserLine4)
                QtCore.QObject.connect(self.laserLine4PowerEdit,
                QtCore.SIGNAL(_fromUtf8("returnPressed()")),
                self.actionPowerEditLaserLine4)
                QtCore.QObject.connect(self.laserLine4Pulse,
                QtCore.SIGNAL(_fromUtf8("clicked()")),
                self.actionPulseLaserLine4)
            elif n == 4:
                QtCore.QObject.connect(self.laserLine5Shutter,
                QtCore.SIGNAL(_fromUtf8("stateChanged(int)")),
                self.actionShutterLaserLine5)
                QtCore.QObject.connect(self.laserLine5PowerSlider,
                QtCore.SIGNAL(_fromUtf8("valueChanged(int)")),
                self.actionPowerSliderLaserLine5)
                QtCore.QObject.connect(self.laserLine5PowerEdit,
                QtCore.SIGNAL(_fromUtf8("returnPressed()")),
                self.actionPowerEditLaserLine5)
                QtCore.QObject.connect(self.laserLine5Pulse,
                QtCore.SIGNAL(_fromUtf8("clicked()")),
                self.actionPulseLaserLine5)
        #QtCore.QObject.connect(self.startRepeatPulse,
        #        QtCore.SIGNAL(_fromUtf8("clicked()")),
        #        self.actionStartPulsing)
        QtCore.QObject.connect(self.seq1Action,
                QtCore.SIGNAL(_fromUtf8("clicked()")),
                self.seq1ActionFcnThread)
        QtCore.QObject.connect(self.seq1Stop,
                QtCore.SIGNAL(_fromUtf8("clicked()")),
                self.seq1ActionFcnThreadTerminater)
        QtCore.QObject.connect(self.repeatPulseIndicator,
                QtCore.SIGNAL(_fromUtf8("stateChanged(int)")),
                self.repeatPulsingThread)
        # Prepare threads and initialize AOTF connection
        self.lock=thread.allocate_lock()
        #   note, on PySerial lib the serial ports are N-1, so serial 2 will be represented by 1
        self.nserial=self.cfg.getint("serial port", "number")-1
        if self.nserial == -1: # Emulation omde
            self.aotfcmd_ = lambda cmd: 1
        else: # Not emulating
            self.aotf=serial.Serial(self.nserial, 19200, timeout=1)
            atexit.register(self.aotf.close)
            self.aotfcmd_('i0')
        self._lastcmd_=time.strftime('%X')
        for n in xrange(5):
            self._shutter[n] = 1
            self.power(n+1, 0)
            self.shutter(n+1, 0)     
            time.sleep(0.01)

        # try statusBar     
        self.statusBar().showMessage('Ready')
        # try menuBar
        #self.menuBar = QtGui.QMenuBar()
        self.menuOperation = QtGui.QMenu()
        self.menuOperation.setTitle('Operation')
        self.actionReset = QtGui.QAction(self)
        self.actionReset.setText('Reset')

        self.menuOperation.addAction(self.actionReset)
        self.menubar.addMenu(self.menuOperation)
        QtCore.QObject.connect(self.actionReset,
                QtCore.SIGNAL('triggered()'),
                self.resetLaser)
    def resetLaser(self):
        for n in xrange(5):
            self._shutter[n] = 1
            self.power(n+1, 0.00)            
            self.shutter(n+1, 0)
            time.sleep(0.01)

    def aotfcmd_(self, cmd, wait = 0):
        self.lock.acquire()
        self.aotf.write(cmd+"\r")
        if wait:
            msg=''
            for n in xrange(10000):
                c=self.aotf.read()
                msg+=c
                if c=='?': break
        self.lock.release()
        self._lastcmd_=time.strftime('%X') 
    def shutter(self, channel=1,on=True):
        if self._shutter[channel-1]==on: 
            return 
        self.aotfcmd_("x%d" % (channel), 1)
        if on: 
            self.aotfcmd_("o1", 1)
        else: 
            self.aotfcmd_("o0",1)
        #self._shutter[channel-1]=on
       
    def power(self, channel, percentage):
        if self._power[channel-1]==percentage: return
        p=(float(percentage)/100.)*1023
        if p>1023: p=1023
        elif p<0: p=0
        p=int(round(p))
        self.aotfcmd_("l%dp%s\n\n" % (channel, str(p).zfill(4)))
        self._power[channel-1]=percentage
    ##define laser 1#########################
    def actionShutterLaserLine1(self):
        self.shutter(1, self.laserLine1Shutter.checkState())
        self.msg(1)
    def actionPowerSliderLaserLine1(self):
        #self._power[0] = self.laserLine1PowerSlider.value()
        self.power(1, self.laserLine1PowerSlider.value())
        self.laserLine1PowerEdit.setText(str(self._power[0]))
    def actionPowerEditLaserLine1(self):
        self._power[0] = int(self.laserLine1PowerEdit.text())    
        self.laserLine1PowerSlider.setValue(self._power[0])
        self.power(1, self._power[0])
    def actionPulseLaserLine1(self):
        waitTime = float(self.laserLine1PulseDuration.text())
        #start = time.strftime('%X')
        self.shutter(1, 1)
        time.sleep(waitTime)
        self.shutter(1,0)
        #stop = time.strftime('%X')
        msg  = 'SHUTTER %s: TIME %s AOTF %.2f STATUS %d' % \
        (self.laserlabels[0],time.strftime('%X'),int(self.laserLine1PowerEdit.text()),\
        self.laserLine1Shutter.checkState())
        self.msg(msg)
    ### end define laser 1 ##########################
    ##define laser 2#########################
    def actionShutterLaserLine2(self):
        self.shutter(2,self.laserLine2Shutter.checkState())
        self.msg(2)
    def actionPowerSliderLaserLine2(self):
        #self._power[1] = self.laserLine2PowerSlider.value()
        self.power(2, self.laserLine2PowerSlider.value())
        self.laserLine2PowerEdit.setText(str(self._power[1]))
    def actionPowerEditLaserLine2(self):
        self._power[1] = int(self.laserLine2PowerEdit.text())
        self.power(2,self._power[1])
        self.laserLine2PowerSlider.setValue(self._power[1])
    def actionPulseLaserLine2(self):
        waitTime = float(self.laserLine2PulseDuration.text())
        #start = time.strftime('%X')
        self.shutter(2,1)
        time.sleep(waitTime)
        self.shutter(2,0)
        #stop = time.strftime('%X')
        self.msg(2)
    ### end define laser 2 ##########################
    ##define laser 3#########################
    def actionShutterLaserLine3(self):
        self.shutter(3,self.laserLine3Shutter.checkState())
        self.msg(3)
    def actionPowerSliderLaserLine3(self):
        #self._power[2] = self.laserLine3PowerSlider.value()
        self.power(3, self.laserLine3PowerSlider.value())
        self.laserLine3PowerEdit.setText(str(self._power[2]))
    def actionPowerEditLaserLine3(self):
        self._power[2] = int(self.laserLine3PowerEdit.text())
        self.power(3,self._power[2])
        self.laserLine3PowerSlider.setValue(self._power[2])
    def actionPulseLaserLine3(self):
        waitTime = float(self.laserLine3PulseDuration.text())
        #start = time.strftime('%X')
        self.shutter(3,1)
        time.sleep(waitTime)
        self.shutter(3,0)
        #stop = time.strftime('%X')
        self.msg(3)
    ### end define laser 3 ##########################
    ##define laser 4#########################
    def actionShutterLaserLine4(self):
        self.shutter(4,self.laserLine4Shutter.checkState())
        self.msg(4)
    def actionPowerSliderLaserLine4(self):
        #self._power[3] = self.laserLine4PowerSlider.value()
        self.power(4, self.laserLine4PowerSlider.value())
        self.laserLine4PowerEdit.setText(str(self._power[3]))
    def actionPowerEditLaserLine4(self):
        self._power[3] = int(self.laserLine4PowerEdit.text())
        self.power(4,self._power[3])
        self.laserLine4PowerSlider.setValue(self._power[3])
    def actionPulseLaserLine4(self):#
        waitTime = float(self.laserLine4PulseDuration.text())
        #start = time.strftime('%X')
        self.shutter(4,1)
        time.sleep(waitTime)
        self.shutter(4,0)
        #stop = time.strftime('%X')
        self.msg(4)
    ### end define laser 4 ##########################
    ##define laser 5#########################
    def actionShutterLaserLine5(self):
        self.shutter(5,self.laserLine5Shutter.checkState())
        msg = 'SHUTTER %s: TIME %s AOTF %.2f STATUS %d' % \
        (self.laserlabels[4],time.strftime('%X'),int(round(float(self.laserLine5PowerEdit.text()))),\
        self.laserLine5Shutter.checkState())
        self.msg(msg)
    def actionPowerSliderLaserLine5(self):
        #self._power[4] = self.laserLine5PowerSlider.value()
        self.power(5, self.laserLine5PowerSlider.value())
        self.laserLine5PowerEdit.setText(str(self._power[4]))
    def actionPowerEditLaserLine5(self):
        self._power[4] = int(self.laserLine5PowerEdit.text())
        self.power(5,self._power[4])
        self.laserLine5PowerSlider.setValue(self._power[4])
    def actionPulseLaserLine5(self):
        waitTime = float(self.laserLine5PulseDuration.text())
        #start = time.strftime('%X')
        self.shutter(5,1)
        time.sleep(waitTime)
        self.shutter(5,0)
        #stop = time.strftime('%X')
        self.msg(5)
    ### end define laser 3 ##########################
    
    def actionPulse(self,*arg):
        if len(arg) == 1:
            n = arg[0]
            if (n==1):
                waitTime = float(self.laserLine1PulseDuration.text())
                power    = int(self.laserLine1PowerEdit.text())
            elif (n==2):
                waitTime = float(self.laserLine2PulseDuration.text())
                power    = int(self.laserLine2PowerEdit.text())
            elif n==3:
                waitTime = float(self.laserLine3PulseDuration.text())
                power    = int(self.laserLine3PowerEdit.text())
            elif n==4:
                waitTime = float(self.laserLine4PulseDuration.text())
                power    = int(self.laserLine4PowerEdit.text())
            elif n==5:
                waitTime = float(self.laserLine5PulseDuration.text())
                power    = int(self.laserLine5PowerEdit.text())
            else :
                return
        elif len(arg) == 2:
            n = arg[0]
            power = arg[1]
            if (n==1):
                waitTime = float(self.laserLine1PulseDuration.text())
            elif (n==2):
                waitTime = float(self.laserLine2PulseDuration.text())
            elif n==3:
                waitTime = float(self.laserLine3PulseDuration.text())
            elif n==4:
                waitTime = float(self.laserLine4PulseDuration.text())
            elif n==5:
                waitTime = float(self.laserLine5PulseDuration.text())
            else :
                return
        self.power(n, power)
        #start = time.strftime('%X')
        self.shutter(n, 1)
        time.sleep(waitTime)
        self.shutter(n, 0)
        #stop = time.strftime('%X')
        msg  = 'SHUTTER %s; AOTF %.2f' % (self.laserlabels[n], power)
        self.msg(msg)


    def __repeatPulsing__(self):

        while self.repeatPulseIndicator.isChecked():
                self.repeatPulseIndicator.setText('Stop Pulsing')
                interval = float(self.repeatPulseDuration.text())
                n = self.laserlabels.index(self.selectLaserLine.currentText())
                #print n
                self.actionPulse(n+1)
                time.sleep(interval)                    
        self.repeatPulseIndicator.setText('Start Pulsing')
            #except:
                #time.sleep(0.1)
                #self.pulsingStatus.setText('no'+str(time.strftime('%X')))
   # def closeEvent(self, event):
        #self.aotf.close()
        #self.destroy()
    def msg(self,*arg):
        self.status.setText(str(type(arg)))
        if isinstance(arg[0], str):
            text = arg[0]
            self.status.setText(text)
        elif isinstance(arg[0], int):
            if arg[0] == 1:
                msg  = 'SHUTTER %s: TIME %s AOTF %.2f STATUS %d' % \
                (self.laserlabels[0],time.strftime('%X'),int(round(float(self.laserLine1PowerEdit.text()))),\
                self.laserLine1Shutter.checkState())
            elif arg[0] == 2:
                msg  = 'SHUTTER %s: TIME %s AOTF %.2f STATUS %d' % \
                (self.laserlabels[1],time.strftime('%X'),int(round(float(self.laserLine2PowerEdit.text()))),\
                self.laserLine2Shutter.checkState())
            elif arg[0] == 3:
                msg  = 'SHUTTER %s: TIME %s AOTF %.2f STATUS %d' % \
                (self.laserlabels[2],time.strftime('%X'),int(round(float(self.laserLine3PowerEdit.text()))),\
                self.laserLine3Shutter.checkState())
            elif arg[0] == 4:
                msg  = 'SHUTTER %s: TIME %s AOTF %.2f STATUS %d' % \
                (self.laserlabels[3],time.strftime('%X'),int(round(float(self.laserLine4PowerEdit.text()))),\
                self.laserLine4Shutter.checkState())
            elif arg[0] == 5:
                msg  = 'SHUTTER %s: TIME %s AOTF %.2f STATUS %d' % \
                (self.laserlabels[4],time.strftime('%X'),int(round(float(self.laserLine5PowerEdit.text()))),\
                self.laserLine5Shutter.checkState())
            self.status.setText(msg)
            #if self.logfile!=None:
            #open(self.logfile,'a').write(text+'\n')
        
    def seq1ActionFcn(self):
        ## parse laser intensity
        # laser 1
        laser1Intensity = self.parseInput(self.seq1Laser1Intensity.text())
        laser2Intensity = self.parseInput(self.seq1Laser2Intensity.text())
        if self.triggerCCD.isChecked():
            self.board.digitalWrite(self.arduinoPin, "HIGH")
            print('set HIGH')
        if laser1Intensity is not None:
            print ('go laser1Intensity is no None')
            if laser2Intensity is not None:
                print ('go laser2Intensity is None')
                if len(laser1Intensity) != len(laser2Intensity):
                    em = QtGui.QErrorMessage(self)
                    em.showMessage('Laser Intensity Must be Equal !!')
                    return
                else:
                    for i in range(int(self.seq1NCycles.text())):
                        self.status.setText('Cycle #' + str(i))
                        for iIntensity in range(len(laser1Intensity)):
                            if not self.seq1StopFlag:
                                self.actionPulse(self.seq1Laser1Label.currentIndex()+1, laser1Intensity[iIntensity])
                            else:
                                break
                            if not self.seq1StopFlag:
                                self.actionPulse(self.seq1Laser2Label.currentIndex()+1, laser2Intensity[iIntensity])
                            else:
                                break
            else:
                for i in range(int(self.seq1NCycles.text())):
                    self.status.setText('Cycle #' + str(i + 1))
                    for iIntensity in range(len(laser1Intensity)):
                        if not self.seq1StopFlag:
                            self.actionPulse(self.seq1Laser1Label.currentIndex()+1, laser1Intensity[iIntensity])
                        else:
                            break
                        if not self.seq1StopFlag:
                            self.actionPulse(self.seq1Laser2Label.currentIndex()+1)
                        else:
                            break
        else:
            if laser2Intensity is not None:
                for i in range(int(self.seq1NCycles.text())):
                    self.status.setText('Cycle #' + str(i + 1))
                    for iIntensity in range(len(laser2Intensity)):
                        if not self.seq1StopFlag:
                            self.actionPulse(self.seq1Laser1Label.currentIndex()+1)
                        else:
                            break
                        if not self.seq1StopFlag:
                            self.actionPulse(self.seq1Laser2Label.currentIndex()+1, laser2Intensity[iIntensity])
                        else:
                            break
            else:
                for i in range(int(self.seq1NCycles.text())):
                    self.status.setText('Cycle #' + str(i + 1))
                    if not self.seq1StopFlag:
                        self.actionPulse(self.seq1Laser1Label.currentIndex()+1)
                    else:
                        break
                    if not self.seq1StopFlag:
                        self.actionPulse(self.seq1Laser2Label.currentIndex()+1)
                    else:
                        break 
        self.seq1Action.setEnabled(True)
        self.seq1Stop.setEnabled(False)
        self.board.digitalWrite(self.arduinoPin, "LOW")
        self.status.setText('Cycling illumination protocal finished !!!')
    def seq1ActionFcnThread(self):
        self.seq1Action.setEnabled(False)
        self.seq1Stop.setEnabled(True)
        self.seq1StopFlag = 0
        self.seq1Thread = threading.Thread(target = self.seq1ActionFcn)
        self.seq1Thread.start()
    def seq1ActionFcnThreadTerminater(self):
        if self.seq1Thread.isAlive:
            self.seq1Action.setEnabled(True)
            self.seq1Stop.setEnabled(False)
            self.seq1StopFlag = 1
            self.board.digitalWrite(self.arduinoPin, "LOW")
            #self.seq1Thread.terminate()
    def repeatPulsingThread(self):
        self.repatPulsingThread = threading.Thread(target = self.__repeatPulsing__)
        self.repatPulsingThread.start()
    def parseInput(self,string):
        if string == "":
            return
        else:
            strList = string.split(",");
            outputInt = map(int, strList)
            return outputInt
Example #50
0
	def _get_temperature(self, *args,**kwargs):
		with self.lock:
			return Arduino.get_temperature(self, *args,**kwargs)
Example #51
0
	def _set_programmes(self, *args,**kwargs):
		with self.lock:
			return Arduino.set_programmes(self, *args,**kwargs)
Example #52
0
	def _get_time(self, *args,**kwargs):
		with self.lock:
			return Arduino.get_time(self, *args,**kwargs)
"""

from Arduino import Arduino
import time
import mido
import pygame

"""
Arduino.Servos.attach(pin, min=544, max=2400) Create servo instance. Only 8 servos can be used at one time.
Arduino.Servos.read(pin) Returns the angle of the servo attached to the specified pin
Arduino.Servos.write(pin, angle) Move an attached servo on a pin to a specified angle
Arduino.Servos.writeMicroseconds(pin, uS) Write a value in microseconds to the servo on a specified pin
Arduino.Servos.detach(pin) Detaches the servo on the specified pin
"""

board = Arduino('9600') #plugged in via USB, serial com at rate 9600
board.Servos.attach(4, min=544, max=2400) 
board.Servos.attach(5, min=544, max=2400) 

mid = mido.MidiFile('004.MID')      #read midi file with mido, ready to extract information

playList =[]
timeDelay = []

for msg in mid:                 #extract relevant information, save them into lists
    if not msg.is_meta:
        #print(msg)
        msgList = str(msg).split(' ')
        if msgList[0] == 'note_on':
            channel = msgList[1][8:]
            note = msgList[2][5:]
def connect_arduino(P_knob, I_knob, D_knob, 
                     P_result_box, I_result_box,  D_result_box, 
                     connected_result, com_choice, connect_button, disconnect_button, set_temp_box, manual_com_choice, 
                     start_data, stop_data, save_params_button, display_params_button, params_box, set_temp_button, auto_collect, current_temp, 
                     plot, messages, **kwargs):
    global parameters
    global arduino
    arduino = Arduino()
    parameters = np.zeros(6)
    found_PID_controller = False
    found_arduino = False
    if manual_com_choice.value:
        arduino = Arduino('COM%s'%com_choice.value, 9600, 1.0)
        if arduino.connect():
            if arduino.ID == 'PID Temperature Controller':
                found_PID_controller = True
                found_arduino = True
                connected_result.value = 'Connected on COM%s'%(com_choice.value)
                messages.write('Successfully connected to Arduino on COM%s. '%com_choice.value)
            else:
                messages.write('Successfully connected to Arduino on %s but ID was not correct.\nID: %s\n' %(com_choice.value, arduino.ID))
                found_arduino = True
                arduino.disconnect()
        else:
            connected_result.value = 'Failed to connect on COM%s' %(com_choice.value)
    else:
        coms = []
        
        for x in map(str, range(1,101)): coms.append('COM'+x)
        for com in coms:
            arduino = Arduino(com, 9600, 1.0)
            if arduino.connect():
                if arduino.ID == 'PID Temperature Controller':
                    found_PID_controller = True
                    found_arduino = True
                    connected_result.value = 'Connected on %s' %(com)
                    messages.write('Successfully connected to Arduino on %s. '%com)
                    print arduino.ID
                else:
                    messages.write('Successfully connected to Arduino on %s but ID was not correct.\nID: %s\n' %(com, arduino.ID))
                    found_arduino = True
                    arduino.disconnect()
                    
            else:
                connected_result.value = 'Failed to connect on %s' %(com)
            if found_PID_controller: break
        if not found_arduino and not found_PID_controller:
            messages.write('Failed to connect to Arduino on COMs 1-100\n')
    if found_arduino:
        if found_PID_controller:
            messages.write('PID Temperature Controller found.\n')
            if arduino.is_connected and arduino.is_ready:
                time.sleep(.2)
                messages.write('Arduino is open for communication.\n')
                P_knob.enabled=True
                I_knob.enabled=True
                D_knob.enabled=True
                P_result_box.enabled=True
                I_result_box.enabled=True
                D_result_box.enabled=True
                connect_button.enabled = False
                disconnect_button.enabled = True
                save_params_button.enabled=False
                display_params_button.enabled=True
                params_box.value=''
                set_temp_button.enabled=True
                start_data.enabled=True
                stop_data.enabled=True
                auto_collect.enabled=True

                initialize_parameters(P_knob, I_knob, D_knob, 
                    P_result_box, I_result_box, 
                    D_result_box, set_temp_box, start_data, stop_data, 
                    current_temp, auto_collect, messages, plot, params_box, **kwargs)
            else:
                messages.write('Arduino connected but not yet ready for serial communication.\n')
        else:
            messages.write('Failed to find PID Temperature Controller, but Arduino boards detected.\n')
    else:
        arduino.disconnect()
        P_knob.enabled=False
        I_knob.enabled=False
        D_knob.enabled=False
        P_result_box.enabled=False
        I_result_box.enabled=False
        D_result_box.enabled=False
        disconnect_button.enabled=False
        connect_button.enabled=True
        set_temp_button.enabled=False
        display_params_button.enabled=False
        start_data.enabled=False
        stop_data.enabled=False
Example #55
0
except ImportError:
    log.warning("Could not initialize temperature sensor, using dummy values!")
    sensor_available = False
'''

try:
    from fs9721 import Client
    sensor_available = True
except:
    log.warning("Could not initialize DMM for temperature")
    sensor_available = False 

try:
    from Arduino import Arduino
    gpio_available = True
    gpio_board = Arduino('9600',port='/dev/ttyACM0')
    gpio_board.pinMode(config.gpio_heat,"OUTPUT")
    gpio_board.pinMode(config.gpio_cool,"OUTPUT")
    gpio_board.pinMode(config.gpio_air,"OUTPUT")
    gpio_board.pinMode(config.gpio_door,"INPUT")
except:
    msg = "Could not initialize GPIOs, oven operation will only be simulated!"
    log.warning(msg)
    gpio_available = False

'''
try:
    import RPi.GPIO as GPIO
    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)
    GPIO.setup(config.gpio_heat, GPIO.OUT)
 def __init__(self, baud_rate='9600', device_port="/dev/ttyACM0"):
     self.arduino_device = Arduino(baud_rate, port=device_port)
Example #57
0
from __future__ import division
from Arduino import Arduino

board = Arduino('9600', '/dev/tty.usbserial-A602TSPH')

while True:
    try:
        val = board.analogRead(0)
        voltage = val * (5.0 / 1023.0)
        print voltage
    except:
        print "N/A"
Example #58
0
import time
import pylaserkbd
import os

config = pylaserkbd.configuration()
try:
    '''try to load the configuration from file.'''
    config.load('config_piano.cfg')
except AssertionError:
    #if there is no configuration file, start
    print "No existing configuration found!"
    config.config_all()
    config.save('config_piano.cfg')
#use parameters in config to setup
cam = pylaserkbd.CAM(config.camid, config.thresh, config.dilate_iterations)
board = Arduino('9600', port = "")
HISTORY_TONE = 0
pitch = ['Do', 'Re', 'Me', 'Fa', 'Sol', 'La', 'Si']
while(True):
    cam.query()
    charpts, contours = cam.retrieve()
    func = pylaserkbd.make_mapping_function_pianomode(config.corner_position)
    tones = pylaserkbd.find_tone(func, charpts)
    if len(tones) >= 2:
        tone = 8 - tones[1]
        board.pinMode(tone, 'OUTPUT')
        board.digitalWrite(tone, 'HIGH')
        if HISTORY_TONE != tone:
            board.digitalWrite(HISTORY_TONE, 'LOW')
            board.pinMode(HISTORY_TONE, 'INPUT')
            print pitch[tones[1]]