Example #1
0
        def __init__(self):
            Thread.__init__(self)
            self.daemon = True
            self.board = PyMata()

            def signal_handler(sig, frame):
                self.stop_motors()
                self.board.reset()
                sys.exit(0)

            signal.signal(signal.SIGINT, signal_handler)
            self.board.set_pin_mode(self.MOTOR_1_PWM, self.board.PWM,
                                    self.board.DIGITAL)
            self.board.set_pin_mode(self.MOTOR_1_A, self.board.OUTPUT,
                                    self.board.DIGITAL)
            self.board.set_pin_mode(self.MOTOR_1_B, self.board.OUTPUT,
                                    self.board.DIGITAL)
            self.board.set_pin_mode(self.MOTOR_2_PWM, self.board.PWM,
                                    self.board.DIGITAL)
            self.board.set_pin_mode(self.MOTOR_2_A, self.board.OUTPUT,
                                    self.board.DIGITAL)
            self.board.set_pin_mode(self.MOTOR_2_B, self.board.OUTPUT,
                                    self.board.DIGITAL)
            self.board.set_pin_mode(self.MOTOR_3_PWM, self.board.PWM,
                                    self.board.DIGITAL)
            self.board.set_pin_mode(self.MOTOR_3_A, self.board.OUTPUT,
                                    self.board.DIGITAL)
            self.board.set_pin_mode(self.MOTOR_3_B, self.board.OUTPUT,
                                    self.board.DIGITAL)
            self.dx, self.dy = 0, 0
Example #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()
Example #3
0
def main():
    port = '/dev/ttyACM0'

    base = 0.3
    gust = numpy.sin(numpy.linspace(0, 2 * 3.14, 100))
    wind = base + (0.1) * gust
    print(wind)

    board = PyMata(port, verbose=True)

    GAUGE_PIN = 6
    POTENTIOMETER_ANALOG_PIN = 0

    board.set_pin_mode(13, board.OUTPUT, board.DIGITAL)
    #board.set_pin_mode(FAN_PIN, board.PWM, board.ANALOG)
    board.servo_config(GAUGE_PIN)
    board.set_pin_mode(POTENTIOMETER_ANALOG_PIN, board.INPUT, board.ANALOG)

    while True:
        pot = board.analog_read(POTENTIOMETER_ANALOG_PIN)
        deg = 180 - int(180.0 * (pot / 1023.0))
        print("{:4} => {:3}".format(pot, deg))

        board.analog_write(GAUGE_PIN, deg)

        gevent.sleep(0.025)

    for _ in range(0, 10):

        for v in list(wind):
            print(v)
            board.analog_write(FAN_PIN, (int)(v * 255))
            gevent.sleep(0.025)
Example #4
0
def init(path):
    board = PyMata(path)

    for pin in range(17):
        board.set_pin_mode(pin + 2, board.OUTPUT, board.DIGITAL)

    return board
def setupLED():
    global PWM_pin
    global board
    PWM_pin = 5
    # use pin D5 as pwm to adjest LED.
    board = PyMata('/dev/ttyS0', verbose=True)
    board.set_pin_mode(PWM_pin, board.PWM, board.DIGITAL)
    print "Start PWM test by pin D5"
Example #6
0
    def __init__(self, pin_num, port="/dev/ttyACM0", debug=False):
        """

        :param pin_num: 数字针脚编号,范围0~19
        :param port: 虚谷连接arduino的COM口,默认为"/dev/ttyACM0"
        :param debug: 当为True的时候,会输出debug信息
        """
        self.pin_num = pin_num
        self.board = PyMata(port, bluetooth=False, verbose=debug)
        # 针脚设置为输出模式,数字信号类型
        self.board.set_pin_mode(pin_num, self.board.OUTPUT, self.board.DIGITAL)
Example #7
0
    def __init__(self, *args):
        #NestedDict.__init__(self, args)
        NestedDict.__init__(self)

        self.logger = logging.getLogger(self.__class__.__name__)

        if Firmata.board is None:
            signal.signal(signal.SIGINT, Firmata.signal_handler)
            Firmata.board = PyMata(self.setdefault("usb_port", "/dev/ttyACM0"))
            self.logger.info("Initialized firmata board '%s'",
                             self["usb_port"])
Example #8
0
    def __init__(self, pin_num, port="/dev/ttyACM0", debug=False):
        """

        :param pin_num: 接入舵机的针脚编号,编号范围0~19
        :param port: 虚谷连接舵机的COM口,默认为"/dev/ttyACM0"
        :param debug: 当为True的时候,会输出debug信息
        """
        pin_num, _ = check_pin_num(pin_num)
        self.pin_num = pin_num
        self.board = PyMata(port, bluetooth=False, verbose=debug)
        self.board.servo_config(pin_num)
Example #9
0
    def __init__(self, pin_type, clk_pin, data_pin, port="/dev/ttyACM0",
                 debug=False):
        """

        :param pin_type: DIGITAL 或者 ANALOG
        :param clk_pin: 时钟总线接入的针脚
        :param data_pin: 数据总线接入的针脚
        :param port: 虚谷连接I2C设备的COM口,默认为"/dev/ttyACM0"
        :param debug: 当为True的时候,会输出debug信息
        """
        self.board = PyMata(port, bluetooth=False, verbose=debug)
        # i2c设备初始化
        self.i2c = self.board.i2c_config(0, pin_type, clk_pin, data_pin)
Example #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)
    '''
    com_port = SearchPort.search_dplay_port()
    # com_port = 'com3'

    try:
        # instantiate PyMata
        firmata = PyMata(com_port, baud_rate=115200)  # pragma: no cover
    except Exception, e:
        print 'Could not instantiate PyMata - is your Arduino plugged in?'
        print e
        logging.exception(
            'Could not instantiate PyMata - is your Arduino plugged in?')
        logging.debug("Exiting s2a_fm")
        return
Example #11
0
    def __init__(self, pin_num, pin_model, pin_type=None, port="/dev/ttyACM0",
                 debug=False):
        """

        :param pin_num: 针脚,已a开头的表示为模拟信号针脚,已d开头的表示为数字信号针脚,编号范围0~19
        :param pin_model: 接受INPUT或者OUTPUT类型
        :param port: 虚谷连接arduino的COM口,默认为"/dev/ttyACM0"
        :param debug: 当为True的时候,会输出debug信息
        """
        pin_num, _pin_type = check_pin_num(pin_num)
        if not pin_type:
            pin_type = _pin_type
        self.pin_num = pin_num
        self.board = PyMata(port, bluetooth=False, verbose=debug)
        self.board.set_pin_mode(self.pin_num, pin_model, pin_type)
Example #12
0
    def __init__(self, port='/dev/ttyACM0'):

        #Warn experimenter that ports are going to switch on, before they are turned off again after initialization
        raw_input(
            'WARNING: Switch off your instruments, all ports are going to turn on. Press ANY KEY to continue'
        )
        self.board = PyMata(port)

        #Look at pymata.py and pymata_command_handler.py if you want to follow the logic. PyMata instances have a _command_handler 			instance in them - this _command_handler instance has two variables - total_pins_discovered and  				number_of_analog_pins_discovered. This sets digital pins 0 to (total_pins_discovered - number_of 			analog_pins_discovered - 1) to 0
        dio = self.board._command_handler.total_pins_discovered - self.board._command_handler.number_of_analog_pins_discovered

        for i in range(dio):
            self.board.digital_write(i, 0)

        print 'It is safe to turn your instruments on now. All digital ports have been switched off'
Example #13
0
    def run(self):
        try:
            from PyMata.pymata import PyMata
        except ImportError:
            logger.error("Pymata not installed, Arduino disabled!")
            return
        else:
            self.running = True
            while self.running:
                if not self.board:
                    if not os.path.exists(self.path):
                        logger.info(
                            "No Arduino, waiting for %s to become available",
                            self.path)
                        self.wake.wait()
                    if not self.running:
                        break
                    board = PyMata(self.path, bluetooth=False)
                    try:
                        for pin in self.pwm:
                            logger.debug("Setting up pin %s as PWM output" %
                                         pin)
                            board.set_pin_mode(pin, board.PWM, board.DIGITAL)
                        for pin in self.fwd + self.rev:
                            logger.debug(
                                "Setting up pin %s as digital output" % pin)
                            board.set_pin_mode(pin, board.OUTPUT,
                                               board.DIGITAL)
                        board.set_pin_mode(self.kicker, board.OUTPUT,
                                           board.DIGITAL)
                        board.digital_write(self.kicker, False)
                    except serial.serialutil.SerialException:
                        logger.error("Failed to connect to Arduino")
                        continue  # Try again
                    else:
                        self.board = board
                        self.alive = True

                self.changed.wait()
                if not self.running:
                    break
                self.changed.clear()
                self.write()
            self.set_abc(0, 0, 0)
            self.write()
Example #14
0
def main():
    notifier = sdnotify.SystemdNotifier()

    the_ipc_session = wp_ipc.Session()

    port = os.environ.get('FIRMATA_PORT', '/dev/ttyACM0')

    board = PyMata(port, verbose=True, bluetooth=False)

    board.set_pin_mode(LED_PIN, board.OUTPUT, board.DIGITAL)
    board.set_pin_mode(BUTTON_PIN, board.PULLUP, board.DIGITAL)
    board.set_pin_mode(FAN_PIN, board.PWM, board.ANALOG)
    board.servo_config(GAUGE_PIN)
    board.set_pin_mode(POTENTIOMETER_ANALOG_PIN, board.INPUT, board.ANALOG)

    notifier.notify("READY=1")

    while True:
        published_values = the_ipc_session.recv()
        for topic, value in published_values.items():
            if "fan_duty" == topic:
                fan_duty255 = int(255 * value)
                if fan_duty255 > 255:
                    fan_duty255 = 255
                if fan_duty255 < 0:
                    fan_duty255 = 0
                board.analog_write(FAN_PIN, fan_duty255)
            elif "gauge_degrees" == topic:
                board.analog_write(GAUGE_PIN, 180 - value)
            elif "led" == topic:
                board.digital_write(LED_PIN, value)

        pot1024 = board.analog_read(POTENTIOMETER_ANALOG_PIN)
        pot = (1.0 / 1024.0) * pot1024

        button_pressed = not bool(board.digital_read(BUTTON_PIN))

        the_ipc_session.send("potentiometer", pot)
        the_ipc_session.send("button", button_pressed)

        gevent.sleep(0.100)

        notifier.notify("WATCHDOG=1")
Example #15
0
    def __init__(self, port=None):
        try:
            from PyMata.pymata import PyMata
        except ImportError:
            msg = 'pingo.arduino.Arduino requires PyMata installed'
            raise ImportError(msg)

        super(ArduinoFirmata, self).__init__()
        self.port = port
        self.PyMata = PyMata(self.port)

        detected_digital_pins = len(
            self.PyMata._command_handler.digital_response_table)
        detected_analog_pins = len(
            self.PyMata._command_handler.analog_response_table)

        self._add_pins([
            DigitalPin(self, location)
            for location in range(detected_digital_pins)
        ] + [
            AnalogPin(self, 'A%s' % location, resolution=10)
            for location in range(detected_analog_pins)
        ])
Example #16
0
    def __init__(self, port=None):
        try:
            from PyMata.pymata import PyMata as PyMata  # noqa
        except ImportError:
            msg = 'pingo.arduino.Arduino requires PyMata installed'
            raise ImportError(msg)

        super(ArduinoFirmata, self).__init__()
        self.port = port
        self.firmata_client = PyMata(self.port, verbose=VERBOSE)

        self.firmata_client.capability_query()
        time.sleep(10)  # TODO: Find a small and safe value
        capability_query_results = self.firmata_client.get_capability_query_results(
        )
        capability_dict = pin_list_to_board_dict(capability_query_results)

        self._add_pins([
            DigitalPin(self, location)
            for location in capability_dict['digital']
        ] + [PwmPin(self, location) for location in capability_dict['pwm']] + [
            AnalogPin(self, 'A%s' % location, resolution=10)
            for location in capability_dict['analog']
        ])
Example #17
0
def main():
    port = '/dev/ttyACM0'

    base = 0.6
    gust = numpy.sin(numpy.linspace(0, 2 * 3.14, 100))
    wind = base + (0.3) * gust
    print(wind)

    board = PyMata(port, verbose=True)

    FAN_PIN = 3
    GAUGE_PIN = 6
    POTENTIOMETER_ANALOG_PIN = 0

    board.set_pin_mode(13, board.OUTPUT, board.DIGITAL)
    board.set_pin_mode(FAN_PIN, board.PWM, board.ANALOG)
    board.servo_config(GAUGE_PIN)
    board.set_pin_mode(POTENTIOMETER_ANALOG_PIN, board.INPUT, board.ANALOG)

    for _ in range(0, 100):

        for v in list(wind):
            print(v)

            pot1024 = board.analog_read(POTENTIOMETER_ANALOG_PIN)
            pot = (1.0 / 1024.0) * pot1024

            v_scaled = pot * v

            gauge_degrees = 180 - int(180.0 * v_scaled)
            board.analog_write(GAUGE_PIN, gauge_degrees)

            fan_duty = int(255 * v_scaled)
            board.analog_write(FAN_PIN, fan_duty)

            gevent.sleep(0.025)
Example #18
0
# Copyright (C) 2015 by sailoog <https://github.com/sailoog/openplotter>
# 					  e-sailing <https://github.com/e-sailing/openplotter>
# Openplotter is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# any later version.
# Openplotter is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Openplotter. If not, see <http://www.gnu.org/licenses/>.
import signal, sys, time
from PyMata.pymata import PyMata


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


signal.signal(signal.SIGINT, signal_handler)
board = PyMata("/dev/ttyOP_FIRM")
time.sleep(1)
board.reset
board.close
Example #19
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
Example #20
0
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)


# Data change callback functions
def cb_potentiometer(data):
    print("Analog Data: ", " Pin: ", data[PIN_NUMBER], " Pin Mode: ",
          data[PIN_MODE], " Data Value: ", data[DATA_VALUE])


def cb_push_button(data):
    print("Digital Data:", " Pin: ", data[PIN_NUMBER], " Pin Mode: ",
          data[PIN_MODE], " Data Value: ", data[DATA_VALUE])


# Instantiate PyMata
board = PyMata("/dev/ttyACM0", verbose=True)

# Set up pin modes for both pins with callbacks for each
board.set_pin_mode(PUSH_BUTTON, board.INPUT, board.DIGITAL, cb_push_button)
board.set_pin_mode(POTENTIOMETER, board.INPUT, board.ANALOG, cb_potentiometer)

# A forever loop until user presses Ctrl+C
while 1:
    pass
Example #21
0
 def __init__(self, port):
     """Initialize the board."""
     from PyMata.pymata import PyMata
     self._port = port
     self._board = PyMata(self._port, verbose=False)
This demo polls the current values returned from a rotary encoder.

It will only work on an Arduino Uno and requires the PyMataPlus sketch to be installed on the Arduino
"""

import sys
import signal

from PyMata.pymata import PyMata

ENCODER_A = 14
ENCODER_B = 15
prev_value = 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)

# configure the pins for the encoder
board.encoder_config(ENCODER_B, ENCODER_A)

while 1:
Example #23
0
import time
import sys
import signal

from capture import pictureCapture
from PyMata.pymata import PyMata
from pymata_aio.pymata3 import PyMata3
import cv2

FLAG = 1
# 超声波传感器初始化
board = PyMata("COM5", verbose=True)
board.sonar_config(12, 12)
# 舵机初始化
SERVO_MOTOR = 9
board.servo_config(SERVO_MOTOR)

# 视频初始化


# 杆子抬起放下操作
def arise_down():
    board.analog_write(SERVO_MOTOR, 0)
    time.sleep(3)
    board.analog_write(SERVO_MOTOR, 95)
    # time.sleep(5)
    print('车辆通行')
    # board.analog_write(SERVO_MOTOR, 0)


# 读取距离当距离小于一定值时,返回开始进行操作
    def Start(self, vehicle):
        logger.log("+-+-+-+-+-+-+ Starting up %s +-+-+-+-+-+-+" % VERSION)

        ### initialize dronekit vehicle ###
        self.vehicle = vehicle

        ### switch vehicle to loiter mode ###
        self.vehicle.mode = VehicleMode("LOITER")

        ### initialize rc manager ###
        self.rcMgr = rcManager.rcManager(self)

        ### initialize app manager ###
        self.appMgr = appManager.appManager(self)

        ### initialize button manager ###
        self.buttonManager = buttonManager.buttonManager(self)

        ### initialize gopro manager ###
        self.goproManager = GoProManager.GoProManager(self)

        ### Initialize GeoFence manager ###
        self.geoFenceManager = GeoFenceManager.GeoFenceManager(self)

        # instantiate rewindManager
        self.rewindManager = rewindManager.RewindManager(self.vehicle, self)
	
	    # Create a PyMata instance and initialize the object avoidance toggles
        self.led_left_state = 0
        self.led_right_state = 0
        self.led_center_state = 0
        self.led_beam_angle_state = 0
        self.center_collision_state = 0

        try:
            self.arduinoBoard = PyMata("/dev/ttyACM0", verbose=True)
            self.arduinoBoard.set_pin_mode(COLL_RIGHT, self.arduinoBoard.INPUT, self.arduinoBoard.DIGITAL)
            self.arduinoBoard.set_pin_mode(COLL_CENTER, self.arduinoBoard.INPUT, self.arduinoBoard.DIGITAL)
            self.arduinoBoard.set_pin_mode(COLL_LEFT, self.arduinoBoard.INPUT, self.arduinoBoard.DIGITAL)
            self.arduinoBoard.set_pin_mode(SCAN_BIT1, self.arduinoBoard.INPUT, self.arduinoBoard.DIGITAL)
            self.arduinoBoard.set_pin_mode(SCAN_BIT2, self.arduinoBoard.INPUT, self.arduinoBoard.DIGITAL)
            self.arduinoBoard.set_pin_mode(SCAN_BIT3, self.arduinoBoard.INPUT, self.arduinoBoard.DIGITAL)
            self.arduinoBoard.set_pin_mode(SCAN_BIT4, self.arduinoBoard.INPUT, self.arduinoBoard.DIGITAL)
        except:
            logger.log("[shotmanager]: Error in communication to Arduino")

        ### init APM stream rates ###
        self.initStreamRates()

		### register callbacks ###
        self.registerCallbacks()
        
        # Try to maintain a constant tick rate
        self.timeOfLastTick = monotonic.monotonic()
        # how many ticks have we performed since an RC update?

        # register all connections (gopro manager communicates via appMgr's socket)
        self.inputs = [self.rcMgr.server, self.appMgr.server]
        self.outputs = []

		#check if gimbal is present
        if self.vehicle.gimbal.yaw is not None:
	        logger.log("[shot]: Gimbal detected.")
	        # Initialize gimbal to RC targeting
	        self.vehicle.gimbal.release()
        else:
            logger.log("[shot]: No gimbal detected.")

        # mark first tick time
        self.timeOfLastTick = monotonic.monotonic()

        # check for In-Air start from Shotmanager crash
        if self.vehicle.system_status == 'ACTIVE':
            logger.log("[shot]: Restart in air.")
            # load vehicle home    
            self.rewindManager.loadHomeLocation()
Example #25
0
#Test działania modułu RGB-LED KY-016 wesja Analog

import sys
import signal
from tkinter import *
from PyMata.pymata import PyMata

# Podpięte piny Digital 9, 10, 11
blue = 11
red = 9
green = 10
#board = PyMata("/dev/ttyACM0", verbose=True)
board = PyMata("\.\COM4", verbose=True)
# Ustawienie modułu piny blue, green, red PWM
board.set_pin_mode(blue, board.PWM, board.DIGITAL)
board.set_pin_mode(green, board.PWM, board.DIGITAL)
board.set_pin_mode(red, board.PWM, board.DIGITAL)


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)


def rd(val):
    board.analog_write(red, int(val))
Example #26
0
This file demonstrates how to use some of the basic PyMata operations.
"""

import time
import sys
import signal

from PyMata.pymata import PyMata

# Digital pin 13 is connected to an LED. If you are running this script with
# an Arduino UNO no LED is needed (Pin 13 is connected to an internal LED).
BOARD_LED = 13
MAGICFLY_CONTROL = 0x42

# Create a PyMata instance
board = PyMata("/COM4", verbose=True)


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)

# Set digital pin 13 to be an output port
board.set_pin_mode(BOARD_LED, board.OUTPUT, board.DIGITAL)

time.sleep(2)
Example #27
0
"""
"""
This file demonstrates using PyMata to control a stepper motor. It requires the use of the FirmataPlus
Arduino sketch included with this release.

It is based upon the following tutorial: https://learn.adafruit.com/adafruit-arduino-lesson-16-stepper-motors/overview
"""

import signal
import sys
import time

from PyMata.pymata import PyMata

# create a PyMata instance
firmata = PyMata("/dev/ttyACM0")


def signal_handler(sig, frm):
    print('You pressed Ctrl+C!!!!')
    if firmata is not None:
        firmata.reset()
    sys.exit(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
Example #28
0
    def __init__(self, port):
        """Initialize the board."""

        self._port = port
        self._board = PyMata(self._port, verbose=False)
#!/usr/bin/python
import time
import sys
import signal
import paho.mqtt.client as mqtt
from PyMata.pymata import PyMata

DEBUG = True
BOARD_LED = 13
board = PyMata("/dev/ttyS0", verbose=False)


def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))


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)

board.set_pin_mode(BOARD_LED, board.OUTPUT, board.DIGITAL)
board.i2c_config(0, board.DIGITAL, 3, 2)

# Setup MQTT Client
client = mqtt.Client()
client.username_pw_set("********", password="******")
Example #30
-1
    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)