示例#1
0
 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)
示例#2
0
def pye(*args, tab_size=4, undo=50):
    from pyb import USB_VCP
    USB_VCP().setinterrupt(-1)
    io_device = IO_DEVICE()
    ret = pye_edit(*args, tab_size=tab_size, undo=undo, io_device=io_device)
    io_device.deinit_tty()
    USB_VCP().setinterrupt(3)
    return ret
    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)
示例#4
0
 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)
示例#5
0
def run_usb_vcp_test():
    serial_port = USB_VCP()
    nmea_line = None
    #serial_port.setinterrupt(-1)

    while True:
        # retrieving data
        if serial_port.any():
            nmea_line = str(serial_port.readline(), 'utf-8')

        if nmea_line:
            delay(1)
            nmea_line = None

        delay(50)
示例#6
0
 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)
示例#7
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)
示例#8
0
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)
示例#9
0
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)
示例#10
0
from pyb import LED, ADC, USB_VCP, Pin
from pyb import millis, elapsed_millis, delay, Timer
from pyb import hard_reset
from array import array

# User Variables
pin_strings = ('X1', 'X2', 'X3', 'X4', 'X5', 'X6', 'X7', 'X8', 'Y11', 'Y12',
               'X19', 'X20', 'X21', 'X22', 'X11', 'X12')
# Objects
usb = USB_VCP()
indicator_light = LED(4)
# Finals
inf = 10**100


# Classes
class VCP(USB_VCP):
    def __init__(self):
        super().__init__()

    def read_timeout(self, timeout=5000):
        start_time = millis()
        while elapsed_millis(start_time) < timeout:
            data = self.read()
            if data:
                return data.decode()

    def write_encode(self, data):
        self.write(bytearray(str(data).encode()))

    def verify_write(self, data, timeout=500):
示例#11
0
文件: usb_vcp.py 项目: openmv/openmv
# #!/usr/bin/env python2.7
# import sys, serial, struct
# port = '/dev/ttyACM0'
# sp = serial.Serial(port, baudrate=115200, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE,
#             xonxoff=False, rtscts=False, stopbits=serial.STOPBITS_ONE, timeout=None, dsrdtr=True)
# sp.setDTR(True) # dsrdtr is ignored on Windows.
# sp.write("snap")
# sp.flush()
# size = struct.unpack('<L', sp.read(4))[0]
# img = sp.read(size)
# sp.close()
# 
# with open("img.jpg", "w") as f:
#     f.write(img)

import sensor, image, time, ustruct
from pyb import USB_VCP

usb = USB_VCP()
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.

while(True):
    cmd = usb.recv(4, timeout=5000)
    if (cmd == b'snap'):
        img = sensor.snapshot().compress()
        usb.send(ustruct.pack("<L", img.size()))
        usb.send(img)
示例#12
0
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)
示例#13
0
'''
串口通信
'''
import sensor, image, time, ustruct
from pyb import USB_VCP

usb = USB_VCP()
sensor.reset()  # 复位并初始化感光元件。
sensor.set_pixformat(sensor.RGB565)  # 设置像素格式为RGB565(或GRAYSCALE)
sensor.set_framesize(sensor.QVGA)  # 将图像大小设置为QVGA (320x240)
sensor.skip_frames(time=2000)  # 等待设置生效。

while (True):
    test = 'hi\r\n'
    usb.send(test)
    time.sleep(1000)
示例#14
0
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
示例#15
0
class DataTX():
    img_width = 320
    img_height = 240
    sent = False
    buff = None


dataTX = DataTX()
dataRX = DataTX()
dataTX.buff = sensor.alloc_extra_fb(DataTX.img_width, DataTX.img_height,
                                    sensor.RGB565)
dataRX.buff = sensor.alloc_extra_fb(DataTX.img_width, DataTX.img_height,
                                    sensor.RGB565)

usb = USB_VCP()

blue_led.on()
spi_error = False

debug_image = False

control = CameraSlaveControl()
control.column_offset = 10
control.row_offset = 10
control.column_zoom_numerator = 22
control.column_zoom_denominator = 20
control.row_zoom_numerator = 22
control.row_zoom_denominator = 20

while (True):
示例#16
0
 def __init__(self):
     self.vs = USB_VCP()
     self.direction = 0
     self.speed = 0
     self.select_dir = 0
     self.select_speed = 0
示例#17
0
import utime, ustruct, pyb
import math
from array import array
from pyb import USB_VCP

usb = USB_VCP()
usb.setinterrupt(-1)
dac1 = pyb.DAC(pyb.Pin('X5'), bits=12)
dac2 = pyb.DAC(pyb.Pin('X6'), bits=12)
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)
示例#18
0
# sp.close()
#
# with open('img.jpg', 'w') as f:
#     f.write(img)
import sensor, image, time, ustruct
from pyb import USB_VCP
from pyb import LED

red_led = LED(1)
green_led = LED(2)
blue_led = LED(3)
ir_led = LED(4)

#usb.send('Camera initialization...')
blue_led.on()
usb = USB_VCP()
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
clock = time.clock()  # Create a clock object to track the FPS.

# sensor.set_gainceiling(16)
blue_led.off()
usb.send('Done')

contrast = 0
brightness = 0
saturation = 0
vertical_flip = False
示例#19
0
import sensor, image, time

from pyb import UART
from pyb import USB_VCP


def timeprint(num):
    if (1):  # set to determine if times should be printed
        print(str(num) + ":" + str(clock.avg()))
        clock.reset()
        clock.tick()


usb = USB_VCP()

uart = UART(3, 9600)  # init with given baudrate
uart.init(9600, bits=8, parity=None, stop=1)  # init with given parameters

sensor.reset()  # Reset and initialize the sensor.
sensor.set_pixformat(
    sensor.GRAYSCALE)  # Set pixel format to RGB565 (or GRAYSCALE)
sensor.set_framesize(sensor.QQVGA)  # Set frame size to QVGA (320x240)

sensor.set_auto_exposure(0, value=1)

sensor.skip_frames(time=2000)  # Wait for settings take effect.

bg = sensor.snapshot()  # get background first from short exposure
bg = bg.copy()

sensor.set_auto_exposure(0, value=100)
示例#20
0
from pyb import USB_VCP

u = USB_VCP()

while True:
    data = u.recv(1)
    ch = data[0]
    if ch < ord(' ') or ch > ord('~'):
        ch = '.'
    print("Rcvd: 0x%x '%c'" % (data[0], ch))

示例#21
0
def Log(Watt, ch):
	p = USB_VCP()
	v = Watt.Volts(ch)
	s = '%5.4f' % v
	p.write(s)
示例#22
0
        else:
            return 0
while(True):
    clock.tick()
    img = sensor.snapshot()
    numb = 0
    rateOfBlue = 0
    rateOfRed = 0
    rateOfGreen = 0
    #查看图片中是否存在该种颜色(占图片中颜色5%)
    calculateRateOfColor(img,hsv_low_red,hsv_high_red,rateOfRed)
    calculateRateOfColor(img,hsv_low_green,hsv_high_green,rateOfGreen)
    calculateRateOfColor(img,hsv_low_blue,hsv_high_blue,rateOfBlue)
    #numb 值为1 所需颜色出现在图片中线  为0不在中线
    if rateOfRed > 0.05:
        numb = calculateRange(img,img,hsv_low_red,hsv_high_red)
    elif rateOfBlue > 0.05:
        numb = calculateRange(img,img,hsv_low_blue,hsv_high_blue)
    elif rateOfGreen > 0.05:
        numb = calculateRange(img,img,hsv_low_green,hsv_high_green)
    else:
        numb = 0
    #图片中有颜色返回True 无该颜色返回False
    if numb == 1:
        USB_VCP.send(True)
    else:
        USB_VCP.send(False)


    print(clock.fps())
示例#23
0
class Controller(object):
    def __init__(self):
        self.vs = USB_VCP()
        self.direction = 0
        self.speed = 0
        self.select_dir = 0
        self.select_speed = 0
        #self.vs.setinterrupt(-1)

    def dir_menu(self):
        print('please input your instructions')
        print('1. set the direction ')
        print('2. set the speed ')
        print('3. send the instruction ')

    def get_instrcution(self):
        print('please input your instructions ')
        print('1. set the direction ')
        print('2. set the speed ')
        print('3. send the instruction ')
        while True:
            if self.vs.any():
                pyb.delay(2000)
                self.instrcution = self.vs.readline()
                if (self.select_dir == 1):
                    if (self.instrcution == b'1'):
                        self.select_dir = 0
                        print('forward')
                        self.dir_menu()
                    elif (self.instrcution == b'2'):
                        self.select_dir = 0
                        print('back')
                        self.dir_menu()
                    elif (self.instrcution == b'3'):
                        self.select_dir = 0
                        print('leftforward')
                        self.dir_menu()
                    elif (self.instrcution == b'4'):
                        self.select_dir = 0
                        print('leftback')
                        self.dir_menu()
                    elif (self.instrcution == b'5'):
                        self.select_dir = 0
                        print('rightforward')
                        self.dir_menu()
                    elif (self.instrcution == b'6'):
                        self.select_dir = 0
                        print('rightback')
                        self.dir_menu()
                    elif (self.instrcution == b'7'):
                        self.select_dir = 0
                        print('stop')
                        self.dir_menu()
                    elif (self.instrcution == b'8'):
                        self.select_dir = 0
                        print('MotorA-F')
                        self.dir_menu()
                    elif (self.instrcution == b'9'):
                        self.select_dir = 0
                        print('MotorA-R')
                        self.dir_menu()
                    elif (self.instrcution == b'10'):
                        self.select_dir = 0
                        print('MotorB-F')
                        self.dir_menu()
                    elif (self.instrcution == b'11'):
                        self.select_dir = 0
                        print('MotorB-R')
                        self.dir_menu()
                    elif (self.instrcution == b'12'):
                        self.select_dir = 0
                        print('RUN')
                        self.dir_menu()
                    else:
                        print('please set the diretion')
                elif (self.select_speed == 1):
                    self.select_speed == 0
                    print('speed is ', int(self.instrcution))
                    print('please input your instructions')
                    print('1. set the direction ')
                    print('2. set the speed ')
                    print('3. send the instruction ')
                elif (self.instrcution == b'1'):
                    self.select_dir = 1
                    print('please set the diretion ')
                    print('1. forward')
                    print('2. back')
                    print('3. leftforward')
                    print('4. leftback')
                    print('5. rightforward')
                    print('6. rightback')
                    print('7. stop')
                    print('8. MotorA-F')
                    print('9. MotorA-R')
                    print('10.MotorB-F')
                    print('11.MotorB-R')
                    print('12.RUN')
                elif (self.instrcution == b'2'):
                    self.select_speed = 1
                    print('set the speed ')
                elif (self.instrcution == b'3'):
                    print('send the instruction ')
                else:
                    print('test', self.instrcution)
                    print('please input your instructions')
                    print('1. set the direction ')
                    print('2. set the speed ')
                    print('3. send the instruction ')
示例#24
0
#

# Single Color RGB565 Blob Tracking Example
#BALL SLURPER
# This example shows off single color RGB565 tracking using the OpenMV Cam.

import sensor, image, time, math, ustruct, pyb
from pyb import USB_VCP, Pin

DBG = True

usb = USB_VCP()
pin = Pin('P0', Pin.OUT_OD)

# Color Tracking Thresholds (L Min, L Max, A Min, A Max, B Min, B Max)
# The below thresholds track in general red/green/blue things. You may wish to tune them...

sensor.reset()

sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time=2000)
sensor.set_auto_exposure(False, 5000)
sensor.set_auto_gain(False, 0, 0)  # must be turned off for color tracking
sensor.set_auto_whitebal(False, (0, 0, 0))
clock = time.clock()


# Only blobs that with more pixels than "pixel_threshold" and more area than "area_threshold" are
# returned by "find_blobs" below. Change "pixels_threshold" and "area_threshold" if you change the
示例#25
0
# Turn on the light so you know something is happening
led = LED(4)
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')
示例#26
0
class usb_vcp_tmcl_interface(tmcl_interface, tmcl_host_interface):
    def __init__(self,
                 port=0,
                 data_rate=None,
                 host_id=2,
                 module_id=1,
                 debug=False):
        del data_rate
        tmcl_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])
示例#27
0
sensor.skip_frames(time=2000)
sensor.set_auto_gain(False)  # must be turned off for color tracking
sensor.set_auto_whitebal(False)  # must be turned off for color tracking
clock = time.clock()

#If you lose the crazyflie at high altitude, increase this number
#0.015 is a good value for infrared. Set to 1 to see background and pickup ceiling lights
EXPOSURE_TIME_SCALE = 0.04
current_exposure_time_in_microseconds = sensor.get_exposure_us()

sensor.set_auto_exposure(False, \
    exposure_us = int(current_exposure_time_in_microseconds * EXPOSURE_TIME_SCALE))

clock = time.clock()  # Tracks FPS.

usb = USB_VCP()

#Send standby code (904) until RasPi gives the go ahead
#comment out this while loop to start the camera spamming coords by default

while (False):
    red_led.off()
    green_led.on()
    blue_led.on()
    ir_led.off()
    print('{904$904}')
    cmd = usb.recv(5, timeout=100)
    if (cmd == b'start'):
        cmd = "0"
        break
示例#28
0
blue_led = LED(3)
green_led = LED(2)
sensor.reset()
sensor.set_pixformat(sensor.GRAYSCALE)
sensor.set_framesize(sensor.VGA)
sensor.set_windowing((640, 80))
sensor.skip_frames(30)
sensor.set_auto_gain(True)
sensor.set_auto_whitebal(True)
sensor.set_auto_exposure(True)
sensor.set_vflip(True)
sensor.set_hmirror(True)
clock = time.clock()
temp = ''
result = ''
usb = USB_VCP()


def barcode_name(code):
    if (code.type() == image.EAN2):
        return "EAN2"
    if (code.type() == image.EAN5):
        return "EAN5"
    if (code.type() == image.EAN8):
        return "EAN8"
    if (code.type() == image.UPCE):
        return "UPCE"
    if (code.type() == image.ISBN10):
        return "ISBN10"
    if (code.type() == image.UPCA):
        return "UPCA"
示例#29
0
    make_dir("/" + rec_date + "/" + rec_hour)
    make_dir("/" + rec_date + "/" + rec_hour + "/" + rec_min)
    filename = "/" + rec_date + "/" + rec_hour + "/" + rec_min + "/" + timestamp(
        datetime)
    filename = filename + "_capture" + ext
    print(filename)
    return filename


# micropython does not have decode, this is a hack
def decode(binary_string):
    return "".join([chr(char) for char in binary_string])


rtc = pyb.RTC()
usb = USB_VCP()

# Blink blue at start
blink(3)
pyb.delay(500)
blink(3)

# Get time from raspberry

while (True):
    pyb.LED(1).on()
    data = usb.read()
    if data != None:
        if len(data) >= 4:
            # we want to check that starts with date and last element is ")"
            if data[:4] == b'date':
示例#30
0
def main():
    # usb object
    usb = USB_VCP()
    i = 0
    j = 0
    emailNum = 0
    while (True):
        clock.tick()
        img = sensor.snapshot(pixformat=sensor.GRAYSCALE)
        blobs = img.find_blobs(threshold_list,
                               pixels_threshold=0,
                               area_threshold=0,
                               merge=True)
        cmd = usb.recv(4, timeout=1)

        if (cmd == b'snap'):
            i = 0
            emailNum = 0

        if (i == 0):
            usb.send(244)

        if (blobs):
            i = 1
            if (i == 1):
                fire_blob = max(blobs, key=lambda x: x.density())
                img.draw_rectangle(fire_blob.rect())
                img.draw_cross(fire_blob.cx(), fire_blob.cy())

                # For pan control
                xPos = fire_blob.cx()
                xErr = 20 - xPos

                # For tilt control
                yPos = fire_blob.cy()
                yErr = 15 - yPos

                #img.draw_string(fire_blob.x(), fire_blob.y() - 10, "Pan Error: %.2f pixels" % xPosErr, mono_space=False)
                usb.send(xPos)
                usb.send(yPos)

                if ((xErr <= 1 and xErr >= -1) and (yErr <= 1 and yErr >= -1)
                        and emailNum == 0):
                    bigPic()  # Convert to better resolution for email photo
                    img2 = sensor.snapshot(pixformat=sensor.GRAYSCALE)
                    blobs = img2.find_blobs(threshold_list,
                                            pixels_threshold=0,
                                            area_threshold=0,
                                            merge=True)
                    fire_blob = max(blobs, key=lambda x: x.density())
                    img2.draw_rectangle(fire_blob.rect())
                    img2.draw_cross(fire_blob.cx(), fire_blob.cy())
                    img2.to_rainbow(
                        color_palette=sensor.PALETTE_IRONBOW)  # color it

                    imgUSB = img2.compress()
                    usb.send(ustruct.pack("<L", imgUSB.size()))
                    usb.send(imgUSB)
                    emailNum = 1
                    smallPic()  # Convert back to low-res imaging for control
示例#31
0
try:
    from pyb import DAC
    from pyb import LED
    from pyb import Pin
    from pyb import USB_VCP

    sensitivity, maxn, minn = .5, 255, 0

    com = USB_VCP()
    light = DAC(2)
    y1, y2, y3 = Pin('Y1', Pin.IN), Pin('Y2', Pin.IN), Pin('Y3', Pin.IN)
    intensity, oldStr = maxn, str(y1.value()) + str(y2.value())

    directTab = {
        '1000': 1,
        '0001': 1,
        '0111': 1,
        '1110': 1,
        '1011': -1,
        '1101': -1,
        '0100': -1,
        '0010': -1
    }

    def setByte(i):
        return i.to_bytes(1)

    def limitNums(num, maxn, minn):
        return max(minn, min(maxn, num))

    def handleLEDs(intensity, value):
示例#32
0
# port = '/dev/ttyACM0'
# sp = serial.Serial(port, baudrate=115200, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE,
#             xonxoff=False, rtscts=False, stopbits=serial.STOPBITS_ONE, timeout=None, dsrdtr=True)
# sp.write("snap")
# sp.flush()
# size = struct.unpack('<L', sp.read(4))[0]
# img = sp.read(size)
# sp.close()
#
# with open("img.jpg", "w") as f:
#     f.write(img)

import sensor, image, time, ustruct
from pyb import USB_VCP

usb = USB_VCP()
sensor.reset()  # Reset and initialize the sensor.
sensor.set_pixformat(
    sensor.RGB565)  # Set pixel format to RGB565 (or GRAYSCALE)
#sensor.set_auto_gain(True)          # Automatically set the gain
#sensor.__write_reg(0x6B, 0x22)      # Enable Advanced AWB
#sensor.set_auto_whitebal(True)      # Automatically set the white balance
#sensor.set_auto_exposure(True)      # Automatically set the exposure
sensor.set_framesize(sensor.QVGA)  # Set frame size to QVGA (320x240)
sensor.skip_frames(time=2000)  # Wait for settings take effect.

while (True):
    cmd = usb.recv(4, timeout=5000)
    if (cmd == b'snap'):
        img = sensor.snapshot().compress()
        usb.send(ustruct.pack("<L", img.size()))
示例#33
0
import sensor, image, time
from pyb import USB_VCP

# Pink
thresholds = [(20, 85, 25, 100, -45, 40)]

# Sensor Initialization
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time=2000)
sensor.set_auto_gain(False)  # must be turned off for color tracking
sensor.set_auto_whitebal(False)  # must be turned off for color tracking

# USB Initialization
usb = USB_VCP()

# Send X,Y
while (True):
    img = sensor.snapshot()
    for blob in img.find_blobs(thresholds,
                               pixels_threshold=25,
                               area_threshold=25,
                               merge=True):

        # Filter non-circle blobs
        if blob.roundness() > 0.6:
            buf = str(blob.cx()) + ' ' + str(blob.cy())
            usb.send(buf)

            # Draw red circle around ball
示例#34
0
def pye(*files):
    from pyb import USB_VCP
    USB_VCP().setinterrupt(-1)
    pye_mp.pye(*files)
    USB_VCP().setinterrupt(3)