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"
class smartkitdata(object): def __init__(self): self.board = PyMata(ARDUINO_ADDRESS) self.board.set_pin_mode(1, self.board.INPUT, self.board.ANALOG) self._data = self.gen_data() def get_data(self): return pd.DataFrame(self._data)[-60:] def update_data(self): self._data = np.vstack([self._data, self.gen_data()]) def gen_data(self): return np.array(self.board.analog_read(1))
def __init__(self, name, broker, port, keepalive, state_topic, command_topic, qos, retain, payload_on, payload_off, optimistic, value_template,serial_port,switch_pin): self._switch_pin = switch_pin self._board = PyMata(serial_port,False,verbose=True) self._board.set_pin_mode(self._switch_pin,self._board.OUTPUT,self._board.DIGITAL) A0 = 7 def pin_callback(data): print("Analog Data: ", " Pin: ", data[PIN_NUMBER], " Pin Mode: ", data[PIN_MODE], " Data Value: ", data[DATA_VALUE]) self._board.set_analog_latch(A0,self._board.ANALOG_LATCH_GT,500,pin_callback) # self._board.set_pin_mode(A0, self._board.INPUT, self._board.ANALOG) # self._board.set_sampling_interval(100) # self._board.set_analog_latch(A0,self._board.ANALOG_LATCH_GT,500,pin_callback) # while True: # time.sleep(0.1) # value = self._board.analog_read(A0) # print(value) self._mqtt = mqtt.Client() self._switch = None self._state_topic = state_topic self._command_topic = command_topic self._qos = qos self._retain = retain self._payload_on = payload_on self._payload_off = payload_off self._optimistic = optimistic self._state = False def on_message( _mqtt, userdata, msg): topic = msg.topic, qos = msg.qos, payload = msg.payload.decode('utf-8'), payload = payload[0] print(msg.topic+" "+payload) if payload == payload_on: self.turn_on() elif payload == payload_off: self.turn_off() self._mqtt.on_message = on_message self._mqtt.connect(broker, port, keepalive) self._mqtt.subscribe(command_topic,qos) self._mqtt.loop_forever()
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'
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
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
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)] )
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 __init__(self): # Initialize fingers and wrist pos self.finger_pos = [0, 0, 0, 0, 0, 90] # Initialize sensor values self.sensor_val = [0, 0, 0, 0, 0] # Initialize the arduino self.arduino = PyMata("/dev/ttyACM0", verbose=True) # Initialize the servos and sensors on arduino for servo_pin in SERVO_PINS: self.arduino.servo_config(servo_pin) for sensor_pin in SENSOR_PINS: self.arduino.enable_analog_reporting(sensor_pin) # Initialize the hand states self.curstate = 'open' self.states = {} self.transitionTable = {}
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']] )
# pymata_analogRead.py # PyMata analog read example from PyMata.pymata import PyMata import time # Pin no. A0 pinNo = 0 # connection port PORT = '/dev/ttyACM0' # Create PyMata instance board = PyMata(PORT, verbose=True) # Set digital pin 13 to be an output port board.set_pin_mode(pinNo, board.INPUT, board.ANALOG) while True: pin = board.analog_read(pinNo) print 'analog read : A0: {}'.format(pin) time.sleep(0.5)
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import time import sys import signal from PyMata.pymata import PyMata # Ping callback function def cb_ping(data): print((str(data[2]) + ' centimeters')) # Create a PyMata instance board = PyMata("/dev/ttyACM0", verbose=True) # you may need to press control-c twice to exit def signal_handler(sig, frame): print('You pressed Ctrl+C!!!!') if board is not None: board.reset() board.close() sys.exit(0) signal.signal(signal.SIGINT, signal_handler) # Configure Trigger and Echo pins # Using default of 50 ms ping interval and max distance of 200 cm. board.sonar_config(12, 12, cb_ping)
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()
class ShotManager(): def __init__(self): # see the shotlist in app/shots/shots.py self.currentShot = shots.APP_SHOT_NONE self.currentModeIndex = DEFAULT_APM_MODE self.curController = None 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() # not yet enabled until this check proves effective #self.vehicle.mode = VehicleMode("RTL") def Run(self): while True: try: #print "in shotManager server loop" # handle TCP/RC packets # we set a timeout of UPDATE_TIME, so we roughly do this every UPDATE_TIME rl, wl, el = select.select(self.inputs, self.outputs, [], UPDATE_TIME) # handle reads for s in rl: if s is self.appMgr.server: # if read is a connection attempt self.appMgr.connectClient() elif s is self.appMgr.client: # if read is from app self.appMgr.parse() elif s is self.rcMgr.server: # if read is an RC packet self.rcMgr.parse() elif s is self.buttonManager.client: # if read is from buttons self.buttonManager.parse() # now handle writes (sololink.btn_msg handles all button writes) for s in wl: if s is self.appMgr.client: # if write is for app self.appMgr.write() # exceptions for s in el: if s is self.appMgr.client: # if its the app socket throwing an exception self.appMgr.exception() else: # otherwise remove whichever socket is excepting if s in self.inputs: self.inputs.remove(s) if s in self.outputs: self.outputs.remove(s) s.close() self.buttonManager.checkButtonConnection() # Check for obstacles when the lidar is active if (self.buttonManager.scanactive == 1): self.checkForObstacle() # Check if copter is outside fence or will be self.geoFenceManager.activateGeoFenceIfNecessary() # call main control/planning loop at UPDATE_RATE if time.time() - self.timeOfLastTick > UPDATE_TIME: self.Tick() except Exception as ex: # reset any RC timeouts and stop any stick remapping self.rcMgr.detach() # try to put vehicle into LOITER self.vehicle.mode = VehicleMode("LOITER") exceptStr = traceback.format_exc() print exceptStr strlist = exceptStr.split('\n') for i in strlist: logger.log(i) if self.appMgr.isAppConnected(): # send error to app packet = struct.pack( '<II%ds' % (len(exceptStr)), app_packet.SOLO_MESSAGE_SHOTMANAGER_ERROR, len(exceptStr), exceptStr) self.appMgr.client.send(packet) # sleep to make sure the packet goes out (for some reason # setting client.setblocking(1) doesn't work) time.sleep(0.4) # cleanup for socket in self.inputs: socket.close() os._exit(1) def enterShot(self, shot): if shot not in shots.SHOT_NAMES: logger.log("[shot]: Shot not recognized. (%d)" % shot) return if shot == shots.APP_SHOT_NONE: pass # check our EKF - if it's bad and that we can't init the shot prior to EKF being OK, reject shot entry attempt elif self.last_ekf_ok is False and shot not in shots.CAN_START_BEFORE_EKF: logger.log( '[shot]: Vehicle EKF quality is poor, shot entry into %s disallowed.' % shots.SHOT_NAMES[shot]) # set shot to APP_SHOT_NONE shot = shots.APP_SHOT_NONE # notify the app of shot entry failure packet = struct.pack('<III', app_packet.SOLO_SHOT_ERROR, 4, app_packet.SHOT_ERROR_BAD_EKF) self.appMgr.sendPacket(packet) # check vehicle system status - if it's CRITICAL or EMERGENCY, reject shot entry attempt elif self.vehicle.system_status in ['CRITICAL', 'EMERGENCY']: logger.log( '[shot]: Vehicle in %s, shot entry into %s disallowed.' % (self.vehicle.system_status, shots.SHOT_NAMES[shot])) # set shot to APP_SHOT_NONE shot = shots.APP_SHOT_NONE # notify the app of shot entry failure packet = struct.pack('<III', app_packet.SOLO_SHOT_ERROR, 4, app_packet.SHOT_ERROR_RTL) self.appMgr.sendPacket(packet) # check if vehicle is not armed or in STANDBY and that we can't init the shot prior to arm, reject shot entry attempt elif (self.vehicle.armed is False or self.vehicle.system_status == 'STANDBY') and shot not in shots.CAN_START_BEFORE_ARMING: logger.log( '[shot]: Vehicle is unarmed, shot entry into %s disallowed.' % shots.SHOT_NAMES[shot]) self.vehicle.mode = VehicleMode("LOITER") # set shot to APP_SHOT_NONE shot = shots.APP_SHOT_NONE # notify the app of shot entry failure packet = struct.pack('<III', app_packet.SOLO_SHOT_ERROR, 4, app_packet.SHOT_ERROR_UNARMED) self.appMgr.sendPacket(packet) # OK fine, you get to start the shot. if self.currentShot != shot: logger.log('[shot]: Entering shot %s.' % shots.SHOT_NAMES[shot]) if self.currentShot == shots.APP_SHOT_REWIND: # we are exiting Rewind self.rewindManager.resetSpline() # APP_SHOT_NONE if shot == shots.APP_SHOT_NONE: # mark curController for garbage collection del self.curController # set curController to None (should also mark for garbage collection) self.curController = None # re-enable manual gimbal controls (RC Targeting mode) self.vehicle.gimbal.release() # disable the stick re-mapper self.rcMgr.enableRemapping(False) # disable scanning self.arduinoBoard.digital_write(6, 0) # if the Rewind shot put us into RTL, lets stay there if self.vehicle.mode.name == 'RTL': logger.log("[shot]: Leaving vehicle in mode RTL") # if vehicle mode is in another mode such as GUIDED or AUTO, then switch to LOITER elif self.vehicle.mode.name in shots.SHOT_MODES: logger.log("[shot]: Changing vehicle mode to LOITER.") self.vehicle.mode = VehicleMode("LOITER") else: self.curController = ShotFactory.get_shot_obj( shot, self.vehicle, self) # update currentShot self.currentShot = shot logger.log("[shot]: Successfully entered %s." % shots.SHOT_NAMES[shot]) # already in that shot else: logger.log('[shot]: Already in shot %s.' % shots.SHOT_NAMES[shot]) # let the world know if self.appMgr.isAppConnected(): self.appMgr.broadcastShotToApp(shot) # let Artoo know too self.buttonManager.setArtooShot(shot) # set new button mappings appropriately self.buttonManager.setButtonMappings() def mode_callback(self, vehicle, name, mode): try: if mode.name != self.lastMode: logger.log("[callback]: Mode changed from %s -> %s" % (self.lastMode, mode.name)) if mode.name == 'RTL': logger.log( "[callback]: System entered RTL, switch to shot!") self.enterShot(shots.APP_SHOT_RTL) elif self.currentShot != shots.APP_SHOT_NONE: # looks like somebody switched us out of guided! Exit our current shot if mode.name not in shots.SHOT_MODES: logger.log( "[callback]: Detected that we are not in the correct apm mode for this shot. Exiting shot!" ) self.enterShot(shots.APP_SHOT_NONE) self.lastMode = mode.name # don't do the following for guided, since we're in a shot if self.lastMode == 'GUIDED' or mode.name == 'RTL': return modeIndex = modes.getAPMModeIndexFromName( self.lastMode, self.vehicle) if modeIndex < 0: logger.log("couldn't find this mode index: %s" % self.lastMode) return if self.currentShot == shots.APP_SHOT_NONE: self.buttonManager.setArtooShot(-1, modeIndex) self.currentModeIndex = modeIndex except Exception as e: logger.log('[shot]: mode callback error, %s' % e) def ekf_callback(self, vehicle, name, ekf_ok): try: if ekf_ok != self.last_ekf_ok: self.last_ekf_ok = ekf_ok logger.log("[callback]: EKF status changed to %d" % (ekf_ok)) self.buttonManager.setButtonMappings() # if we regain EKF and are landing - just push us into fly if ekf_ok and self.vehicle.mode.name == 'LAND': self.enterShot(shots.APP_SHOT_NONE) # only store home in the air when no home loc exists if self.rewindManager: if ekf_ok and self.last_armed and self.rewindManager.homeLocation is None: self.rewindManager.loadHomeLocation() except Exception as e: logger.log('[callback]: ekf callback error, %s' % e) def armed_callback(self, vehicle, name, armed): try: if armed != self.last_armed: self.last_armed = armed logger.log("[callback]: armed status changed to %d" % (armed)) self.buttonManager.setButtonMappings() # clear Rewind manager cache self.rewindManager.resetSpline() if not armed and self.currentShot not in shots.CAN_START_BEFORE_ARMING: self.enterShot(shots.APP_SHOT_NONE) self.vehicle.mode = VehicleMode("LOITER") # stop recording upon disarm (landing, hopefully) if not armed: self.goproManager.handleRecordCommand( self.goproManager.captureMode, RECORD_COMMAND_STOP) # read home loc from vehicle if armed: self.rewindManager.loadHomeLocation() except Exception as e: logger.log('[callback]: armed callback error, %s' % e) def camera_feedback_callback(self, vehicle, name, msg): try: if self.currentShot in shots.SITE_SCAN_SHOTS or self.vehicle.mode.name == 'AUTO': # issue GoPro record command self.goproManager.handleRecordCommand(CAPTURE_MODE_PHOTO, RECORD_COMMAND_START) except Exception as e: logger.log('[callback]: camera feedback callback error, %s.' % e) def initStreamRates(self): STREAM_RATES = { mavutil.mavlink.MAV_DATA_STREAM_EXTENDED_STATUS: 2, mavutil.mavlink.MAV_DATA_STREAM_EXTRA1: 10, mavutil.mavlink.MAV_DATA_STREAM_EXTRA2: 10, mavutil.mavlink.MAV_DATA_STREAM_EXTRA3: 2, mavutil.mavlink.MAV_DATA_STREAM_POSITION: 10, mavutil.mavlink.MAV_DATA_STREAM_RAW_SENSORS: 2, mavutil.mavlink.MAV_DATA_STREAM_RAW_CONTROLLER: 3, mavutil.mavlink.MAV_DATA_STREAM_RC_CHANNELS: 5, } for stream, rate in STREAM_RATES.items(): msg = self.vehicle.message_factory.request_data_stream_encode( 0, 1, # target system, target component stream, # requested stream id rate, # rate 1 # start it ) self.vehicle.send_mavlink(msg) def notifyPause(self, inShot=0): '''notify the autopilot that we would like to pause''' if inShot: return msg = self.vehicle.message_factory.command_long_encode( 0, # target system 1, # target component mavutil.mavlink.MAV_CMD_SOLO_BTN_PAUSE_CLICK, # frame 0, # confirmation int(inShot), # param 1: 1 if Solo is in a shot mode, 0 otherwise 0, 0, 0, 0, 0, 0) # params 2-7 (not used) # send command to vehicle self.vehicle.send_mavlink(msg) # This fetches and returns the value of the parameter matching the given name # If the parameter is not found, returns the given default value instead def getParam(self, name, default=None): return self.vehicle.parameters.get(name, wait_ready=False) or default # we call this at our UPDATE_RATE # drives the shots as well as anything else timing-dependent def Tick(self): self.timeOfLastTick = time.time() self.rcMgr.rcCheck() # update rewind manager if (self.currentShot == shots.APP_SHOT_REWIND or self.currentShot == shots.APP_SHOT_RTL or self.vehicle.mode.name == 'RTL') is False: self.rewindManager.updateLocation() # Always call remap channels = self.rcMgr.remap() if self.curController: self.curController.handleRCs(channels) def getHomeLocation(self): if self.rewindManager.homeLocation is None or self.rewindManager.homeLocation.lat == 0: return None else: return self.rewindManager.homeLocation def enterFailsafe(self): ''' called when we loose RC link or have Batt FS event ''' # dont enter failsafe on the ground if not self.vehicle.armed or self.vehicle.system_status != 'ACTIVE': return # dont enter failsafe if we are already rewinding home if self.currentShot == shots.APP_SHOT_REWIND: self.curController.exitToRTL = True return if self.currentShot == shots.APP_SHOT_RTL: return if self.last_ekf_ok is False: # no GPS - force an emergency land self.vehicle.mode = VehicleMode("LAND") return # ignore FS while in Auto mode if self.vehicle.mode.name == 'AUTO' and self.rewindManager.fs_thr == 2: return if self.rewindManager.enabled: self.enterShot(shots.APP_SHOT_REWIND) self.curController.exitToRTL = True else: self.enterShot(shots.APP_SHOT_RTL) def registerCallbacks(self): self.last_ekf_ok = False self.last_armed = False self.lastMode = self.vehicle.mode.name # MODE self.vehicle.add_attribute_listener( 'mode', self.mode_callback) #register with vehicle class (dronekit) # EKF # call ekf back first self.ekf_callback(self.vehicle, 'ekf_ok', self.vehicle.ekf_ok) self.vehicle.add_attribute_listener( 'ekf_ok', self.ekf_callback) #register with vehicle class (dronekit) # ARMED self.vehicle.add_attribute_listener( 'armed', self.armed_callback) #register with vehicle class (dronekit) # CAMERA FEEDBACK self.vehicle.add_message_listener( 'CAMERA_FEEDBACK', self.camera_feedback_callback ) #register with vehicle class (dronekit) # gopro manager callbacks (defined in gopro manager) self.vehicle.add_attribute_listener('gopro_status', self.goproManager.state_callback) self.vehicle.add_attribute_listener( 'gopro_get_response', self.goproManager.get_response_callback) self.vehicle.add_attribute_listener( 'gopro_set_response', self.goproManager.set_response_callback) def checkForObstacle(self): # check if beam will hit the ground at altitudes lower than 3 meters then disable scan self.pitch_angle = abs(self.vehicle.attitude.pitch) self.check_altitude = self.vehicle.location.global_relative_frame.alt #logger.log("pitch: %s" % self.pitch_angle) if (self.vehicle.attitude.pitch < 0 and self.check_altitude < 3): self.beamreach = (self.check_altitude / math.sin(self.pitch_angle)) else: self.beamreach = 1000 if (self.beamreach > SCAN_BEAM_DISTANCE): if (self.led_beam_angle_state == 1): self.led_beam_angle_state = 0 self.LEDrgb(2, 2, 0, 255, 0) self.LEDrgb(3, 2, 255, 0, 0) if (self.arduinoBoard.digital_read(COLL_RIGHT) == 1): if (self.led_right_state == 0): logger.log("[objavoid]: Obstacle on the right") # send info to app if self.appMgr.isAppConnected(): exceptStr = "Obstacle to the right" packet = struct.pack( '<II%ds' % (len(exceptStr)), app_packet.SOLO_MESSAGE_SHOTMANAGER_ERROR, len(exceptStr), exceptStr) self.appMgr.client.send(packet) # sleep to make sure the packet goes out time.sleep(0.1) # LED right_front set to strobe magenta self.LEDrgb(3, 2, 255, 0, 0) self.LEDrgb(2, 4, 255, 0, 255) self.led_right_state = 1 self.led_left_state = 0 self.led_center_state = 0 self.led_beam_angle_state = 0 elif (self.arduinoBoard.digital_read(COLL_CENTER) == 1): if (self.led_center_state == 0): logger.log("[objavoid]: Obstacle in center") # when we are not in a shot, nor in RTL or LAND and flying higher than 1 meter if (self.currentShot == shots.APP_SHOT_NONE and (self.vehicle.mode.name != 'LAND' or self.vehicle.mode.name != 'RTL')): if (self.check_altitude > 1): self.vehicle.mode = VehicleMode("BRAKE") # all other shots and modes trigger an audio and visual warning only to not interfere with shots # send status to app if self.appMgr.isAppConnected(): exceptStr = "Obstacle ahead in %.1f" % self.coll_distance( ) + " meters" packet = struct.pack( '<II%ds' % (len(exceptStr)), app_packet.SOLO_MESSAGE_SHOTMANAGER_ERROR, len(exceptStr), exceptStr) self.appMgr.client.send(packet) # sleep to make sure the packet goes out time.sleep(0.2) # both LED front set to strobe magenta self.LEDrgb(2, 4, 255, 0, 255) self.LEDrgb(3, 4, 255, 0, 255) self.led_right_state = 0 self.led_left_state = 0 self.led_center_state = 1 self.led_beam_angle_state = 0 elif (self.arduinoBoard.digital_read(COLL_LEFT) == 1): if (self.led_left_state == 0): logger.log("[objavoid]: Obstacle on the left") # send status to app if self.appMgr.isAppConnected(): exceptStr = "Obstacle to the left" packet = struct.pack( '<II%ds' % (len(exceptStr)), app_packet.SOLO_MESSAGE_SHOTMANAGER_ERROR, len(exceptStr), exceptStr) self.appMgr.client.send(packet) # sleep to make sure the packet goes out time.sleep(0.1) # LED left_front set to strobe magenta self.LEDrgb(2, 2, 0, 255, 0) self.LEDrgb(3, 4, 255, 0, 255) self.led_right_state = 0 self.led_left_state = 1 self.led_center_state = 0 self.led_beam_angle_state = 0 else: # no obstacle in sight reset everything if (self.led_left_state == 1 or self.led_right_state == 1 or self.led_center_state == 1): logger.log("[objavoid]: no obstacle in sight reset LED") self.LEDrgb(2, 2, 0, 255, 0) self.LEDrgb(3, 2, 255, 0, 0) self.led_right_state = 0 self.led_left_state = 0 self.led_center_state = 0 self.led_beam_angle_state = 0 else: if (self.led_beam_angle_state == 0): logger.log( "[objavoid]: pitch/altitude too low - obstacle detection disabled" ) self.LEDrgb(2, 4, 255, 100, 0) self.LEDrgb(3, 4, 255, 100, 0) self.led_beam_angle_state = 1 self.led_right_state = 0 self.led_left_state = 0 self.led_center_state = 0 # send status to app if self.appMgr.isAppConnected(): exceptStr = "Solo altitude too low for scan" packet = struct.pack( '<II%ds' % (len(exceptStr)), app_packet.SOLO_MESSAGE_SHOTMANAGER_ERROR, len(exceptStr), exceptStr) self.appMgr.client.send(packet) # sleep to make sure the packet goes out time.sleep(0.1) def coll_distance(self): x = str(self.arduinoBoard.digital_read(SCAN_BIT4)) + str( self.arduinoBoard.digital_read(SCAN_BIT3)) + str( self.arduinoBoard.digital_read(SCAN_BIT2)) + str( self.arduinoBoard.digital_read(SCAN_BIT1)) y = float(int(x, 2)) / 2 return y def LEDpadArray(self, byteArray): return byteArray + bytearray([0]) * (24 - len(byteArray)) # Set LED pattern and color (RGB value) def LEDrgb(self, led, pattern, red, green, blue): #print "rgb", led, pattern, red, green, blue byteArray = bytearray(['R', 'G', 'B', '0', pattern, red, green, blue]) self.LEDsendMessage(led, 255, byteArray) # reset LED to default behavior def LEDreset(self, led): #print "reset", led self.LEDsendMessage(led, 0) def LEDsendMessage(self, led, macro, byteArray=bytearray()): #print "sendMessage", led, macro, ":".join(str(b) for b in byteArray) msg = self.vehicle.message_factory.led_control_encode( 0, 0, led, macro, len(byteArray), self.LEDpadArray(byteArray)) self.vehicle.send_mavlink(msg) # Can't find a functional flush() operation, so wait instead time.sleep(0.2)
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()
""" """ This example illustrates manipulating a servo motor. """ import time import sys import signal from PyMata.pymata import PyMata SERVO_MOTOR = 5 # servo attached to this pin # 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) # move the servo to 20 degrees
Created on 16/02/2016 @author: jecrespo @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]
# re-arm the latch to fire on the next transition to high board.set_digital_latch(PUSH_BUTTON, board.DIGITAL_LATCH_HIGH, cb_push_button) 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) # create a PyMata instance board = PyMata("/dev/ttyACM0") # set pin modes # set the pin to light the green led board.set_pin_mode(GREEN_LED, board.OUTPUT, board.DIGITAL) # set the pin to receive button presses board.set_pin_mode(PUSH_BUTTON, board.INPUT, board.DIGITAL) # arm the digital latch to detect when the button is pressed board.set_digital_latch(PUSH_BUTTON, board.DIGITAL_LATCH_HIGH, cb_push_button) while 1: pass
# LCD module HD44780 import time import sys import signal import pymata_pwm from PyMata.pymata import PyMata board = PyMata('/dev/ttyS0', verbose = True) ###### 4-bits mode bit config ###### # bit7 ---------------------- bit0 # # d7 d6 d5 d4 bl en rw rs # #################################### device_addr = 0x27 # device address bl_bit = 0x08 # backlight bit en_bit = 0x04 # read/write enable bit rw_bit = 0x02 # rs_bit = 0x01 # DATA = 0x01 COMMAND = 0x00 setBackLight = 1 def delay_ms(time_ms): time.sleep(time_ms/1000) # def i2c_send(value, mode):
def cb_potentiometer_latch(data): # turn off LEDs board.analog_write(RED_LED, 0) board.digital_write(GREEN_LED, 0) # print all data from the latch callback including time stamp print('Latching Event Mode:%x Pin:%d Data Value:%d Time of Event:%s' % (data[LATCH_TYPE], data[LATCH_PIN], data[LATCH_DATA_VALUE], time.asctime(time.gmtime(data[LATCH_TIME_STAMP])))) # shut things down board.close() # create a PyMata instance board = PyMata("/dev/ttyACM0", True, False) 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 pin modes board.set_pin_mode(GREEN_LED, board.OUTPUT, board.DIGITAL) board.set_pin_mode(RED_LED, board.PWM, board.DIGITAL) board.set_pin_mode(PUSH_BUTTON, board.INPUT, board.DIGITAL, cb_push_button)
This file demonstrates how to recreate the basic blink sketch using PyMata """ import signal import time from PyMata.pymata import PyMata # Pin 13 has an LED connected on most Arduino boards. # give it a name: LED = 13 # Create an instance of PyMata. SERIAL_PORT = "/dev/ttyACM0" firmata = PyMata(SERIAL_PORT, max_wait_time=10, firmata_type=PyMata.STANDARD_FIRMATA) # initialize the digital pin as an output. firmata.set_pin_mode(LED, firmata.OUTPUT, firmata.DIGITAL) try: # run in a loop over and over again forever: while True: firmata.digital_write( LED, firmata.HIGH) # turn the LED on (HIGH is the voltage level) time.sleep(1.0) # wait for a second firmata.digital_write( LED, firmata.LOW) # turn the LED off by making the voltage LOW
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 # Create a PyMata instance board = PyMata("/dev/ttyUSB0", 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)
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:
from PyMata.pymata import PyMata # Define some devices and their pin numbers and desired mode RED_LED = 11 # a digital output to control an LED WHITE_LED = 6 # a PWM output to control LED BUTTON_SWITCH = 12 # a digital input to read a push button switch POTENTIOMETER = 2 # this A2, an analog input BEEPER = 3 # A digital output connected to a piezo device SERVO_MOTOR = 5 # Create an instance of PyMata. # The PyMata constructor will print status to the console and will return # when PyMata is ready to accept commands or will exit if unsuccessful firmata = PyMata("/dev/ttyACM0") # Retrieve and print Arduino Firmware version information firmata.refresh_report_firmware() print firmata.get_firmata_firmware_version() # Set the pin mode for a digital output pin firmata.set_pin_mode(RED_LED, firmata.OUTPUT, firmata.DIGITAL) # Turn on the RED LED firmata.digital_write(RED_LED, 1) # Wait 3 seconds and turn it off time.sleep(3)
import signal from PyMata.pymata import PyMata 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) # Create a PyMata instance board = PyMata("/dev/ttyACM0") # Set the pin mode board.servo_config(5) board.set_pin_mode(12, board.OUTPUT, board.DIGITAL) board.set_pin_mode(0, board.INPUT, board.ANALOG) # Send query request to Arduino board.capability_query() # Some boards take a long time to respond - adjust as needed time.sleep(5) print("Pin Capability Report") print(board.get_capability_query_results()) print("PyMata Digital Response Table")
""" This is a demonstration of playing a tone on a piezo device. FirmataPlus is required to be loaded on the Arduino for this to work """ import time import sys import signal from PyMata.pymata import PyMata BEEPER = 3 # pin that piezo device is attached to # create a PyMata instance board = PyMata("/dev/ttyACM0") def signal_handler(sig, frm): print('You pressed Ctrl+C!!!!') if board is not None: board.reset() sys.exit(0) signal.signal(signal.SIGINT, signal_handler) board.play_tone(BEEPER, board.TONE_TONE, 1000, 500) time.sleep(2) # play a continuous tone, wait 3 seconds and then turn tone off
import logging import os from flask import Flask from flask_apscheduler import APScheduler from flask_sqlalchemy import SQLAlchemy from PyMata.pymata import PyMata from slackclient import SlackClient logging.basicConfig( level=logging.DEBUG, format='%(asctime)s (%(threadName)-10s) %(message)s', ) app = Flask(__name__) app.config.from_object('config') # instantiate db before scheduler, as it is a dependency for some jobs db = SQLAlchemy(app) # instantiate slack_client before scheduler, as it is a dependency for some jobs slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN')) # instantiate PyMata interface to the MCU (ATmega32U4) mcu = PyMata("/dev/ttyS0", verbose=True) # instantiate the scheduler scheduler = APScheduler() scheduler.init_app(app) from app import views, models
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 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
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
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 this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import time import sys import signal from PyMata.pymata import PyMata # create a PyMata instance board = PyMata("/dev/ttyACM0", verbose=True) # you may need to press ctrl c twice def signal_handler(sig, frame): print('You pressed Ctrl+C') if board is not None: board.reset() board.close() sys.exit(0) signal.signal(signal.SIGINT, signal_handler) # Configure the trigger and echo pins board.sonar_config(12, 12)
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 # 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)
import json import threading import time import textwrap import subprocess import struct from PyMata.pymata import PyMata # Give the pins names: REDPIN = 5 GREENPIN = 3 BLUEPIN = 6 # Create an instance of PyMata. SERIAL_PORT = "/dev/ttyS0" firmata = PyMata( SERIAL_PORT, max_wait_time=5 ) # initialize the digital pin as an output. firmata.set_pin_mode( REDPIN, firmata.PWM, firmata.DIGITAL) firmata.set_pin_mode( GREENPIN, firmata.PWM, firmata.DIGITAL) firmata.set_pin_mode( BLUEPIN, firmata.PWM, firmata.DIGITAL) api_key='' api_secret='' access_token_key='' access_token_secret='' class DisplayLoop(StreamListener): """ This class is a listener for tweet stream data.
def __init__(self, port): """Initialize the board.""" from PyMata.pymata import PyMata self._port = port self._board = PyMata(self._port, verbose=False)
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()
# Motor pins on Arduino MOTOR_1_PWM = 2 MOTOR_1_A = 3 MOTOR_1_B = 4 MOTOR_2_PWM = 5 MOTOR_2_A = 6 MOTOR_2_B = 7 MOTOR_3_PWM = 8 MOTOR_3_A = 9 MOTOR_3_B = 10 def signal_handler(sig, frame): board.reset() # Here we initialize the motor pins on Arduino board = PyMata(bluetooth=False) signal.signal(signal.SIGINT, signal_handler) board.set_pin_mode(MOTOR_1_PWM, board.PWM, board.DIGITAL) board.set_pin_mode(MOTOR_1_A, board.OUTPUT, board.DIGITAL) board.set_pin_mode(MOTOR_1_B, board.OUTPUT, board.DIGITAL) board.set_pin_mode(MOTOR_2_PWM, board.PWM, board.DIGITAL) board.set_pin_mode(MOTOR_2_A, board.OUTPUT, board.DIGITAL) board.set_pin_mode(MOTOR_2_B, board.OUTPUT, board.DIGITAL) board.set_pin_mode(MOTOR_3_PWM, board.PWM, board.DIGITAL) board.set_pin_mode(MOTOR_3_A, board.OUTPUT, board.DIGITAL) board.set_pin_mode(MOTOR_3_B, board.OUTPUT, board.DIGITAL) class MotorThread(Thread): def __init__(self): Thread.__init__(self) self.daemon = True
class ArduinoFirmata(Board, AnalogInputCapable): 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)] ) def cleanup(self): #self.PyMata.close() has sys.exit(0) if hasattr(self, 'PyMata'): try: self.PyMata.transport.close() except AttributeError: pass def __repr__(self): cls_name = self.__class__.__name__ return '<{cls_name} {self.port!r}>'.format(**locals()) def _set_pin_mode(self, pin, mode): self.PyMata.set_pin_mode( pin.location, PIN_MODES[mode], self.PyMata.DIGITAL ) def _get_pin_state(self, pin): _state = self.PyMata.digital_read(pin.location) if _state == self.PyMata.HIGH: return pingo.HIGH return pingo.LOW def _set_pin_state(self, pin, state): self.PyMata.digital_write( pin.location, PIN_STATES[state] ) def _set_analog_mode(self, pin, mode): pin_id = int(pin.location[1:]) self.PyMata.set_pin_mode( pin_id, self.PyMata.INPUT, self.PyMata.ANALOG ) def _get_pin_value(self, pin): pin_id = int(pin.location[1:]) return self.PyMata.analog_read(pin_id)
import time import sys import signal from PyMata.pymata import PyMata # define Digital pin 12-6 COLL_RIGHT = 4 COLL_CENTER = 3 COLL_LEFT = 2 TOGGLE_SWITCH = 5 SCAN_ENABLE = 6 # Create a PyMata instance board = PyMata("/dev/ttyACM0", verbose=True) def signal_handler(sig, frame): print('You pressed Ctrl+C') print("Stop Scanning") board.digital_write(SCAN_ENABLE, 0) time.sleep(2) if board is not None: board.reset() sys.exit(0) signal.signal(signal.SIGINT, signal_handler) # Set digital pins
class blech_board: 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' def calibrate(self, port, on_time, repeats, iti): for i in range(repeats): sleep(iti) start = time() * 1000.0 self.board.digital_write(port, 1) while True: if (time() * 1000.0 - start) >= on_time * 1000.0: self.board.digital_write(port, 0) break def passive_deliveries_constant(self, ports=[0, 1, 2, 3], iti=15.0, deliveries_per_channel=30, on_time=[0.02, 0.02, 0.02, 0.02]): num_tastes = len(ports) total_deliveries = num_tastes * deliveries_per_channel self.delivery_arr = [] for i in range(total_deliveries): self.delivery_arr.append(i % num_tastes) shuffle(self.delivery_arr) for i in self.delivery_arr: sleep(iti) start = time() * 1000.0 self.board.digital_write(ports[i], 1) while True: if (time() * 1000.0 - start) >= on_time[i] * 1000.0: self.board.digital_write(ports[i], 0) break def clear_tastes(self, ports=[2, 3, 4, 5], open_time=200.0): for i in ports: self.board.digital_write(i, 1) sleep(open_time) for i in ports: self.board.digital_write(port, 0) def np_no_switch(self, poke_ports=[8, 9], taste_ports=[2, 3], deliveries_per_channel=50, iti=5.0, on_time=[0.02, 0.02]): for i in poke_ports: self.board.set_pin_mode(i, self.board.INPUT, self.board.DIGITAL) sleep(2.0) total_deliveries = len(poke_ports) * deliveries_per_channel delivery_counter = 0 while (delivery_counter < total_deliveries): sleep(iti) for i in range(len(poke_ports)): if self.board.digital_read(poke_ports[i]) == 0: start = time() * 1000.0 self.board.digital_write(taste_ports[i], 1) while True: if (time() * 1000.0 - start) >= on_time[i] * 1000.0: self.board.digital_write(taste_ports[i], 0) break print 'Trial ', delivery_counter + 1, ' of ', total_deliveries, ' done' delivery_counter += 1 print 'All done' def np_switching(self, poke_ports=[8, 9], taste_ports=[2, 3], deliveries_per_channel=30, iti=15.0, switching_every=1, on_time=[0.02, 0.02]): for i in poke_ports: self.board.set_pin_mode(i, self.board.INPUT, self.board.DIGITAL) sleep(2.0) total_deliveries = len(poke_ports) * deliveries_per_channel self.poke_array = [] for i in range(total_deliveries): self.poke_array.append((i / switching_every) % len(poke_ports)) delivery_counter = 0 for i in self.poke_array: sleep(iti) while True: if self.board.digital_read(poke_ports[i]) == 0: start = time() * 1000.0 self.board.digital_write(taste_ports[i], 1) while True: if (time() * 1000.0 - start) >= on_time[i] * 1000.0: self.board.digital_write(taste_ports[i], 0) break print 'Trial ', delivery_counter + 1, ' of ', total_deliveries, ' done' delivery_counter += 1 break print 'All done'
""" This example illustrates manipulating a servo motor. """ import time import sys import signal from PyMata.pymata import PyMata SERVO_MOTOR = 9 # servo attached to this pin # 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
class Motors(Thread): MOTOR_1_PWM = 2 MOTOR_1_A = 3 MOTOR_1_B = 4 MOTOR_2_PWM = 5 MOTOR_2_A = 6 MOTOR_2_B = 7 MOTOR_3_PWM = 8 MOTOR_3_A = 9 MOTOR_3_B = 10 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 def stop_motors(self): self.board.digital_write(self.MOTOR_1_B, 0) self.board.digital_write(self.MOTOR_1_A, 0) self.board.digital_write(self.MOTOR_2_B, 0) self.board.digital_write(self.MOTOR_2_A, 0) self.board.digital_write(self.MOTOR_3_B, 0) self.board.digital_write(self.MOTOR_3_A, 0) def run(self): while True: # Reset all direction pins to avoid damaging H-bridges # TODO: USE dx,dy now in (-1,1)+(None,None) range self.stop_motors() dist = abs(self.dx) if dist > 0.2: #was 2 if self.dx > 0: print("Turning left") self.board.digital_write(self.MOTOR_1_B, 1) self.board.digital_write(self.MOTOR_2_B, 1) self.board.digital_write(self.MOTOR_3_B, 1) else: print("Turning right") self.board.digital_write(self.MOTOR_1_A, 1) self.board.digital_write(self.MOTOR_2_A, 1) self.board.digital_write(self.MOTOR_3_A, 1) self.board.analog_write(self.MOTOR_1_PWM, int(dist**0.7 + 25)) self.board.analog_write(self.MOTOR_2_PWM, int(dist**0.7 + 25)) self.board.analog_write(self.MOTOR_3_PWM, int(dist**0.7 + 25)) # elif self.dy > 30: else: print("Going forward") self.board.digital_write(self.MOTOR_1_B, 1) self.board.digital_write(self.MOTOR_3_A, 1) self.board.analog_write(self.MOTOR_1_PWM, int(self.dy**0.5) + 30) self.board.analog_write(self.MOTOR_2_PWM, 0) self.board.analog_write(self.MOTOR_3_PWM, int(self.dy**0.5) + 30) sleep(0.03)
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 this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import time import sys import signal from PyMata.pymata import PyMata # create a PyMata instance board = PyMata("/dev/ttyACM0", verbose=True) # you may need to press ctrl c twice def signal_handler(sig, frame): print('You pressed Ctrl+C') if board is not None: board.reset() board.close() sys.exit(0) signal.signal(signal.SIGINT, signal_handler) # Configure the trigger and echo pins board.sonar_config(12, 12)
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()
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
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
import time from PyMata.pymata import PyMata addr = 0x48 # Initialize Arduino using port name port = PyMata("/dev/cu.usbmodem621") # Configure I2C pin port.i2c_config(0, port.ANALOG, 4, 5) # one shot read asking peripheral to send 2 bytes port.i2c_read(addr, 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(addr) # 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 firmata.close()
This file demonstrates how to use some of the basic PyMata operations. """ import time import sys import signal from PyMata.pymata import PyMata from pprint import pprint # 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 # 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) board.enable_digital_reporting(BOARD_LED) time.sleep(2)
def __init__(self, port): from PyMata.pymata import PyMata self._port = port self._board = PyMata(self._port, verbose=False)
import time from PyMata.pymata import PyMata board = PyMata("/dev/ttyACM0") # for leonardo board.i2c_config(0, board.DIGITAL, 3, 2) # for uno # board.i2c_config(0, board.ANALOG, 4, 5) while True: try: board.i2c_write( 0x23, board.I2C_READ_CONTINUOUSLY) # same results with board.I2C_READ time.sleep(.2) board.i2c_read( 0x23, 0, 2, board.I2C_READ) # same results with board.I2C_READ_CONTINUOUSLY time.sleep(.3) data = board.i2c_get_read_data(0x23) print('Got read data: %s' % data) lux = (data[1] << 8 | data[2]) >> 4 lux /= 1.2 print(str(lux) + ' lux') except KeyboardInterrupt: board.close()
This example illustrates using callbacks for digital and analog input. Monitor the current analog input and digital input of two pins. """ import signal import sys import time from PyMata.pymata import PyMata # Instantiate PyMata board = PyMata("/dev/ttyACM0", verbose=True) board.encoder_config(7,2) # Set up pin modes for both pins with callbacks for each board.set_pin_mode(5, board.PWM, board.DIGITAL) board.set_pin_mode(6, board.PWM, board.DIGITAL) board.analog_write(5, 255) board.analog_write(6, 0) time.sleep(2) count = board.digital_read(2) print count time.sleep(2) board.analog_write(5, 0)
def __init__(self, port): self._port = port self._board = PyMata(self._port, verbose=False)
def __init__(self, port_id='/dev/ttyACM0', bluetooth=True, verbose=True): # PyMata is an old style class so you can't use super. PyMata.__init__(self, port_id, bluetooth, verbose)
#!/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="******")
class ArduinoBoard: """Representation of an Arduino board.""" def __init__(self, port): """Initialize the board.""" self._port = port self._board = PyMata(self._port, verbose=False) def set_mode(self, pin, direction, mode): """Set 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.INPUT, 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): """Set a given digital pin to high.""" self._board.digital_write(pin, 1) def set_digital_out_low(self, pin): """Set a given digital pin to low.""" self._board.digital_write(pin, 0) def get_digital_in(self, pin): """Get the value from a given digital pin.""" self._board.digital_read(pin) def get_analog_in(self, pin): """Get 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): """Disconnect the board and close the serial connection.""" self._board.reset() self._board.close()
# 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
def __init__(self, port_id='/dev/ttyACM0', bluetooth=True, verbose=True): # PyMata is an old style class so you can't use super. PyMata.__init__(self, port_id, bluetooth, verbose) # Setup handler for response data. # Note that the data length (1) appears to be unused for these sysex # responses. self._command_handler.command_dispatch.update({CP_COMMAND: [self._response_handler, 1]}) # Setup configured callbacks to null. self._accel_callback = None self._tap_callback = None self._temp_callback = None self._cap_callback = None
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 __init__(self): # Initialize fingers and wrist pos self.t_pos = 0 self.i_pos = 0 self.m_pos = 0 self.r_pos = 0 self.l_pos = 0 self.w_pos = 90 # Initialize sensor values self.t_sen = 0 self.i_sen = 0 self.m_sen = 0 self.r_sen = 0 self.l_sen = 0 # Initialize the arduino self.arduino = PyMata("/dev/ttyACM0", verbose=True) # Initialize the servos and sensors on arduino for pin in SERVO_PINS: self.arduino.servo_config(pin) sensor_pin = 0 self.arduino.enable_analog_reporting(sensor_pin) sensor_pin += 1 # Initialize the hand states self.curstate = 'open' self.states = {} self.transitionTable = {}