class usb_vcp_tmcl_interface(tmcl_module_interface, tmcl_host_interface): def __init__(self, port=0, data_rate=None, host_id=2, module_id=1, debug=False): del data_rate tmcl_module_interface.__init__(self, host_id, module_id, debug) tmcl_host_interface.__init__(self, host_id, module_id, debug) self.__vcp = USB_VCP(port) self.__vcp.init() self.__vcp.setinterrupt(-1) def __enter__(self): return self def __exit__(self, exitType, value, traceback): del exitType, value, traceback self.close() def close(self): self.__vcp.setinterrupt(3) self.__vcp.close() return 0 def data_available(self, hostID, moduleID): del hostID, moduleID return self.__vcp.any() def _send(self, hostID, moduleID, data): del hostID, moduleID self.__vcp.write(data) def _recv(self, hostID, moduleID): del hostID, moduleID read = bytearray(0) while(len(read) < 9): read += self.__vcp.read(9) if(not(read)): read = bytearray(0) return read def printInfo(self): pass def enableDebug(self, enable): self._debug = enable @staticmethod def supportsTMCL(): return True @staticmethod def supportsCANopen(): return False @staticmethod def available_ports(): return set([0])
class USB_Port: def __init__(self): self.usb_serial = USB_VCP() self.recv_buf = bytearray(1) # Disable Control-C on the USB serial port in case one comes in the # data. self.usb_serial.setinterrupt(-1) def read_byte(self): """Reads a byte from the usb serial device.""" if self.usb_serial.any(): bytes_read = self.usb_serial.recv(self.recv_buf) if bytes_read > 0: return self.recv_buf[0] def write(self, data): """Writes an entire packet to the serial port.""" self.usb_serial.write(data)
class USB_Port: """Implements a port which can be used to receive bioloid device commands from a host. """ def __init__(self): self.usb_serial = USB_VCP() self.baud = 0 self.recv_buf = bytearray(1) # Disable Control-C on the USB serail port in case one comes in the # data. self.usb_serial.setinterrupt(-1) def any(self): """Returns a truthy value if characters are available to be read.""" return self.usb_serial.any() def read_byte(self): """Reads a byte from the usb serial device. This function will return None if no character was read within the designated timeout. The max Return Delay time is 254 x 2 usec = 508 usec (the default is 500 usec). This represents the minimum time between receiving a packet and sending a response. """ bytes_read = self.usb_serial.recv(self.recv_buf, timeout=2) if bytes_read > 0: return self.recv_buf[0] def set_baud(self, baud): """Sets the baud rate. Note that for USB Serial, this is essentially a no-op. We store the baud rate that was set, so that """ self.baud = baud def write_packet(self, packet_data): """Writes an entire packet to the serial port.""" self.usb_serial.write(packet_data)
class CoroCLI(): def __init__(self, role): self.role = role self.console = USB_VCP() self.command_dispatch = { } self.cmd_hist = [b''] self.prompt = bytes(self.role + '> ', 'ASCII') self.tx_want_ack = True self.destination = bytes(8) @coroutine def readline(self): console = self.console hi = 0 buf = b'' while console.isconnected(): if console.any(): c = console.read(1) if c == b'\x04': raise GotEOT elif c == b'\x0e': # ^N buf = self.cmd_hist[hi][:] hi = max(hi-1, 0) console.write(b'\r' + self.prompt + buf + b'\x1b[K') elif c == b'\x10': # ^P buf = self.cmd_hist[hi][:] hi = min(hi+1, len(self.cmd_hist)-1) console.write(b'\r' + self.prompt + buf + b'\x1b[K') elif c == b'\x7f' or c == b'\x08': if buf: console.write(b'\x08 \x08') buf = buf[:-1] elif c == b'\r' or c == b'\n': if buf and buf != self.cmd_hist[0]: self.cmd_hist.insert(0, buf) if len(self.cmd_hist) > 16: self.cmd_hist.pop() hi = 0 console.write(b'\r\n') return buf else: buf += c console.write(c) else: yield from sleep(50) @coroutine def write(self, buf): self.console.write(buf) yield @coroutine def writeln(self, buf): yield from self.write(buf) yield from self.write(b'\r\n') @coroutine def interpret(self, line): if not line: return cmd, _, rol = line.lstrip().partition(b' ') cmd = str(cmd, 'ASCII') rol = rol.lstrip() fun = self.command_dispatch.get(cmd.lower()) if fun: yield from fun(self, cmd, rol) elif cmd in ('help', '?'): yield from self.write('Commands are: ') yield from self.writeln(', '.join(sorted(self.command_dispatch.keys()))) else: yield from self.writeln('huh?') @coroutine def repl(self, noquit=False): console = self.console while(console.isconnected()): #console.self.write(prompt) yield from self.write(self.prompt) try: line = yield from self.readline() yield from self.interpret(line) except GotEOT: if noquit: yield from self.writeln("can't quit!") else: return
pwmGain = pyb.Pin('X1') pwmSlew = pyb.Pin('X2') pwmBias = pyb.Pin('X3') tim2 = pyb.Timer(2, freq=10000) tim5 = pyb.Timer(5, freq=1000000) pwmBiasCh = tim5.channel(3, pyb.Timer.PWM, pin=pwmBias) pwmGainCh = tim5.channel(1, pyb.Timer.PWM, pin=pwmGain) pwmBiasCh.pulse_width_percent(50) pwmSlewCh = tim2.channel(2, pyb.Timer.PWM, pin=pwmSlew) amplitude, Stop = 999, True frequency = 10000 duty = 10 while Stop: cmd = usb.recv(4, timeout=5000) usb.write(cmd) if (cmd == b'strt'): pyb.LED(1).on() pyb.LED(2).off() pyb.LED(3).off() utime.sleep(1) tim2 = pyb.Timer(2, freq=10000) pwmSlewCh.pulse_width_percent(duty) elif (cmd == b'ampl'): data1 = bytes(8) cmd = usb.recv(4, timeout=5000) data1 = ustruct.unpack('L', cmd) dataList1 = list(data1) dataStr1 = [str(i) for i in dataList1] percent = int("".join(dataStr1)) usb.write(ustruct.pack('L', percent))
led.on() # Write out a sinusoidal curve to channel X5, which is wired via a # female-female jumper to X2 # -- # create a buffer containing a sine-wave, using half-word samples buf = array( 'H', 2048 + int(2047 * math.sin(2 * math.pi * i / 128)) for i in range(128)) dac = DAC(1, bits=12) # Wired to X5 dac.write_timed(buf, 400 * len(buf), mode=DAC.CIRCULAR) # Instatiate the USB serial object u = USB_VCP() u.write('Hello world!!') # Enter into an infinite loop while True: # Get a line from the serial connection line = u.readline() # If there is nothing, line will be None if not line is None and line: # What you got is a byte object, convert from bytes (binary data) to python string line = line.decode('ascii') # Split the string at the delimiter, creating a 3-element list els = line.strip().split(',')
import time from pyb import (USB_VCP, Servo) SLEEP = 0.1 UP = -90 DOWN = 0 SPEED = 1000 servo = Servo(1) servo.angle(30) p = USB_VCP() while True: if p.any(): command = p.readline().strip() if command == b'up': servo.angle(UP, SPEED) p.write(b'up-ok\n') elif command == b'down': servo.angle(DOWN, SPEED) p.write(b'down-ok\n') else: p.write(command + b'\n') p.write(b'err\n') time.sleep(SLEEP)
#timeprint(3) x = int((largeblob.y() - xbottom) * (scalex)) z = int(largeblob.pixels() * scalez) if (x < 0): x = 0 if (y < 0): y = 0 if (x > 127): x = 127 if (y > 127): y = 127 usb.write(chr(x)) usb.write(chr(y)) usb.write(chr(z)) usb.write("\r") #print(y) if mode == 0 or mode == 1: color = x bright = y else: if y < 64: bright = (y) + 15 else: bright = (127 - y) + 15
def Log(Watt, ch): p = USB_VCP() v = Watt.Volts(ch) s = '%5.4f' % v p.write(s)
# USB serial example. # # WARNING: # This script should NOT be run from the IDE or command line, it should be saved as main.py # Note the following commented script shows how to receive the image from the host side. import sensor, image, time, ustruct from pyb import USB_VCP, LED usb = USB_VCP() led = LED(1) sensor.reset() # Reset and initialize the sensor. sensor.set_pixformat(sensor.RGB565) # Set pixel format to RGB565 (or GRAYSCALE) sensor.set_framesize(sensor.QVGA) # Set frame size to QVGA (320x240) sensor.skip_frames(time = 2000) # Wait for settings take effect. usb.setinterrupt(3) # input while(True): cmd = usb.recv(1, timeout=5000) if (cmd == b'\x01'): led.toggle() for item in range(65, 91): usb.write(ustruct.pack('<b', item)) else: continue