Beispiel #1
0
class ArduinoBoard(object):
    """ Represents an Arduino board. """

    def __init__(self, port):
        from PyMata.pymata import PyMata
        self._port = port
        self._board = PyMata(self._port, verbose=False)

    def set_mode(self, pin, direction, mode):
        """ Sets the mode and the direction of a given pin. """
        if mode == 'analog' and direction == 'in':
            self._board.set_pin_mode(pin,
                                     self._board.INPUT,
                                     self._board.ANALOG)
        elif mode == 'analog' and direction == 'out':
            self._board.set_pin_mode(pin,
                                     self._board.OUTPUT,
                                     self._board.ANALOG)
        elif mode == 'digital' and direction == 'in':
            self._board.set_pin_mode(pin,
                                     self._board.OUTPUT,
                                     self._board.DIGITAL)
        elif mode == 'digital' and direction == 'out':
            self._board.set_pin_mode(pin,
                                     self._board.OUTPUT,
                                     self._board.DIGITAL)
        elif mode == 'pwm':
            self._board.set_pin_mode(pin,
                                     self._board.OUTPUT,
                                     self._board.PWM)

    def get_analog_inputs(self):
        """ Get the values from the pins. """
        self._board.capability_query()
        return self._board.get_analog_response_table()

    def set_digital_out_high(self, pin):
        """ Sets a given digital pin to high. """
        self._board.digital_write(pin, 1)

    def set_digital_out_low(self, pin):
        """ Sets a given digital pin to low. """
        self._board.digital_write(pin, 0)

    def get_digital_in(self, pin):
        """ Gets the value from a given digital pin. """
        self._board.digital_read(pin)

    def get_analog_in(self, pin):
        """ Gets the value from a given analog pin. """
        self._board.analog_read(pin)

    def get_firmata(self):
        """ Return the version of the Firmata firmware. """
        return self._board.get_firmata_version()

    def disconnect(self):
        """ Disconnects the board and closes the serial connection. """
        self._board.reset()
        self._board.close()
Beispiel #2
0
def main():
    #vehicle = connect('udp:192.168.1.177:14554', baud=57600, wait_ready=True)
    #vehicle = connect('udp:10.42.0.1:14555', baud=57600, wait_ready=True)
    #vehicle = connect('udp:127.0.0.1:14553', baud=57600, wait_ready=True)

    arduino = PyMata("/dev/ttyUSB0")

    arduino.sonar_config(3, 4)
    arduino.sonar_config(5, 6)
    arduino.sonar_config(7, 8)

    def signal_handler(signal, frame):
        if arduino != None:
            arduino.reset()
        sys.exit(0)
    
    signal.signal(signal.SIGINT, signal_handler)

    while True:
        arduino.digital_write(13, 1)
        data = arduino.get_sonar_data()

        sonarS = data[3][1]
        sonarL = data[5][1]
        sonarR = data[7][1]

        print sonarS, sonarR, sonarL

        
        time.sleep(.05)

    #vehicle.mode = VehicleMode("LAND")
    #vehicle.close()
    arduino.close()
Beispiel #3
0
class ArduinoBoard(object):
    """ Represents an Arduino board. """

    def __init__(self, port):
        self._port = port
        self._board = PyMata(self._port, verbose=False)

    def set_mode(self, pin, direction, mode):
        """ Sets the mode and the direction of a given pin. """
        if mode == 'analog' and direction == 'in':
            self._board.set_pin_mode(pin,
                                     self._board.INPUT,
                                     self._board.ANALOG)
        elif mode == 'analog' and direction == 'out':
            self._board.set_pin_mode(pin,
                                     self._board.OUTPUT,
                                     self._board.ANALOG)
        elif mode == 'digital' and direction == 'in':
            self._board.set_pin_mode(pin,
                                     self._board.OUTPUT,
                                     self._board.DIGITAL)
        elif mode == 'digital' and direction == 'out':
            self._board.set_pin_mode(pin,
                                     self._board.OUTPUT,
                                     self._board.DIGITAL)
        elif mode == 'pwm':
            self._board.set_pin_mode(pin,
                                     self._board.OUTPUT,
                                     self._board.PWM)

    def get_analog_inputs(self):
        """ Get the values from the pins. """
        self._board.capability_query()
        return self._board.get_analog_response_table()

    def set_digital_out_high(self, pin):
        """ Sets a given digital pin to high. """
        self._board.digital_write(pin, 1)

    def set_digital_out_low(self, pin):
        """ Sets a given digital pin to low. """
        self._board.digital_write(pin, 0)

    def get_digital_in(self, pin):
        """ Gets the value from a given digital pin. """
        self._board.digital_read(pin)

    def get_analog_in(self, pin):
        """ Gets the value from a given analog pin. """
        self._board.analog_read(pin)

    def get_firmata(self):
        """ Return the version of the Firmata firmware. """
        return self._board.get_firmata_version()

    def disconnect(self):
        """ Disconnects the board and closes the serial connection. """
        self._board.reset()
        self._board.close()
Beispiel #4
0
# create a PyMata instance
board = PyMata("/dev/ttyACM0")


def signal_handler(sig, frame):
    print('You pressed Ctrl+C!!!!')
    if board is not None:
        board.reset()
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
# control the servo - note that you don't need to set pin mode
# configure the servo
board.servo_config(SERVO_MOTOR)

while (1):
    # move the servo to 20 degrees
    board.analog_write(SERVO_MOTOR, 20)
    time.sleep(1)

    # move the servo to 100 degrees
    board.analog_write(SERVO_MOTOR, 100)
    time.sleep(1)

# move the servo to 20 degrees
board.analog_write(SERVO_MOTOR, 20)

# close the interface down cleanly
board.close()
class BiColorDisplayController:
    # display blink control values

    board_address = 0 # i2c address
    blink_rate = 0  # blink rate
    brightness = 0 # brightness

    # blink rate defines
    HT16K33_BLINK_CMD = 0x80
    HT16K33_BLINK_DISPLAYON = 0x01
    HT16K33_BLINK_OFF = 0
    HT16K33_BLINK_2HZ = 1
    HT16K33_BLINK_1HZ = 2
    HT16K33_BLINK_HALFHZ = 3

    # oscillator control values
    OSCILLATOR_ON = 0x21
    OSCILLATOR_OFF = 0x20

    # led color selectors
    LED_OFF = 0
    LED_RED = 1
    LED_YELLOW = 2
    LED_GREEN = 3

    # brightness
    MAX_BRIGHTNESS = 15

    # the display buffer
    # This is an 16x16 matrix that stores pixel data for the display
    # Even rows store the green pixel data and odd rows store the red pixel data.
    #
    # A physical row on the device is controlled by a row pair (ie 0,1 and 2,3, etc) for the 2 colors.
    #
    # To output yellow the red and green information for the rows will be set high.
    #
    display_buffer = [[0 for x in xrange(8)] for x in xrange(8)]


    def __init__(self, address, blink_rate, brightness):

        # create an instance of PyMata - we are using an Arduino UNO
        """

        @param address: I2C address of the device
        @param blink_rate: desired blink rate
        @param brightness: brightness level for the display
        """
        self.firmata = PyMata("/dev/ttyACM0")

        self.board_address = address
        self.blink_rate = blink_rate
        self.brightness = brightness
        self.clear_display_buffer()

        # configure firmata for i2c on an UNO
        self.firmata.i2c_config(0, self.firmata.ANALOG, 4, 5)

        # turn on oscillator
        self.oscillator_set(self.OSCILLATOR_ON)

        # set blink rate
        self.set_blink_rate(self.blink_rate)

        # set brightness
        self.set_brightness(self.brightness)

    def set_blink_rate(self, b):
        """
        Set the user's desired blink rate (0 - 3)
        @param b: blink rate
        """
        if (b > 3):
            b = 0 # turn off if not sure
        self.firmata.i2c_write(self.board_address,
                                 (self.HT16K33_BLINK_CMD | self.HT16K33_BLINK_DISPLAYON | (b << 1)))

    def oscillator_set(self, osc_mode):
        """
        Turn oscillator on or off
        @param osc_mode: osc mode (OSCILLATOR_ON or OSCILLATOR_OFF)
        """
        self.firmata.i2c_write(self.board_address, osc_mode)

    def set_brightness(self, brightness):
        """
        Set the brightness level for the entire display
        @param brightness: brightness level (0 -15)
        """
        if brightness > 15:
            brightness = 15
        brightness |= 0xE0
        self.brightness = brightness
        self.firmata.i2c_write(0x70,  brightness)

    def set_pixel(self, row, column, color, suppress_write):
        # rows 0,2,4,6,8,10,12,14 are green
        # rows 1,3,5,7,9,11,13,15 are red
        #
        # A row entry consists of 2 bytes, the first always being 0 and the second
        # being the state of the pixel (high or low)
        """

        @param row: pixel row number
        @param column: pix column number
        @param color: pixel color (yellow is both red and green both on)
        @param suppress_write: if true, just sets the internal data structure, else writes out the pixel to the display
        """
        if (row < 0) or (row >= 8):
            print "set_pixel(): ROW out of range"
            return
        if (column < 0) or (column >= 8):
            print "set_pixel(): COLUMN out of range"
            return

        self.display_buffer[row][column] = color

        # output changes to row on display

        green = 0
        red = 0

        # calculate row for green rows and then adjust it for red

        for col in range(0, 8):
            # assemble green data for the row and output
            if self.display_buffer[row][col] == self.LED_GREEN:
                green |= 1 << col
            elif self.display_buffer[row][col] == self.LED_RED:
                red |= 1 << col
            elif self.display_buffer[row][col] == self.LED_YELLOW:
                green |= 1 << col
                red |= 1 << col
            elif self.display_buffer[row][col] == self.LED_OFF:
                green &= ~(1 << col)
                red &= ~(1 << col)

        if suppress_write == False:
            self.firmata.i2c_write(0x70, row * 2, 0, green)
            self.firmata.i2c_write(0x70, row * 2 + 1, 0, red)

    def set_bit_map(self, shape, color):
        """
        Populate the bit map with the supplied "shape" and color
        and then write the entire bitmap to the display
        @param shape: pattern to display
        @param color: color for the pattern
        """
        for row in xrange(0, 8):
            data = shape[row]
            # shift data into buffer
            bit_mask = 0x80
            for column in xrange(0, 8):
                if data & bit_mask:
                    self.set_pixel(row, column, color, True)
                bit_mask >>= 1
        self.output_entire_buffer()

    def output_entire_buffer(self):
        """
        Write the entire buffer to the display
        """
        green = 0
        red = 0

        for row in xrange(0, 8):
            for col in xrange(0, 8):
                if self.display_buffer[row][col] == self.LED_GREEN:
                    green |= 1 << col
                elif self.display_buffer[row][col] == self.LED_RED:
                    red |= 1 << col
                elif self.display_buffer[row][col] == self.LED_YELLOW:
                    green |= 1 << col
                    red |= 1 << col
                elif self.display_buffer[row][col] == self.LED_OFF:
                    green &= ~(1 << col)
                    red &= ~(1 << col)

            self.firmata.i2c_write(0x70, row * 2, 0, green)
            self.firmata.i2c_write(0x70, row * 2 + 1, 0, red)


    def clear_display_buffer(self):
        """
        Set all led's to off.
        """
        for row in range(0, 8):
            self.firmata.i2c_write(0x70,  row * 2, 0, 0)
            self.firmata.i2c_write(0x70,  (row * 2) + 1, 0, 0)

            for column in range(0, 8):
                self.display_buffer[row][column] = 0

    def close(self):
        """
        close the interface down cleanly

        """
        self.firmata.close()
Beispiel #6
0
def s2a_fm():
    """
    This is the "main" function of the program.
    It will instantiate PyMata for communication with an Arduino micro-controller
    and the command handlers class.
    It will the start the HTTP server to communicate with Scratch 2.0
    @return : This is the main loop and should never return
    """
    # total number of pins on arduino board
    total_pins_discovered = 0
    # number of pins that are analog
    number_of_analog_pins_discovered = 0

    # make sure we have a log directory and if not, create it.
    if not os.path.exists('log'):
        os.makedirs('log')

    # turn on logging
    logging.basicConfig(filename='./log/s2a_fm_debugging.log',
                        filemode='w',
                        level=logging.DEBUG)
    logging.info(
        's2a_fm version 1.5    Copyright(C) 2013-14 Alan Yorinks    All Rights Reserved '
    )
    print 's2a est la version entierement en francais de s2a_fm, une sorte de s2a_fr v1.7'
    print 's2a_fm version 1.5   Copyright(C) 2013-14 Alan Yorinks    Tous droits reserves '

    # print 'Traductions francaises : Sebastien Canet'

    # get the com_port from the command line or default if none given
    # if user specified the com port on the command line, use that when invoking PyMata,
    # else use '/dev/ttyACM0'
    if len(sys.argv) == 2:
        com_port = str(sys.argv[1])
    else:
        com_port = '/dev/ttyACM0'
    logging.info('com port = %s' % com_port)

    try:
        # instantiate PyMata
        firmata = PyMata(com_port)  # pragma: no cover
    except Exception:
        print 'Impossible de communiquer avec PyMata - votre carte Arduino est bien connectee ??'
        logging.exception(
            'Could not instantiate PyMata - is your Arduino plugged in?')
        logging.debug("Exiting s2a_fm")
        return

    # determine the total number of pins and the number of analog pins for the Arduino
    # get the arduino analog pin map
    # it will contain an entry for all the pins with non-analog set to firmata.IGNORE
    firmata.analog_mapping_query()

    capability_map = firmata.get_analog_mapping_request_results()

    firmata.capability_query()
    print "Merci de patienter pendant la detection du nombre de pins de votre Arduino. Cela peut prendre pres de 30s de plus."

    # count the pins
    for pin in capability_map:
        total_pins_discovered += 1
        # non analog pins will be marked as IGNORE
        if pin != firmata.IGNORE:
            number_of_analog_pins_discovered += 1

    # log the number of pins found
    logging.info('%d Total Pins and %d Analog Pins Found' %
                 (total_pins_discovered, number_of_analog_pins_discovered))

    # instantiate the command handler
    scratch_command_handler = ScratchCommandHandlers(
        firmata, com_port, total_pins_discovered,
        number_of_analog_pins_discovered)

    # wait for a maximum of 30 seconds to retrieve the Arduino capability query
    start_time = time.time()

    pin_capability = firmata.get_capability_query_results()
    while not pin_capability:
        if time.time() - start_time > 30:
            print ''
            print "Impossible de determiner le nombre de pins - sortie du script."
            firmata.close()
            # keep sending out a capability query until there is a response
        pin_capability = firmata.get_capability_query_results()
        time.sleep(.1)

    # we've got the capability, now build a dictionary with pin as the key and a list of all the capabilities
    # for the pin as the key's value
    pin_list = []
    total_pins_discovered = 0
    for entry in pin_capability:
        # bump up pin counter each time IGNORE is found
        if entry == firmata.IGNORE:
            scratch_command_handler.pin_map[total_pins_discovered] = pin_list
            total_pins_discovered += 1
            pin_list = []
        else:
            pin_list.append(entry)

    print "Detection des pins de la carte Arduino faite en %d secondes" % (
        int(time.time() - start_time))

    try:
        # lance un script pour automatiser l'ouverture de Scratch pendant que le serveur se met en route
        # il est separe pour permettre aux utilisateurs de le modifier en direct, dans le batch, ca simplifie
        # os.startfile('Scratch2.bat')
        # start the server passing it the handle to PyMata and the command handler.
        scratch_http_server.start_server(firmata, scratch_command_handler)

    except Exception:
        logging.debug('Erreur dans s2a_fm.py %s' % str(Exception))
        firmata.close()
        return

    except KeyboardInterrupt:
        # give control back to the shell that started us
        logging.info('s2a_fm.py: keyboard interrupt exception')
        firmata.close()
        return
Beispiel #7
0
						self.btn_serv_pos.config(state = NORMAL)
						self.btn_serv_neg.config(state = NORMAL)
					else:
						#el switch esta presionado, los botones se deshabilitan
						self.lbl_switch.set("HIGH")
						self.btn_serv_pos.config(state = DISABLED)
						self.btn_serv_neg.config(state = DISABLED)
				elif(key == "pot"):
					#actualizo el valor escalado del potenciometro
					self.lbl_val_pote.set(value)
				else:
					break
		
	
	def alert(self):
		'''
		muestro un mensaje de error en el caso de llegar a un
		valor de 0 o de 180 en la variable servo_pos
		'''
		showerror("ERROR", self.lbl_servo_err)
		

if __name__ == "__main__":
	ard = PyMata()
	app = simple(None)
	app.title('my app')
	app.focus_set()
	config_ardu()
	app.mainloop()
	ard.close()
Beispiel #8
0

signal.signal(signal.SIGINT, signal_handler)

# send the arduino a firmata reset
firmata.reset()

# configure the stepper to use pins 9.10,11,12 and specify 512 steps per revolution
firmata.stepper_config(512, [12, 11, 10, 9])

# allow time for config to complete
time.sleep(.5)

# ask Arduino to return the stepper library version number to PyMata
firmata.stepper_request_library_version()

# allow time for command and reply to go across the serial link
time.sleep(.5)

print(("Stepper Library Version", ))
print((firmata.get_stepper_version()))

# move motor #0 500 steps forward at a speed of 20
firmata.stepper_step(20, 500)

# move motor #0 500 steps reverse at a speed of 20
firmata.stepper_step(20, -500)

# close firmata
firmata.close()
# This code is supporting material for the book
# Python Programming for Arduino
# by Pratik Desai
# published by PACKT Publishing

import time
from PyMata.pymata import PyMata

#Initializing Arduino using PyFirmata constructor
port = PyMata("COM5")

#Configure I2C pin
port.i2c_config(0, port.ANALOG, 4, 5)

# One shot read asking peripheral to send 2 bytes
port.i2c_read(0x23, 0, 2, port.I2C_READ)
# Wait for peripheral to send the data
time.sleep(3)

# Read from the peripheral
data = port.i2c_get_read_data(0x23)

# Obtain lux values from received data
LuxSum = (data[1] << 8 | data[2]) >> 4

lux = LuxSum/1.2
print str(lux) + ' lux'

port.close()
Beispiel #10
0
def s2a_fm():
    """
    This is the "main" function of the program.
    It will instantiate PyMata for communication with an Arduino micro-controller
    and the command handlers class.
    It will the start the HTTP server to communicate with Scratch 2.0
    @return : This is the main loop and should never return
    """
    # total number of pins on arduino board
    total_pins_discovered = 0
    # number of pins that are analog
    number_of_analog_pins_discovered = 0

    # make sure we have a log directory and if not, create it.
    if not os.path.exists('log'):
        os.makedirs('log')

    # turn on logging
    logging.basicConfig(filename='./log/s2a_fm_debugging.log',
                        filemode='w',
                        level=logging.DEBUG)
    logging.info(
        's2a_fm version 1.5    Copyright(C) 2013-14 Alan Yorinks    All Rights Reserved '
    )
    print 's2a_fm version 1.5   Copyright(C) 2013-14 Alan Yorinks    All Rights Reserved '

    # get the com_port from the command line or default if none given
    # if user specified the com port on the command line, use that when invoking PyMata,
    # else use '/dev/ttyACM0'
    if len(sys.argv) == 2:
        com_port = str(sys.argv[1])
    else:
        com_port = '/dev/ttyACM0'
    logging.info('com port = %s' % com_port)

    try:
        # instantiate PyMata
        firmata = PyMata(com_port)  # pragma: no cover
    except Exception:
        print 'Could not instantiate PyMata - is your Arduino plugged in?'
        logging.exception(
            'Could not instantiate PyMata - is your Arduino plugged in?')
        logging.debug("Exiting s2a_fm")
        return

    # determine the total number of pins and the number of analog pins for the Arduino
    # get the arduino analog pin map
    # it will contain an entry for all the pins with non-analog set to firmata.IGNORE
    firmata.analog_mapping_query()

    capability_map = firmata.get_analog_mapping_request_results()

    firmata.capability_query()
    print "Please wait for Total Arduino Pin Discovery to complete. This can take up to 30 additional seconds."

    # count the pins
    for pin in capability_map:
        total_pins_discovered += 1
        # non analog pins will be marked as IGNORE
        if pin != firmata.IGNORE:
            number_of_analog_pins_discovered += 1

    # log the number of pins found
    logging.info('%d Total Pins and %d Analog Pins Found' %
                 (total_pins_discovered, number_of_analog_pins_discovered))

    # instantiate the command handler
    scratch_command_handler = ScratchCommandHandlers(
        firmata, com_port, total_pins_discovered,
        number_of_analog_pins_discovered)

    # wait for a maximum of 30 seconds to retrieve the Arduino capability query
    start_time = time.time()

    pin_capability = firmata.get_capability_query_results()
    while not pin_capability:
        if time.time() - start_time > 30:
            print ''
            print "Could not determine pin capability - exiting."
            firmata.close()
            # keep sending out a capability query until there is a response
        pin_capability = firmata.get_capability_query_results()
        time.sleep(.1)

    # we've got the capability, now build a dictionary with pin as the key and a list of all the capabilities
    # for the pin as the key's value
    pin_list = []
    total_pins_discovered = 0
    for entry in pin_capability:
        # bump up pin counter each time IGNORE is found
        if entry == firmata.IGNORE:
            scratch_command_handler.pin_map[total_pins_discovered] = pin_list
            total_pins_discovered += 1
            pin_list = []
        else:
            pin_list.append(entry)

    print "Arduino Total Pin Discovery completed in %d seconds" % (
        int(time.time() - start_time))

    try:
        # start the server passing it the handle to PyMata and the command handler.
        scratch_http_server.start_server(firmata, scratch_command_handler)

    except Exception:
        logging.debug('Exception in s2a_fm.py %s' % str(Exception))
        firmata.close()
        return

    except KeyboardInterrupt:
        # give control back to the shell that started us
        logging.info('s2a_fm.py: keyboard interrupt exception')
        firmata.close()
        return
Beispiel #11
0
class s2a_fm:

    """
    This is the "main" function of the program.
    It will instantiate PyMata for communication with an Arduino micro-controller
    and the command handlers class.
    It will the start the HTTP server to communicate with Scratch 2.0
    @return : This is the main loop and should never return
    """
    def __init__(self):
        subprocess.Popen("scratch2")
        # total number of pins on arduino board
        self.total_pins_discovered = 0
        # number of pins that are analog
        self.number_of_analog_pins_discovered = 0
        # COM-Port
        self.com_port = "COM1"
        #firmata
        #self.firmata ="-

        # make sure we have a log directory and if not, create it.
        if not os.path.exists('log'):
            os.makedirs('log')

        # turn on logging
        logging.basicConfig(filename='./log/s2a_fm_debugging.log', filemode='w', level=logging.DEBUG)
        logging.info('s2a_fm version 1.5    Copyright(C) 2013-14 Alan Yorinks    All Rights Reserved ')
        print 's2a_fm version 1.5   Copyright(C) 2013-14 Alan Yorinks    All Rights Reserved '

        # get the com_port from the command line or default if none given
        # if user specified the com port on the command line, use that when invoking PyMata,
        # else use '/dev/ttyACM0'
    

    def search_port(self):
        #returns all serial COM-Ports
        possible_ports = serial_ports() 
        print 
        for com_port in possible_ports:
            logging.info('com port = %s' % com_port)
            try:
                # instantiate PyMata
                self.firmata = PyMata(com_port)  # pragma: no cover
                self.com_port = com_port
                return 1
            except Exception:
                print('Could not instantiate PyMata - is your Arduino plugged in?')
                logging.exception('Could not instantiate PyMata on Port %s' % com_port)
        return 0
        #TODO: Ask if User Wants to flash Arduino on this Port
            
        
    def discover_arduino(self):
        # determine the total number of pins and the number of analog pins for the Arduino
        # get the arduino analog pin map
        # it will contain an entry for all the pins with non-analog set to self.firmata.IGNORE
        self.firmata.analog_mapping_query()

        self.capability_map = self.firmata.get_analog_mapping_request_results()

        self.firmata.capability_query()
        print("Please wait for Total Arduino Pin Discovery to complete. This can take up to 30 additional seconds.")

        # count the pins
        for pin in self.capability_map:
                self.total_pins_discovered += 1
                # non analog pins will be marked as IGNORE
                if pin != self.firmata.IGNORE:
                    self.number_of_analog_pins_discovered += 1

        # log the number of pins found
        logging.info('%d Total Pins and %d Analog Pins Found' % (self.total_pins_discovered, self.number_of_analog_pins_discovered))

        # instantiate the command handler
        self.scratch_command_handler = ScratchCommandHandlers(self.firmata, self.com_port, self.total_pins_discovered,
                                                         self.number_of_analog_pins_discovered)

        # wait for a maximum of 30 seconds to retrieve the Arduino capability query
        start_time = time.time()

        pin_capability = self.firmata.get_capability_query_results()
        while not pin_capability:
            if time.time() - start_time > 30:
                print "Could not determine pin capability - exiting."
                self.firmata.close()
                # keep sending out a capability query until there is a response
            pin_capability = self.firmata.get_capability_query_results()
            time.sleep(.1)

        # we've got the capability, now build a dictionary with pin as the key and a list of all the capabilities
        # for the pin as the key's value
        pin_list = []
        total_pins_discovered = 0
        for entry in pin_capability:
            # bump up pin counter each time IGNORE is found
            if entry == self.firmata.IGNORE:
                self.scratch_command_handler.pin_map[total_pins_discovered] = pin_list
                total_pins_discovered += 1
                pin_list = []
            else:
                pin_list.append(entry)

        print "Arduino Total Pin Discovery completed in %d seconds" % (int(time.time() - start_time))
    def guess_path(self):
        os_name = sys.plattform
        if os_name == "linux2":
            return  "scratch2"
        elif os_name == "win32" or os_name == "cygwin":
            #try some
            if os.path.exists("C:\Program Files (x86)\Scratch 2\Scratch 2.exe"):
                return "C:\Program Files (x86)\Scratch 2\Scratch 2.exe"
        elif os_name == "darwin":
            return "scratch2"
        return -1

    def start_server(self):
        try:
            # start the server passing it the handle to PyMata and the command handler.
            scratch_http_server.start_server(self.firmata, self.scratch_command_handler)

        except Exception:
            logging.debug('Exception in s2a_fm.py %s' % str(Exception))
            self.firmata.close()
            return

        except KeyboardInterrupt:
            # give control back to the shell that started us
            logging.info('s2a_fm.py: keyboard interrupt exception')
            self.firmata.close()
            return
Beispiel #12
0
@description: Blink Arduino mediante Firmata
@url: http://www.aprendiendoarduino.com/
'''


import time
import sys
from PyMata.pymata import PyMata

BOARD_LED = 13
port = input("Puerto Serie Arduino: ")

try:
    arduino = PyMata(port, verbose=True)

    for x in range(10):
        print(x + 1)
        # Set the output to 1 = High
        arduino.digital_write(BOARD_LED, 1)
        # Wait a half second between toggles.
        time.sleep(.5)
        # Set the output to 0 = Low
        arduino.digital_write(BOARD_LED, 0)
        time.sleep(.5)

    # Close PyMata when we are done
    arduino.close()
except: # catch *all* exceptions
    e = sys.exc_info()[0]
    print("Puerto no válido. %s" % e)
Beispiel #13
0
class Firmata(Adaptor):

    def __init__(self, options):
        super(Firmata, self).__init__(options)

        if 'port' not in options:
            raise self.ParameterRequired(
                'A port must be specified for Firmata connection.'
            )

        self.port = options.get('port')
        self.board = PyMata('/dev/ttyACM0', verbose=True)

        signal.signal(signal.SIGINT, self.signal_handler)

        self.pins = {
            'digital': [],
            'analog': [],
            'pwm': [],
            'servo': [],
            'i2c': [],
        }

    def analog_write(self, pin_number, value):
        if pin_number not in self.pins['analog']:
            self.pins['analog'].append(pin_number)
            self.board.set_pin_mode(
                pin_number,
                self.board.OUTPUT,
                self.board.ANALOG
            )

        self.board.analog_write(pin_number, value)

    def analog_read(self, pin_number):
        if pin_number not in self.pins['analog']:
            self.pins['analog'].append(pin_number)
            self.board.set_pin_mode(
                pin_number,
                self.board.INPUT,
                self.board.ANALOG
            )

        return self.board.analog_read(pin_number)

    def digital_write(self, pin_number, value):
        if pin_number not in self.pins['digital']:
            self.pins['digital'].append(pin_number)
            self.board.set_pin_mode(
                pin_number,
                self.board.OUTPUT,
                self.board.DIGITAL
            )

        self.board.digital_write(pin_number, value)

    def digital_read(self, pin_number):
        if pin_number not in self.pins['digital']:
            self.pins['digital'].append(pin_number)
            self.board.set_pin_mode(
                pin_number,
                self.board.INPUT,
                self.board.DIGITAL
            )

        return self.board.analog_write(pin_number)

    def pwm_write(self, pin_number, value):
        if pin_number not in self.pins['pwm']:
            self.pins['pwm'].append(pin_number)
            self.board.set_pin_mode(
                pin_number,
                self.board.PWM,
                self.board.DIGITAL
            )

        return self.board.analog_write(pin_number, value)

    def pwm_read(self, pin_number):
        if pin_number not in self.pins['pwm']:
            self.pins['pwm'].append(pin_number)
            self.board.set_pin_mode(
                pin_number,
                self.board.PWM,
                self.board.DIGITAL
            )

        return self.board.analog_read(pin_number)

    def servo_write(self, pin_number, value):
        if pin_number not in self.pins['servo']:
            self.pins['servo'].append(pin_number)
            self.board.servo_config(pin_number)

        self.board.analog_write(pin_number, value)

    def disconnect(self):
        # Close the firmata interface down cleanly
        self.board.close()

    def signal_handler(self, sig, frame):
        print('Ctrl+C pressed')
        if self.board is not None:
            self.board.reset()
        sys.exit(0)

    class ParameterRequired(Exception):
        def __init__(self, message='A required parameter was not provided.'):
            super(Firmata.ParameterRequired, self).__init__(message)

        def __str__(self):
            return self.message
# by Pratik Desai
# published by PACKT Publishing

import time
from PyMata.pymata import PyMata

#Initialize Arduino using port name
port = PyMata("COM5")

#Configure I2C pin
port.i2c_config(0, port.ANALOG, 4, 5)

# One shot read asking peripheral to send 2 bytes
port.i2c_read(0x48, 0, 2, port.I2C_READ)
# Wait for peripheral to send the data
time.sleep(3)

# Read from the peripheral
data = port.i2c_get_read_data(0x48)

# Obtain temperature from received data
TemperatureSum = (data[1] << 8 | data[2]) >> 4

celsius = TemperatureSum * 0.0625
print celsius

fahrenheit = (1.8 * celsius) + 32
print fahrenheit

port.close()
Beispiel #15
0
def s2a_fm():

    """
    This is the "main" function of the program.
    It will instantiate PyMata for communication with an Arduino micro-controller
    and the command handlers class.
    It will the start the HTTP server to communicate with Scratch 2.0
    @return : This is the main loop and should never return
    """
    # total number of pins on arduino board
    total_pins_discovered = 0
    # number of pins that are analog
    number_of_analog_pins_discovered = 0

    # make sure we have a log directory and if not, create it.
    if not os.path.exists('log'):
        os.makedirs('log')

    # turn on logging
    logging.basicConfig(filename='./log/s2a_fm_debugging.log', filemode='w', level=logging.DEBUG)
    logging.info('s2a_fm version 1.0    Copyright(C) 2013 Alan Yorinks    All Rights Reserved ')
    print 's2a_fm version 1.0    Copyright(C) 2013 Alan Yorinks    All Rights Reserved '

    # get the com_port from the command line or default if none given
    # if user specified the com port on the command line, use that when invoking PyMata,
    # else use '/dev/ttyACM0'
    if len(sys.argv) == 2:
        com_port= str(sys.argv[1])
    else:
        com_port = '/dev/ttyACM0'
    logging.info('com port = %s' % com_port)



    try:
        # instantiate PyMata
        firmata = PyMata(com_port)  # pragma: no cover
    except:
        Exception
        print 'Could not instantiate PyMata - is your Arduino plugged in?'
        logging.exception('Could not instantiate PyMata - is your Arduino plugged in?')
        logging.debug("Exiting s2a_fm")
        return

    # determine the total number of pins and the number of analog pins for the Arduino
    # get the arduino analog pin map
    # it will contain an entry for all the pins with non-analog set to firmata.IGNORE
    firmata.analog_mapping_query()

    capability_map = firmata.get_analog_mapping_request_results()

    # count the pins
    for pin in capability_map:
            total_pins_discovered += 1
            # non analog pins will be marked as IGNORE
            if pin != firmata.IGNORE:
                number_of_analog_pins_discovered += 1

    # log the number of pins found
    logging.info('%d Total Pins and %d Analog Pins Found' % (total_pins_discovered,
                                                     number_of_analog_pins_discovered))
    # instantiate the command handler
    scratch_command_handler = ScratchCommandHandlers(firmata, com_port, total_pins_discovered,
                                                     number_of_analog_pins_discovered)

    try:
        # start the server passing it the handle to PyMata and the command handler.
        scratch_http_server.start_server(firmata, scratch_command_handler)

    except Exception:
        logging.debug('Exception in s2a_fm.py %s' % str(Exception))
        firmata.close()
        return

    except KeyboardInterrupt:
        # give control back to the shell that started us
        logging.info('s2a_fm.py: keyboard interrupt exception')
        firmata.close()
        return
Beispiel #16
0
def s2a_fm():

    """
    This is the "main" function of the program.
    It will instantiate PyMata for communication with an Arduino micro-controller
    and the command handlers class.
    It will the start the HTTP server to communicate with Scratch 2.0
    @return : This is the main loop and should never return
    """
    # total number of pins on arduino board
    total_pins_discovered = 0
    # number of pins that are analog
    number_of_analog_pins_discovered = 0

    # make sure we have a log directory and if not, create it.
    if not os.path.exists('log'):
        os.makedirs('log')

    # turn on logging
    logging.basicConfig(filename='./log/s2a_fm_debugging.log', filemode='w', level=logging.DEBUG)
    logging.info('s2a_fm version 1.5    Copyright(C) 2013-14 Alan Yorinks    All Rights Reserved ')
    print 's2a_fm version 1.5   Copyright(C) 2013-14 Alan Yorinks    All Rights Reserved '

    # get the com_port from the command line or default if none given
    # if user specified the com port on the command line, use that when invoking PyMata,
    # else use '/dev/ttyACM0'
    if len(sys.argv) == 2:
        com_port = str(sys.argv[1])
    else:
        com_port = '/dev/ttyACM0'
    logging.info('com port = %s' % com_port)

    try:
        # instantiate PyMata
        firmata = PyMata(com_port)  # pragma: no cover
    except Exception:
        print 'Could not instantiate PyMata - is your Arduino plugged in?'
        logging.exception('Could not instantiate PyMata - is your Arduino plugged in?')
        logging.debug("Exiting s2a_fm")
        return

    # determine the total number of pins and the number of analog pins for the Arduino
    # get the arduino analog pin map
    # it will contain an entry for all the pins with non-analog set to firmata.IGNORE
    firmata.analog_mapping_query()

    capability_map = firmata.get_analog_mapping_request_results()

    firmata.capability_query()
    print "Please wait for Total Arduino Pin Discovery to complete. This can take up to 30 additional seconds."

    # count the pins
    for pin in capability_map:
            total_pins_discovered += 1
            # non analog pins will be marked as IGNORE
            if pin != firmata.IGNORE:
                number_of_analog_pins_discovered += 1

    # log the number of pins found
    logging.info('%d Total Pins and %d Analog Pins Found' % (total_pins_discovered, number_of_analog_pins_discovered))

    # instantiate the command handler
    scratch_command_handler = ScratchCommandHandlers(firmata, com_port, total_pins_discovered,
                                                     number_of_analog_pins_discovered)

    # wait for a maximum of 30 seconds to retrieve the Arduino capability query
    start_time = time.time()

    pin_capability = firmata.get_capability_query_results()
    while not pin_capability:
        if time.time() - start_time > 30:
            print ''
            print "Could not determine pin capability - exiting."
            firmata.close()
            # keep sending out a capability query until there is a response
        pin_capability = firmata.get_capability_query_results()
        time.sleep(.1)

    # we've got the capability, now build a dictionary with pin as the key and a list of all the capabilities
    # for the pin as the key's value
    pin_list = []
    total_pins_discovered = 0
    for entry in pin_capability:
        # bump up pin counter each time IGNORE is found
        if entry == firmata.IGNORE:
            scratch_command_handler.pin_map[total_pins_discovered] = pin_list
            total_pins_discovered += 1
            pin_list = []
        else:
            pin_list.append(entry)

    print "Arduino Total Pin Discovery completed in %d seconds" % (int(time.time() - start_time))

    try:
        # start the server passing it the handle to PyMata and the command handler.
        scratch_http_server.start_server(firmata, scratch_command_handler)

    except Exception:
        logging.debug('Exception in s2a_fm.py %s' % str(Exception))
        firmata.close()
        return

    except KeyboardInterrupt:
        # give control back to the shell that started us
        logging.info('s2a_fm.py: keyboard interrupt exception')
        firmata.close()
        return
Beispiel #17
0

signal.signal(signal.SIGINT, signal_handler)

# send the arduino a firmata reset
firmata.reset()

# configure the stepper to use pins 9.10,11,12 and specify 512 steps per revolution
firmata.stepper_config(512, [12, 11, 10, 9])

# allow time for config to complete
time.sleep(.5)

# ask Arduino to return the stepper library version number to PyMata
firmata.stepper_request_library_version()

# allow time for command and reply to go across the serial link
time.sleep(.5)

print("Stepper Library Version",)
print(firmata.get_stepper_version())

# move motor #0 500 steps forward at a speed of 20
firmata.stepper_step(20, 500)

# move motor #0 500 steps reverse at a speed of 20
firmata.stepper_step(20, -500)

# close firmata
firmata.close()
Beispiel #18
0
def s2a_fm():
    """
    This is the "main" function of the program.
    It will instantiate PyMata for communication with an Arduino micro-controller
    and the command handlers class.
    It will the start the HTTP server to communicate with Scratch 2.0
    @return : This is the main loop and should never return
    """
    global s2a_fm_status

    # total number of pins on arduino board
    total_pins_discovered = 0
    # number of pins that are analog
    number_of_analog_pins_discovered = 0
    # Ethernet/WiFi autodetect
    autodetect = 0

    print 's2a_fm version 1.5   Copyright(C) 2013-14 Alan Yorinks    All Rights Reserved '

    # get the com_port from the command line or default if none given
    # if user specified the com port on the command line, use that when invoking PyMata,
    # else use '/dev/ttyACM0'

    projectName = '86Hexapodtest'
    com_port = '/dev/ttyACM0'
    ui_server_port = 8386

    if len(sys.argv) == 2:
        if str(sys.argv[1]) == 'autodetect':
            autodetect = 1
        else:
            com_port = str(sys.argv[1])

    elif len(sys.argv) == 3:
        if str(sys.argv[1]).find('com') == 0:
            com_port = str(sys.argv[1])
            ui_server_port = int(sys.argv[2])
        elif str(sys.argv[1]) == 'autodetect':
            autodetect = 1
            ui_server_port = int(sys.argv[2])
        else:
            host_ip = str(sys.argv[1])
            host_port = int(sys.argv[2])

    elif len(sys.argv) == 4:
        host_ip = str(sys.argv[1])
        host_port = int(sys.argv[2])
        ui_server_port = int(sys.argv[3])

    try:
        # instantiate PyMata
        if autodetect == 1:
            firmata = PyMata(host_port=2000,
                             ui_server_port=ui_server_port,
                             projectName=projectName,
                             autodetect=autodetect)
        elif str(sys.argv[1]).find('com') == 0:
            firmata = PyMata(port_id=com_port,
                             ui_server_port=ui_server_port)  # pragma: no cover
        elif len(sys.argv) == 3 or len(sys.argv) == 4:
            firmata = PyMata(host_ip=host_ip,
                             host_port=host_port,
                             ui_server_port=ui_server_port)  # pragma: no cover
    except Exception:
        print 'Could not instantiate PyMata - is your Arduino plugged in?'
        return

    firmata.set_s2a_fm_status(5)

    # determine the total number of pins and the number of analog pins for the Arduino
    # get the arduino analog pin map
    # it will contain an entry for all the pins with non-analog set to firmata.IGNORE
    # firmata.analog_mapping_query()
    # time.sleep(.1)
    capability_map = firmata.get_analog_mapping_request_results()

    firmata.capability_query()
    print "Please wait for Total Arduino Pin Discovery to complete. This can take up to 30 additional seconds."

    # count the pins
    for pin in capability_map:
        total_pins_discovered += 1
        # non analog pins will be marked as IGNORE
        if pin != firmata.IGNORE:
            number_of_analog_pins_discovered += 1

    # instantiate the command handler
    scratch_command_handler = ScratchCommandHandlers(
        firmata, com_port, total_pins_discovered,
        number_of_analog_pins_discovered)

    firmata.set_s2a_fm_status(6)

    # wait for a maximum of 30 seconds to retrieve the Arduino capability query
    start_time = time.time()

    pin_capability = firmata.get_capability_query_results()
    while not pin_capability:
        firmata.set_s2a_fm_status(7)
        if time.time() - start_time > 30:
            firmata.set_s2a_fm_status(99)
            firmata.set_error_no(4)
            print ''
            print "Could not determine pin capability - exiting."
            firmata.send_error_message()
            firmata.close(True)
            return
            # keep sending out a capability query until there is a response
        pin_capability = firmata.get_capability_query_results()
        time.sleep(.1)

    firmata.set_s2a_fm_status(8)

    # we've got the capability, now build a dictionary with pin as the key and a list of all the capabilities
    # for the pin as the key's value
    pin_list = []
    total_pins_discovered = 0
    for entry in pin_capability:
        # bump up pin counter each time IGNORE is found
        if entry == firmata.IGNORE:
            scratch_command_handler.pin_map[total_pins_discovered] = pin_list
            total_pins_discovered += 1
            pin_list = []
        else:
            pin_list.append(entry)

    print "Arduino Total Pin Discovery completed in %d seconds" % (
        int(time.time() - start_time))

    firmata.set_s2a_fm_status(9)

    thread.start_new_thread(firmata.send_command_check_active, (firmata, ))

    try:
        # start the server passing it the handle to PyMata and the command handler.
        scratch_http_server.start_server(firmata, scratch_command_handler)
    except Exception:
        firmata.set_error_no(5)
        firmata.send_error_message()
        firmata.close(True)
        return

    except KeyboardInterrupt:
        # give control back to the shell that started us
        firmata.set_error_no(99)
        firmata.close(True)
        return
Beispiel #19
0
master = Tk()
master.title("RGB LED")
master.geometry('250x200')

r = Scale(master,
          from_=255,
          to=0,
          command=(rd),
          label="Red",
          troughcolor="red")
r.pack(side=LEFT)
g = Scale(master,
          from_=255,
          to=0,
          command=(gr),
          label="Green",
          troughcolor="green")
g.pack(side=RIGHT)
b = Scale(master,
          from_=255,
          to=0,
          command=(bl),
          label="Blue",
          troughcolor="blue")
b.pack(side=RIGHT)

mainloop()

board.close()
board.reset()
Beispiel #20
0
@version: 1.0
@description: Blink Arduino mediante Firmata
@url: http://www.aprendiendoarduino.com/
'''

import time
import sys
from PyMata.pymata import PyMata

BOARD_LED = 13
port = input("Puerto Serie Arduino: ")

try:
    arduino = PyMata(port, verbose=True)

    for x in range(10):
        print(x + 1)
        # Set the output to 1 = High
        arduino.digital_write(BOARD_LED, 1)
        # Wait a half second between toggles.
        time.sleep(.5)
        # Set the output to 0 = Low
        arduino.digital_write(BOARD_LED, 0)
        time.sleep(.5)

    # Close PyMata when we are done
    arduino.close()
except:  # catch *all* exceptions
    e = sys.exc_info()[0]
    print("Puerto no válido. %s" % e)