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()
class ArduinoBoard(object): """ Represents an Arduino board. """ def __init__(self, port): from PyMata.pymata import PyMata self._port = port self._board = PyMata(self._port, verbose=False) def set_mode(self, pin, direction, mode): """ Sets the mode and the direction of a given pin. """ if mode == 'analog' and direction == 'in': self._board.set_pin_mode(pin, self._board.INPUT, self._board.ANALOG) elif mode == 'analog' and direction == 'out': self._board.set_pin_mode(pin, self._board.OUTPUT, self._board.ANALOG) elif mode == 'digital' and direction == 'in': self._board.set_pin_mode(pin, self._board.OUTPUT, self._board.DIGITAL) elif mode == 'digital' and direction == 'out': self._board.set_pin_mode(pin, self._board.OUTPUT, self._board.DIGITAL) elif mode == 'pwm': self._board.set_pin_mode(pin, self._board.OUTPUT, self._board.PWM) def get_analog_inputs(self): """ Get the values from the pins. """ self._board.capability_query() return self._board.get_analog_response_table() def set_digital_out_high(self, pin): """ Sets a given digital pin to high. """ self._board.digital_write(pin, 1) def set_digital_out_low(self, pin): """ Sets a given digital pin to low. """ self._board.digital_write(pin, 0) def get_digital_in(self, pin): """ Gets the value from a given digital pin. """ self._board.digital_read(pin) def get_analog_in(self, pin): """ Gets the value from a given analog pin. """ self._board.analog_read(pin) def get_firmata(self): """ Return the version of the Firmata firmware. """ return self._board.get_firmata_version() def disconnect(self): """ Disconnects the board and closes the serial connection. """ self._board.reset() self._board.close()
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()
class ArduinoFirmata(Board, AnalogInputCapable, PwmOutputCapable): 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']] ) def cleanup(self): # self.firmata_client.close() has sys.exit(0) if hasattr(self, 'PyMata'): try: self.firmata_client.transport.close() except AttributeError: pass def __repr__(self): cls_name = self.__class__.__name__ return '<{cls_name} {self.port!r}>'.format(**locals()) def _set_digital_mode(self, pin, mode): self.firmata_client.set_pin_mode( pin.location, PIN_MODES[mode], self.firmata_client.DIGITAL ) def _set_analog_mode(self, pin, mode): pin_id = int(pin.location[1:]) self.firmata_client.set_pin_mode( pin_id, self.firmata_client.INPUT, self.firmata_client.ANALOG ) def _set_pwm_mode(self, pin, mode): pin_id = int(pin.location) self.firmata_client.set_pin_mode( pin_id, self.firmata_client.PWM, self.firmata_client.DIGITAL ) def _get_pin_state(self, pin): _state = self.firmata_client.digital_read(pin.location) if _state == self.firmata_client.HIGH: return pingo.HIGH return pingo.LOW def _set_pin_state(self, pin, state): self.firmata_client.digital_write( pin.location, PIN_STATES[state] ) def _get_pin_value(self, pin): pin_id = int(pin.location[1:]) return self.firmata_client.analog_read(pin_id) def _set_pwm_duty_cycle(self, pin, value): pin_id = int(pin.location) firmata_value = int(value * 255) return self.firmata_client.analog_write(pin_id, firmata_value) def _set_pwm_frequency(self, pin, value): raise NotImplementedError
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) board.set_pin_mode(POTENTIOMETER, board.INPUT, board.ANALOG) board.set_analog_latch(POTENTIOMETER, board.ANALOG_LATCH_GTE, 1000) # do nothing loop - program exits when latch data event occurs for potentiometer while 1: count += 1 if count == 300: print('bye bye') board.close() analog = board.analog_read(POTENTIOMETER) board.analog_write(RED_LED, analog // 4) digital = board.digital_read(PUSH_BUTTON) board.digital_write(GREEN_LED, digital) latch = board.get_analog_latch_data(POTENTIOMETER) if latch[1] == board.LATCH_LATCHED: board.analog_write(RED_LED, 0) board.digital_write(GREEN_LED, 0) print('Latching Event Occurred at: ' + time.asctime(time.gmtime(latch[3]))) board.close() sys.exit(0)
from PyMata.pymata import PyMata from time import sleep # Define channels to be used tastes = [2, 3] # Enter DIO board port numbers # How long to leave valves open (seconds) duration = 20 board = PyMata('/dev/ttyACM0') # USB port identifier # Board is a generic variable name and must be changed everywhere in the code if changed here. for i in tastes: board.digital_write(tastes[i],1) sleep(duration) for i in tastes: board.digital_write(tastes[i],0) print 'The purge is complete. This was the most sucessful purge yet!'
class Mqtt_Pymata: 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 turn_on(self): self._state = True self.apply_state() self.report_state() def turn_off(self): self._state = False self.apply_state() self.report_state() def apply_state(self): self._board.digital_write(self._switch_pin,self._board.HIGH if self._state else self._board.LOW) def report_state(self): self._mqtt.publish( self._state_topic, self._payload_on if self._state else self._payload_off, self._qos, self._retain)
# 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 time.sleep( 1.0 ); # wait for a second except KeyboardInterrupt: # Catch exception raised by using Ctrl+C to quit pass # close the interface down cleanly firmata.close()
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)
@description: Blink Arduino mediante Firmata @url: http://www.aprendiendoarduino.com/ ''' import time import sys from PyMata.pymata import PyMata BOARD_LED = 13 port = input("Puerto Serie Arduino: ") try: arduino = PyMata(port, verbose=True) for x in range(10): print(x + 1) # Set the output to 1 = High arduino.digital_write(BOARD_LED, 1) # Wait a half second between toggles. time.sleep(.5) # Set the output to 0 = Low arduino.digital_write(BOARD_LED, 0) time.sleep(.5) # Close PyMata when we are done arduino.close() except: # catch *all* exceptions e = sys.exc_info()[0] print("Puerto no válido. %s" % e)
class Firmata(Adaptor): def __init__(self, options): super(Firmata, self).__init__(options) if 'port' not in options: raise self.ParameterRequired( 'A port must be specified for Firmata connection.' ) self.port = options.get('port') self.board = PyMata('/dev/ttyACM0', verbose=True) signal.signal(signal.SIGINT, self.signal_handler) self.pins = { 'digital': [], 'analog': [], 'pwm': [], 'servo': [], 'i2c': [], } def analog_write(self, pin_number, value): if pin_number not in self.pins['analog']: self.pins['analog'].append(pin_number) self.board.set_pin_mode( pin_number, self.board.OUTPUT, self.board.ANALOG ) self.board.analog_write(pin_number, value) def analog_read(self, pin_number): if pin_number not in self.pins['analog']: self.pins['analog'].append(pin_number) self.board.set_pin_mode( pin_number, self.board.INPUT, self.board.ANALOG ) return self.board.analog_read(pin_number) def digital_write(self, pin_number, value): if pin_number not in self.pins['digital']: self.pins['digital'].append(pin_number) self.board.set_pin_mode( pin_number, self.board.OUTPUT, self.board.DIGITAL ) self.board.digital_write(pin_number, value) def digital_read(self, pin_number): if pin_number not in self.pins['digital']: self.pins['digital'].append(pin_number) self.board.set_pin_mode( pin_number, self.board.INPUT, self.board.DIGITAL ) return self.board.analog_write(pin_number) def pwm_write(self, pin_number, value): if pin_number not in self.pins['pwm']: self.pins['pwm'].append(pin_number) self.board.set_pin_mode( pin_number, self.board.PWM, self.board.DIGITAL ) return self.board.analog_write(pin_number, value) def pwm_read(self, pin_number): if pin_number not in self.pins['pwm']: self.pins['pwm'].append(pin_number) self.board.set_pin_mode( pin_number, self.board.PWM, self.board.DIGITAL ) return self.board.analog_read(pin_number) def servo_write(self, pin_number, value): if pin_number not in self.pins['servo']: self.pins['servo'].append(pin_number) self.board.servo_config(pin_number) self.board.analog_write(pin_number, value) def disconnect(self): # Close the firmata interface down cleanly self.board.close() def signal_handler(self, sig, frame): print('Ctrl+C pressed') if self.board is not None: self.board.reset() sys.exit(0) class ParameterRequired(Exception): def __init__(self, message='A required parameter was not provided.'): super(Firmata.ParameterRequired, self).__init__(message) def __str__(self): return self.message
# 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) firmata.digital_write(RED_LED, 0) # Set the white led for pwm operation firmata.set_pin_mode(WHITE_LED, firmata.PWM, firmata.DIGITAL) # Set the white led to full brightness (255) for 1 second firmata.analog_write(WHITE_LED, 255) time.sleep(1) # now set it to half brightness for 1 second firmata.analog_write(WHITE_LED, 128) time.sleep(1)
# create a PyMata instance firmata = PyMata("/dev/ttyACM0") def signal_handler(sig, frame): print('You pressed Ctrl+C!!!!') if firmata is not None: firmata.reset() sys.exit(0) signal.signal(signal.SIGINT, signal_handler) # set digital pin 13 to be an output port firmata.set_pin_mode(BOARD_LED, firmata.OUTPUT, firmata.DIGITAL) time.sleep(5) print("Blinking LED on pin 13") # blink for 10 times for x in range(10): print(x + 1) firmata.digital_write(BOARD_LED, 1) # wait a half second between toggles. time.sleep(.5) firmata.digital_write(BOARD_LED, 0) time.sleep(.5) # close PyMata when we are done firmata.close()
firmata.set_pin_mode(52,firmata.OUTPUT,firmata.DIGITAL) firmata.set_pin_mode(53,firmata.OUTPUT,firmata.DIGITAL) # configure 4 pins for 4 SONAR modules firmata.sonar_config(6,6) time.sleep(.1) firmata.sonar_config(7,7) time.sleep(.1) firmata.sonar_config(37,37) time.sleep(.1) firmata.sonar_config(39,39) time.sleep(1) # create a forever loop that will sequentially turn on all LEDS, # then print out the sonar data for the 4 PING devices # then sequentially turns off all LEDS and print PING data again print firmata.get_digital_response_table() while 1: for i in range(46,54): time.sleep(.1) firmata.digital_write(i, 1) print firmata.get_sonar_data() for i in range(46,54): time.sleep(.1) firmata.digital_write(i, 0) print firmata.get_sonar_data()
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'
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) print("Blinking LED on pin 13 for 10 times ...") # Blink for 10 times for x in range(10): print(x + 1) # Set the output to 1 = High board.digital_write(BOARD_LED, 1) # Wait a half second between toggles. time.sleep(.5) # Set the output to 0 = Low board.digital_write(BOARD_LED, 0) time.sleep(.5) # Close PyMata when we are done board.close()
control = vessel.control sas = conn.add_stream(getattr, control, "sas") gear = conn.add_stream(getattr, control, "gear") lights = conn.add_stream(getattr, control, "lights") brakes = conn.add_stream(getattr, control, "brakes") # Your Application Continues Below This Point print "We are go!" while 1 : s = speed() if s > 400: s = 400 board.analog_write(SPEEDOMETER, int(s * 255 / 400)) f = 0 mf = maxFuel() if mf > 0 : f = fuel() / mf board.analog_write(FUELGAUGE, int(f * 255)) g = math.fabs(gforce()) / 40 if g > 1: g = 1 board.analog_write(GFORCEMETER, int(g * 255)) board.digital_write(SASLAMP, sas()) board.digital_write(GEARLAMP, gear()) board.digital_write(LAMPLAMP, lights()) board.digital_write(BRAKELAMP, brakes()) time.sleep(0.05)
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)
tasteduration1 = 2 # Time valve should be open in seconds tasteduration2 = 2 iti = 5 # Set ITI # Set mode on input channels and clear outputs board.set_pin_mode(pokeport1, board.INPUT, board.DIGITAL) board.set_pin_mode(pokeport2, board.INPUT, board.DIGITAL) #board.digital_write(tasteport1, 0) #board.digital_write(tasteport2, 0) trial = 1 while trial < trials: if board.digital_read(pokeport1) == 1: board.digital_write(tasteport1, 1) sleep(tasteduration1) board.digital_write(tasteport1, 0) print 'Completed trial number', trial sleep(iti) trial = trial+1 elif board.digital_read(pokeport2) == 1: board.digital_write(tasteport2, 1) sleep(tasteduration2) board.digital_write(tasteport2, 0) print 'Completed trial number', trial sleep(iti) trial = trial+1 print('It\'s all ogre now') # Shrek is love, shrek is life