class ArduinoSerial(object):

	def __init__(self):
		self.NOTHING = 0
		self.OPEN = 1   # clip is open, in transit (fsr low, switch low)
		self.EMPTY = 2   # clip is closed, no paper in (fsr high, switch high)
		self.READY = 3   # clip is closed, paper in place (fsr high, switch low)
		self.UNKNOWN = 4   # initial state 
		self.initSerial()
		#self.ser = None
		
	def initSerial(self):
		# configure the serial connections (the parameters differs on the device you are connecting to)
		portName = Serial.list()[0];
		#try:
  		self.ser = Serial(this, portName, 9600)
  		#except:
  		#	print "ERROR: Arduino Unavailable, Serial object could not be initialized."

	def check(self):
		retVal = self.NOTHING
		#check to see if we have a serial object
		#if self.ser:
		if self.ser.available() > 0:
			out = int(self.ser.read())
			out = out-48
			if out != self.NOTHING:
				retVal = out
		return retVal
示例#2
0
 def _try_to_establish_serial(self):
     try:
         print(Serial.list())
         self._serial = Serial(this, "/dev/tty.usbmodem1412", 9600)  # max rate?
         print("*** established serial connection")
     except Exception as exc:
         print("*** error attempting to connect to Pyboard : %s" %exc)
         self._serial = None
def setup():
    global ducks, NUMDUCKS, numNotHidden, reticule, timer, PLAY_TIME
    global player_tuple, gameOn, timer_started, myPort

    if not MOUSE_INPUT:
        print "Select serial port of accelerometer gun"
        for i, port in enumerate(Serial.list()):
            print "[%d] %s" % (i, port)
        print ">> ",
        whichPort = int(raw_input().strip())
        myPort = Serial(this, Serial.list()[whichPort], 9600)
        myPort.bufferUntil(ord('\n'))

    print "Place NFC tag on reader."
    print "Press [ENTER] to continue..."
    raw_input()
    (status, player_tuple) = get_player()
    if status != 0:
        print "Error getting player."
        exit()
    elif player_tuple == None:
        print "New player!"
        #player_tuple = (0,0,0)
    else:
        print "Player found."
        print "Total: %d; High: %d" % (player_tuple[1], player_tuple[2])

    size(1400, 800)
    timer_started = False  # Hack to get timer to restart on first frame
    timer = Timer(10, 60, PLAY_TIME)
    timer.start()
    for i in range(NUMDUCKS):
        ducks.append(Duck(int(random(150, 1200)), 500))
    # print "DUCKS"
    # for duck in ducks:
    #     print duck
    #     print duck.x
    #     print duck.y
    #     print duck.dx
    #     print duck.dy
    reticule = Reticule(MOUSE_INPUT)
    gameOn = True
 def __init__(self):
     """Initialise the micro:bit, would be good to find it automatically."""
     portName = Serial.list()[len(Serial.list()) - 1]
     port = Serial(this, portName, 115200)
     port.bufferUntil(10)
     self.port = port
     self.state = {'a': False, 'b': False}
     self.data = {
         'name': u'None',
         'accelerometer': PVector(0, 0, -64),
         'button_a': {
             'pressed': False,
             'down': False,
             'up': False
         },
         'button_b': {
             'pressed': False,
             'down': False,
             'up': False
         }
     }
	def initSerial(self):
		# configure the serial connections (the parameters differs on the device you are connecting to)
		portName = Serial.list()[0];
		#try:
  		self.ser = Serial(this, portName, 9600)
示例#6
0
class Comm:

    def __init__(self):
        self._init = False
        self._sent_request = False
        self._controls = []
        self._values = {}
        self._serial = None #  todo: need a close hook

    def service(self, mouse_down, applet):
        if self._init:
            for control in self._controls:
                control.service(mouse_down)
            while self._serial.available() > 0:
                line = self._serial.readStringUntil(10)
                if line is not None:
                    print("> %s" %line.strip())
        else:
            self._try_to_build(applet)

    def _try_to_build(self, applet):
        if self._serial is not None:
            if self._sent_request:

                json_str = self._serial.readStringUntil(10)

                if json_str is not None:
                    try:
                        definitions = json.loads(json_str.decode())
                        self._build_control(definitions, applet)
                        self._init = True
                    except ValueError:
                        print(json_str.strip())
            else:
                print("Requesting definitions")
                self._serial.write("?\n".encode())
                self._sent_request = True
        else:
            self._try_to_establish_serial()

    def _build_control(self, definitions, applet):
        x = 10
        y = 5
        for definition in definitions:
            control = controls.slider_from_dict(definition, x, y, applet, self)
            self._controls.append(control)
            y += controls.height

    def _try_to_establish_serial(self):
        try:
            print(Serial.list())
            self._serial = Serial(this, "/dev/tty.usbmodem1412", 9600)  # max rate?
            print("*** established serial connection")
        except Exception as exc:
            print("*** error attempting to connect to Pyboard : %s" %exc)
            self._serial = None

    def send_value(self, key, value):
        try:
            old = self._values[key]
        except KeyError:
            old = None
        if old != value:
            d = {key: value}
            json_str = json.dumps(d).encode()
            print("sending %s" % json_str)
            self._serial.write(json_str)
            self._serial.write("\n".encode())
        self._values[key] = value

    def send(com, value):
        com.write(json.dumps(value).encode())
        com.write("\n".encode())
        for line in com.readlines():
            if len(line) > 1:
                print("> %s" % line.decode())