Exemplo n.º 1
0
 def __init__(self):
     self._serial = pyb.USB_VCP()
     self._dict = {}
     self._channel_definitions = []
Exemplo n.º 2
0
# main.py -- put your code here!
import pyb, time

led = pyb.LED(3)
usb = pyb.USB_VCP()
while (usb.isconnected() == False):
    led.on()
    time.sleep(150)
    led.off()
    time.sleep(100)
    led.on()
    time.sleep(150)
    led.off()
    time.sleep(600)
Exemplo n.º 3
0
#Start Pocket_Organ if the "Volume" key is pressed down
from board import main_startup_pin, keyboard_melody_led
from time import sleep


def start():
    print("Starting Pocket Organ")
    keyboard_melody_led(
        1)  #Flash Shift led (it will be turned off during initialization)
    import pocket_organ


#Start if USB is disconnected
#Otherwise, start if Vol is pressed
import pyb

p = pyb.USB_VCP()
if p.isconnected():
    if not (main_startup_pin()):
        start()
else:
    start()
print("Not starting Pocket Organ")

#End
Exemplo n.º 4
0
import uos
import uio
import ujson
import pyb
import lighting

usb_pyboard = pyb.USB_VCP()

SensorList = ['TOF0', 'TOF1', 'TOF2']
sw_send_to_terminal = True


def YoN_in_list(senser_name):
    return senser_name in SensorList


def send_to_terminal(sensor_name, time, value):
    # the form of the data sent to terminal is the 'directory'
    dict_data = {"sensor_name": sensor_name, "time": time, "value": value}
    usb_pyboard.send(ujson.dumps(dict_data))
    usb_pyboard.send("\n")


def organiser_content(sensor_name, time, value):
    num_sensor = SensorList.index(sensor_name)
    #content = str(time) + ","
    #for i in range(0, num_sensor):
    #    content = content + ","

    #content = content + str(value) + ","
Exemplo n.º 5
0
# sleep_ms is defined to stop things breaking if someone imports uasyncio.core
# Power won't be saved if this is done.
sleep_ms = utime.sleep_ms

d_series = uname().machine[:4] == 'PYBD'
use_utime = True  # Assume the normal utime timebase

if sys.platform == 'pyboard':
    import pyb
    mode = pyb.usb_mode()
    if mode is None:  # USB is disabled
        use_utime = False  # use RTC timebase
    elif 'VCP' in mode:  # User has enabled VCP in boot.py
        # Detect an active connection (not just a power source)
        if pyb.USB_VCP().isconnected():  # USB will work normally
            print('USB connection: rtc_time disabled.')
        else:
            pyb.usb_mode(None)  # Save power
            use_utime = False  # use RTC timebase
else:
    raise OSError('rtc_time.py is Pyboard-specific.')

# For lowest power consumption set unused pins as inputs with pullups.
# Note the 4K7 I2C pullups on X9 X10 Y9 Y10 (Pyboard 1.x).

# Pulling Pyboard D pins should be disabled if using WiFi as it now seems to
# interfere with it. Although until issue #5152 is fixed it's broken anyway.
if d_series:
    print('Running on Pyboard D')
    if not use_utime:
Exemplo n.º 6
0
def loop(control, thermal, screen, menu, input_handler, camera_slave, **kwargs):

    led_green = LED(2) # red led
    led_green.off()

    usb = pyb.USB_VCP()
    running_from_ide = usb.isconnected()


    def camera_slave_sync_cancel_condition():
        if control.preview is not CameraPreview.VISIBLE or menu.state is not CameraState.PREVIEW:
            logger.info("Cancel camera slave sync")
            return True
        return False

    camera_slave.sync_cancel_condition = camera_slave_sync_cancel_condition

    state = None
    camera_preview = None
    camera_playback_img_name = ""
    previous_text = ""
    screen_refresh_needed = True
    state_ticks_ms = utime.ticks_ms()

    menu.process_action("middle")
    while True:
        changed_state = state is not menu.state
        state = menu.state

        changed_preview = camera_preview is not control.preview
        camera_preview = control.preview

        # -----------------------------------------------------------------------------------------
        # INITIALIZATIONS
        if changed_state:
            state_ticks_ms = utime.ticks_ms()
            logger.info("Processing state change to ", menu.state)
            if menu.state is CameraState.PREVIEW:
                control.fps_reset()
            if menu.state is CameraState.PLAYBACK or menu.state is CameraState.POSTVIEW:
                #control.set_normal_resolution()
                control.update_playback_img_name(go_to_last=True)
                camera_playback_img_name = ""

        if changed_preview:
            control.fps_reset()
            logger.info("Processing preview change to ", control.preview)

        # -----------------------------------------------------------------------------------------
        # RUN TIME

        if state is CameraState.PREVIEW:
            control.fps_tick()
            screen_refresh_needed = True
            text = "\n" + menu.generate_text()

            if camera_preview is CameraPreview.THERMAL or camera_preview is CameraPreview.THERMAL_ANALYSIS or camera_preview is CameraPreview.THERMAL_GREY or camera_preview is CameraPreview.MIX:

                thermal.get_spotmeter_values()
                def map_g_to_temp(g):
                    return ((g * (thermal.temperature_max - thermal.temperature_min)) / 255.0) + thermal.temperature_min

                img = sensor.snapshot()
                img_touch_x = max(0,min(sensor.width() - 1, round(control.x * sensor.width()/screen.width) ))
                img_touch_y = max(0,min(sensor.height() - 1, round(control.y * sensor.height()/screen.height) ))
                pixel = "{:.2f}".format(map_g_to_temp(img.get_pixel(img_touch_x, img_touch_y)))

                if camera_preview is CameraPreview.THERMAL_GREY:
                    img.to_rgb565()
                elif camera_preview is CameraPreview.THERMAL or camera_preview is CameraPreview.MIX:
                    img.to_rainbow(color_palette=sensor.PALETTE_IRONBOW) # color it
                elif camera_preview is CameraPreview.THERMAL_ANALYSIS:
                    # Color tracking concept from lepton_object_temp_color_1.py in the OpenMV examples
                    # Color Tracking Thresholds (Grayscale Min, Grayscale Max)
                    threshold_list = [(200, 255)]

                    blob_stats = []
                    blobs = img.find_blobs(threshold_list, pixels_threshold=200, area_threshold=200, merge=True)
                    # Collect stats into a list of tuples
                    for blob in blobs:
                        blob_stats.append((blob.x(), blob.y(), map_g_to_temp(img.get_statistics(thresholds=threshold_list,
                                                                                                roi=blob.rect()).mean())))
                    img.to_rainbow(color_palette=sensor.PALETTE_IRONBOW) # color it
                    # Draw stuff on the colored image
                    for blob in blobs:
                        img.draw_rectangle(blob.rect())
                        img.draw_cross(blob.cx(), blob.cy())
                    for blob_stat in blob_stats:
                        img.draw_string(blob_stat[0], blob_stat[1] - 10, "%.2f C" % blob_stat[2], mono_space=False)

                qqvga2qvga(sensor.get_fb(), screen.screen_buff)

            if camera_preview is CameraPreview.VISIBLE or camera_preview is CameraPreview.MIX:
                input_handler.disable()
                sync_success = camera_slave.sync()
                input_handler.enable()
                if not sync_success:
                    logger.info("Failed sync")
                    screen.screen_buff.fill(c=(10,10,10))
                    screen.screen_buff.draw_string(screen.width//2, screen.height//2, "ERROR", c=(255,0,0))

                if camera_preview is CameraPreview.VISIBLE:
                    qvga2qvga(camera_slave.rx_buff, screen.screen_buff, 0, 1)
                    pixel = screen.screen_buff.get_pixel(control.x, control.y)
                elif camera_preview is CameraPreview.MIX:
                    qvga2qvga(camera_slave.rx_buff, screen.screen_buff, 0, 2)

            if menu.page != "ROOT" or control.always_pixel_pointer:
                screen.screen_buff.draw_rectangle(control.x-5, control.y-5, 10, 10, color=(255,0,255), thickness=1, fill=True)
                if menu.state is CameraState.PREVIEW:
                    text_y_offset = 50 if control.y < screen.height//2 else -50
                    screen.screen_buff.draw_string(control.x - 20, control.y + text_y_offset, "{}".format(pixel))

        if state is CameraState.PLAYBACK or state is CameraState.POSTVIEW:
            screen_refresh_needed = False

            if menu.page == "ANALYSIS":
                screen_refresh_needed = True

            text = menu.generate_text()
            if  previous_text != text:
                screen_refresh_needed = True

            if not control.playback_img_name:
                logger.info("No image to be loaded")
                menu.back()
                continue
            elif control.playback_img_name != camera_playback_img_name or screen_refresh_needed:
                camera_playback_img_name = control.playback_img_name
                logger.info("Displaying image...", control.playback_img_name, " and text ", text)
                try:
                    img = image.Image(control.playback_img_name, copy_to_fb=True)
                    qvga2qvga(sensor.get_fb(), screen.screen_buff, 0, 1)

                    if control.to_save_fb_as_startup:
                        control.save_fb_as_startup(screen.screen_buff)
                    img.to_grayscale()
                    try:
                        file_name = control.playback_img_name.split("/")[-1].split(".")[0]
                        file_name = file_name.split("_")
                        thermal.temperature_min = float(file_name[1]) / 100
                        thermal.temperature_max = float(file_name[2]) / 100
                    except Exception as e:
                        print("Could not get min and max from name", e)
                    print("file_name", file_name, thermal.temperature_min, thermal.temperature_max)
                except OSError as e:
                    screen.screen_buff.draw_rectangle(0, 0, screen.width, screen.height, color=(30,30,30), fill=True)
                    screen.screen_buff.draw_string(round(screen.width/6), round(screen.height/2.3), "ERROR LOADING...", color=(255,0,0), scale=2.0)
                    logger.info("Error while loading ", control.playback_img_name, ". Try Again. Error", e)


                if menu.page == "ANALYSIS":

                    def map_g_to_temp(g):
                        return ((g * (thermal.temperature_max - thermal.temperature_min)) / 255.0) + thermal.temperature_min

                    img_touch_x = max(0,min(sensor.width() - 1, round(control.x * sensor.width()/screen.width) ))
                    img_touch_y = max(0,min(sensor.height() - 1, round(control.y * sensor.height()/screen.height) ))
                    pixel = "{:.2f}".format(map_g_to_temp(img.get_pixel(img_touch_x, img_touch_y)))

                    screen.screen_buff.draw_rectangle(control.x-5, control.y-5, 10, 10, color=(255,0,255), thickness=1, fill=True)
                    text_y_offset = 50 if control.y < screen.height//2 else -50
                    screen.screen_buff.draw_string(control.x - 20, control.y + text_y_offset, "{}".format(pixel))

                screen_refresh_needed = True


            if state is CameraState.POSTVIEW and utime.ticks_diff(utime.ticks_ms(), state_ticks_ms) > 2000:
                menu.back()

        ########################################################################
        # INPUT TASKS which are BIG
        if control.to_save_img:
            control.save_img(screen.screen_buff, thermal.temperature_min, thermal.temperature_max)
            menu.process_action("postview")
            led_green.on()
            utime.sleep_ms(100)
            led_green.off()


        ########################################################################
        # DISPLAY IN SCREEN
        if menu.state is CameraState.PLAYBACK and menu.page == "MENU":
            screen.screen_buff.draw_rectangle(0,0,screen.width//2,screen.height,color=(0,0,0), fill=True)

        if screen_refresh_needed:
            previous_text = text
            screen.screen_buff.draw_string(10, 10, text, color=(57, 255, 20), scale=2.1, mono_space=False)
            if state is CameraState.PLAYBACK:
                logger.info("Refresh needed")
            screen.write_to_screen(screen.screen_buff)
            screen_refresh_needed = False

        ########################################################################
        # OTHER FUNCTIONALITY

        if not running_from_ide and usb.isconnected():
            screen.screen_buff.draw_rectangle(0, screen.height//3, screen.width, screen.height//3, color=(10,10,10), fill=True)
            screen.screen_buff.draw_string(round(screen.width/5), round(screen.height/2.3), "USB DEBUGGING", color=(255,0,0), scale=2.0)
            screen.write_to_screen(screen.screen_buff)
            utime.sleep_ms(500)
            input_handler.disable()
            exit(0)
        if input_handler.pin.value() == 0 and input_handler.time_since_interrupt() > 100:
            input_handler.interrupt_callback(line="LOOP")

        gc.collect()
Exemplo n.º 7
0
import pyb
import dht
import machine
import sht31

[pyb.LED(i).off() for i in range(1, 5)]

interval = 10000
flashduration = 50
P36pin = 'Y11'
DHT11pin = 'X7'
SCLpin = 'X9'
SDApin = 'X10'

serial = pyb.USB_VCP()
p36 = pyb.ADC(pyb.Pin(P36pin))
d = dht.DHT11(machine.Pin(DHT11pin))
i2c = machine.I2C(sda=machine.Pin(SDApin),
                  scl=machine.Pin(SCLpin),
                  freq=400000)
sht31sensor = sht31.SHT31(i2c)


def flashLED(num=1, duration=flashduration):
    pyb.LED(num).on()
    pyb.delay(duration)
    pyb.LED(num).off()


def adc2mV(adcval):
Exemplo n.º 8
0
 def __init__(self, callback=None):
     self.callback = callback
     self.data = ""
     if USB_ENABLED:
         self.usb = pyb.USB_VCP()
    def turret_hub_fun(self):
        ''' Defines the task function method for a turret hub object.
        '''
        self.vcp = pyb.USB_VCP ()
        
        STATE_0 = micropython.const(0)
        STATE_1 = micropython.const(1)
        STATE_2 = micropython.const(2)
        STATE_3 = micropython.const(3)
        STATE_4 = micropython.const(4)
        STATE_5 = micropython.const(5)
        STATE_6 = micropython.const(6)
        STATE_7 = micropython.const(7)
        STATE_8 = micropython.const(8)
        STATE_9 = micropython.const(9)
        STATE_10 = micropython.const(10)
        STATE_11 = micropython.const(11)
        
        self.state = STATE_0
        self.pan_coords.put(0)
        self.tilt_coords.put(0)        
        
        while True:

            #################################
            
            ## STATE 0: CALIBRATE POINT A   
            if self.state == STATE_0:  
                self.read_GUI()
                yield (self.state)
                
                if self.CALIBRATION_FLG:
                    # input location A into pan centroids
                    self.calibrate_point(0, self.pan_position.get(), self.tilt_angle.get(), pan = True)
                    self.CALIBRATION_FLG = False
                    self.state = STATE_1

            #################################
            
            ## STATE 1: CALIBRATE POINT B    
            elif self.state == STATE_1:
                self.read_GUI()
                yield (self.state)
                
                if self.CALIBRATION_FLG:
                    # input location B into pan centroids
                    self.calibrate_point(1, self.pan_position.get(), self.tilt_angle.get(), pan = True)
                    self.CALIBRATION_FLG = False
                    self.state = STATE_2

            #################################

            ## STATE 2: CALIBRATE POINT C   
            elif self.state == STATE_2:
                self.read_GUI()
                yield (self.state)
                
                if self.CALIBRATION_FLG:
                    # input location C into pan centroids
                    self.calibrate_point(2, self.pan_position.get(), self.tilt_angle.get(), pan = True)
                    self.CALIBRATION_FLG = False
                    self.state = STATE_3

            #################################

            ## STATE 3: CALIBRATE POINT D   
            elif self.state == STATE_3:
                self.read_GUI()
                yield (self.state)
                
                if self.CALIBRATION_FLG:
                    # input location D into pan centroids
                    self.calibrate_point(3, self.pan_position.get(), self.tilt_angle.get(), pan = True)
                    self.CALIBRATION_FLG = False
                    self.state = STATE_4

            #################################

            ## STATE 4: CALIBRATE POINT E & 1
            elif self.state == STATE_4:
                self.read_GUI()
                yield (self.state)
                
                if self.CALIBRATION_FLG:
                    # input location E into pan centroids
                    self.calibrate_point(4, self.pan_position.get(), self.tilt_angle.get(), pan = True)
                    # input location 1 into tilt centroids
                    self.calibrate_point(0, self.pan_position.get(), self.tilt_angle.get(), tilt = True)
                    self.CALIBRATION_FLG = False
                    self.state = STATE_5

            #################################

            ## STATE 5: CALIBRATE POINT 2 
            elif self.state == STATE_5:  
                self.read_GUI()
                yield (self.state)
                
                if self.CALIBRATION_FLG:
                    # input location 2 into tilt centroids
                    self.calibrate_point(1, self.pan_position.get(), self.tilt_angle.get(), tilt = True)
                    self.CALIBRATION_FLG = False
                    self.state = STATE_6
 
            #################################
           
            ## STATE 6: CALIBRATE POINT 3   
            elif self.state == STATE_6:
                self.read_GUI()
                yield (self.state)
                
                if self.CALIBRATION_FLG:
                    # input location 3 into tilt centroids
                    self.calibrate_point(2, self.pan_position.get(), self.tilt_angle.get(), tilt = True)
                    self.CALIBRATION_FLG = False
                    self.state = STATE_7

            #################################

            ## STATE 7: CALIBRATE POINT 4   
            elif self.state == STATE_7:
                self.read_GUI()
                yield (self.state)
                
                if self.CALIBRATION_FLG:
                    # input location 4 into tilt centroids
                    self.calibrate_point(3, self.pan_position.get(), self.tilt_angle.get(), tilt = True)
                    self.CALIBRATION_FLG = False
                    self.state = STATE_8

            #################################

            ## STATE 8: CALIBRATE POINT 5 
            elif self.state == STATE_8:
                self.read_GUI()
                yield (self.state)
                
                if self.CALIBRATION_FLG:
                    # input location 5 into tilt centroids
                    self.calibrate_point(4, self.pan_position.get(), self.tilt_angle.get(), tilt = True)
                    # Begin winding up gun!!!
                    self.WINDUP_GUN.put(1)
                    self.state = STATE_9

            #################################
            
            ## STATE 9: STOPPED, NOT SHOOTING
            elif self.state == STATE_9:                
                self.read_GUI()
                yield (self.state)
                
                if self.TARGET_CMD:
                    self.state = STATE_10

            #################################

            ## STATE 10: MOVING, SHOOTING
            elif self.state == STATE_10:
                # clear the target cmd flag for state 9 next time
                self.TARGET_CMD = False
                self.state = STATE_11

            #################################
                    
            ## STATE 11: STOPPED, SHOOTING
            elif self.state == STATE_11:
                self.read_GUI()
                yield (self.state)
                
                if not self.FEED_BULLETS.get():
                    self.state = STATE_9

            #################################
                    
            yield (self.state)
Exemplo n.º 10
0
# -*- coding: utf-8 -*-
"""
Created on Mon May 27 17:48:42 2019

@author: claud
"""

import pyb

repl = pyb.USB_VCP()
uart = pyb.UART(3, 9600)

while True:
    if uart.any():
        ch = uart.read()
        repl.write(ch)
    if repl.any():
        ch = repl.read()
        uart.write(ch)
Exemplo n.º 11
0
    def turret_hub_fun(self):
        ''' Defines the task function method for a turret hub object.
        '''
        vcp = pyb.USB_VCP()

        STATE_0 = micropython.const(0)
        STATE_1 = micropython.const(1)
        STATE_2 = micropython.const(2)
        STATE_3 = micropython.const(3)
        STATE_4 = micropython.const(4)

        self.state = STATE_0

        while True:
            ## STATE 0: CALIBRATE GRID
            if self.state == STATE_0:
                # --- insert calibration code here (waits for user input) ---
                # vars currently place holders for below code...
                self.pan_coords.put(0)
                self.tilt_coords.put(0)
                print('pan tilt to zero')
                yield (self.state)

                if self.CALIBRATION_DONE:
                    self.state = STATE_1

            ## STATE 1: STOPPED, NOT SHOOTING
            elif self.state == STATE_1:
                # --- insert XBee command code here (looking for cmds) ---
                # pull the coordinates from the pan and tilt matrices
                # set TARGET_CMD when coordinates are retrieved...
                #print('in first state')
                if vcp.any():
                    y = float(vcp.read(2).decode('UTF-8'))
                    print('recieved value:' + str(y))
                    if (y == 1):
                        #self.coordinate.put(2000)
                        self.pan_coords.put(2000)
                        print('updtated pan coords to 2000')
                        self.TARGET_CMD = 1
                    if (y == 2):
                        self.pan_coords.put(-2000)
                        print('updtated pan coords to -2000')
                        self.TARGET_CMD = 1
                    if (y == 3):
                        self.tilt_coords.put(15)
                        print('updtated tilt coords to 15')
                        self.TARGET_CMD = 1
                    if (y == 4):
                        self.tilt_coords.put(-15)
                        print('updtated tilt coords to -15')
                        self.TARGET_CMD = 1

                yield (self.state)


#                if self.TARGET_CMD:
##                    self.WINDUP_GUN.put(micropython.const(1))
##                    self.pan_coords.put(self.pan_coords)
##                    self.tilt_coords.put(self.tilt_coords)
#                    self.state = STATE_2
#
#            ## STATE 2: MOVING, NOT SHOOTING
#            elif self.state == STATE_2:
##                if self.pan_completion.get() > 50.0 and self.tilt_completion.get() > 50.0:
##                    self.FEED_BULLETS.put(micropython.const(1))
#                    self.state = STATE_3
#
#            ## STATE 3: MOVING, SHOOTING
#            elif self.state == STATE_3:
#                if self.pan_completion.get() == 100.0 and self.tilt_completion.get() == 100.0:
#                    # init the time for keeping track of how long to shoot
#                    self.timer_init = utime.ticks_ms()
#                    # clear the target cmd flag for state 1 next time
#                    self.TARGET_CMD = micropython.const(0)
#                    # clear the pan and tilt coords...
#                    self.pan_coords.put()
#                    self.tilt_coords.put()
#                    self.state = STATE_4
#
#            ## STATE 4: STOPPED, SHOOTING
#            elif self.state == STATE_4:
#                if (utime.ticks_ms() - self.timer_init) > self.timeout:
#                    self.FEED_BULLETS = micropython.const(0)
#                    # delay 1 second to wait for feeder to stop..
#                    while (utime.ticks_ms() - self.timeout) < 1000:
#                        yield (self.state)
#                    self.WINDUP_GUN = micropython.const(0)
##                    self.DESTINATION_50_COMPLETE = micropython.const(0)
#                    self.timer_init = 0
#                    self.state = STATE_1
#
#            yield (self.state)
Exemplo n.º 12
0
 def init_usb(self):
     self.usb = pyb.USB_VCP()
Exemplo n.º 13
0
    
    def halt(self):
        # lock the stepper motor, this draws power
        # enable low is needed to send step instructions to the motor
        self.enable.low()
    
    def off(self):
        # turn the motor off and allow free spin
        self.enable.high()
        self.step.low()

# objects needed for callbacks
tim1 = pyb.Timer(8, freq=10000)
stepper = Stepper('X1', 'X2', 'X3', tim1.freq())
# virtual comm port connection
com = pyb.USB_VCP()

# limit switch callback
# delay and interupt enabling/disabling for switch debouncing 
def limit_cb(line):
    limit.disable()
    pyb.delay(10)
    stepper.off()
    pyb.LED(2).toggle()
    limit.enable()
    print('[pyboard] limit switch active: stepper off')

def stepper_cb(t):
    stepper.turn()

tim1.callback(stepper_cb)
    def run(self):
        myled = pyb.LED(1)
        myled2 = pyb.LED(2)
        myled.on()
        AC_handler = Access_control_upy()
        AC_handler.loadcell.tare()
        micros = pyb.Timer(2, prescaler=83,
                           period=0x3fffffff)  #just a microsecond timer

        enable_pin_1 = pyb.Pin(
            'X11', pyb.Pin.OUT
        )  # Enables/disables the drivers on the + side of doors 1 & 2.
        enable_pin_2 = pyb.Pin(
            'X12', pyb.Pin.OUT
        )  # Enables/disables the drivers on the + side of doors 3 & 4.
        enable_pin_1.value(1)  # Enable drivers.
        enable_pin_2.value(1)

        highside_pins = [
            pyb.Pin(p, pyb.Pin.OUT) for p in ('Y3', 'Y5', 'Y12', 'X6')
        ]  # Controls whether + side of door is driven to 12V or 0V.
        lowside_pins = [
            pyb.Pin(p, pyb.Pin.OUT) for p in ('Y4', 'Y6', 'Y11', 'X5')
        ]  # Controls whether - side of door is driven to 12V or 0V.
        signal_pins = [pyb.ADC(p) for p in ('X1', 'X2', 'X3', 'X4')
                       ]  # Pins used to sense voltage on + side of doors.

        for i in range(4):  # Drive both sides of all doors to 0V.
            highside_pins[i].value(0)
            lowside_pins[i].value(0)

        P_read_en1 = signal_pin(signal_pins[0], enable_pin_1,
                                enable_pin_2)  #Pin('Y1', Pin.IN, Pin.PULL_UP)
        P_read_en2 = signal_pin(signal_pins[1], enable_pin_1,
                                enable_pin_2)  #Pin('Y2', Pin.IN, Pin.PULL_UP)
        P_read_ex1 = signal_pin(signal_pins[2], enable_pin_1,
                                enable_pin_2)  #Pin('Y3', Pin.IN, Pin.PULL_UP)
        P_read_ex2 = signal_pin(signal_pins[3], enable_pin_1,
                                enable_pin_2)  #Pin('Y4', Pin.IN, Pin.PULL_UP)

        P_mag_en1 = magnet_pin(highside_pins[0],
                               lowside_pins[0])  #Pin('X8', Pin.OUT_PP)
        P_mag_en2 = magnet_pin(highside_pins[1],
                               lowside_pins[1])  #Pin('X7', Pin.OUT_PP)
        P_mag_ex1 = magnet_pin(highside_pins[2],
                               lowside_pins[2])  #Pin('X6', Pin.OUT_PP)
        P_mag_ex2 = magnet_pin(highside_pins[3],
                               lowside_pins[3])  #Pin('X5', Pin.OUT_PP)

        MAGs = [P_mag_en1, P_mag_en2, P_mag_ex1, P_mag_ex2]

        com = pyb.USB_VCP()

        ONE_MOUSE = 8
        TWO_MICE = 40
        NEWSTATE = True
        state = 'allow_entry'
        build_msg = lambda x: 'start_' + x + '_end'

        com.write(build_msg('state:' + state))
        for mag in [0, 1, 2, 3]:
            MAGs[mag].value(0)  #this should be 0

        myled.off()
        self.baseline_read = 0.
        self.baseline_alpha = .3
        self.forced_delay = 500
        last_check = micros.counter()
        mean = lambda x: float(sum(x)) / float(len(x))

        state = 'allow_entry'
        ## This is the infinite loop
        #state = 'error_state'
        has_send_error = False
        millis_since_check_wait_close = None
        num_times_checked_for_error = 0  #first check is a variable that basically ensures that a mouse must be stuck for 2 sets of scale readings before an error state is raised
        try:

            while True:

                if state == 'allow_entry':
                    #last_weight = self.baseline_alpha*AC_handler.loadcell.weigh(times=1) + (1-self.baseline_alpha)*last_weight
                    if NEWSTATE:
                        com.write(build_msg('state:' + state))
                        NEWSTATE = False

                    for mag in range(4):
                        if mag in [1, 2, 3]:
                            MAGs[mag].value(1)
                        else:
                            MAGs[mag].value(0)

                    #if the entry door is opened
                    weight = AC_handler.loadcell.weigh()
                    if weight > ONE_MOUSE:
                        state = 'wait_close'
                        NEWSTATE = True
                        last_check = micros.counter()
                        MAGs[0].value(1)
                        pyb.delay(self.forced_delay)
                    #if P_read_en1.value():
                    #    state = 'wait_close'
                    #    NEWSTATE = True; pyb.delay(self.forced_delay)
                    #    last_check = micros.counter()

                if state == 'wait_close':

                    if NEWSTATE:
                        com.write(build_msg('state:' + state))
                        NEWSTATE = False

                    if P_read_en1.value() == 0:  #if entry door is closed again
                        com.write(
                            build_msg('door0_closed:' +
                                      str(P_read_en1.measured_value)))
                        ## This is an extra check step to try to help prevent the door from being unnecessarily closed
                        weight = AC_handler.loadcell.weigh()
                        if weight < ONE_MOUSE:
                            state = 'allow_entry'
                            NEWSTATE = True
                            pyb.delay(self.forced_delay)
                            last_check = micros.counter()
                        else:
                            for mag in range(4):
                                MAGs[mag].value(1)

                            state = 'check_mouse'
                            NEWSTATE = True
                            pyb.delay(self.forced_delay)
                            last_check = micros.counter()
                    else:
                        com.write(
                            build_msg('door0_open:' +
                                      str(P_read_en1.measured_value)))
                    weight = AC_handler.loadcell.weigh()
                    #if weight>ONE_MOUSE:
                    #    if millis_since_check_wait_close is None:
                    #        millis_since_check_wait_close = pyb.millis()
                    #
                    #    else:
                    #        if pyb.elapsed_millis(millis_since_check_wait_close)>(300*1000):
                    #            state = 'error_state'

                    if weight < ONE_MOUSE:
                        millis_since_check_wait_close = None
                #in this state check that a mouse has entered the access control system and
                #make sure that it is in fact only 1 mouse in the access control system
                if state == 'check_mouse':

                    if NEWSTATE:
                        millis_since_check_wait_close = None
                        com.write(build_msg('state:' + state))
                        NEWSTATE = False

                    weights = []
                    for _ in range(50):
                        weight = AC_handler.loadcell.weigh(times=1)
                        com.write(build_msg('temp_w:' + str(weight)))
                        pyb.delay(10)
                        weights.append(weight)

                        #This is a second check so that the entry door does not stay unnecessarily closed
                        #this value must be greater than 2
                        if ((mean(weights) - self.baseline_read) < ONE_MOUSE
                                and len(weights) > 2):
                            break
                    filt_w = [0] + [
                        1. /
                        (abs(weights[ix] - j) + abs(weights[ix + 2] - j))**2
                        for ix, j in enumerate(weights[1:-1])
                    ] + [0]
                    filt_sum = float(sum(filt_w))
                    filt_w2 = [wtmp / filt_sum for wtmp in filt_w]
                    weight = sum([i * j for i, j in zip(weights, filt_w2)])

                    weight = weight - self.baseline_read
                    #weight = 25
                    com.write(build_msg('weight:' + str(weight)))

                    #if more than one mouse got in
                    if weight > TWO_MICE:
                        com.write('2 mice')
                        state = 'allow_exit'
                        NEWSTATE = True
                        pyb.delay(self.forced_delay)
                    elif weight < ONE_MOUSE:
                        com.write('0 mice')
                        state = 'allow_entry'
                        NEWSTATE = True
                        pyb.delay(self.forced_delay)
                    else:
                        com.write('1 mice')
                        com.write(build_msg('weight:' + str(weight)))
                        getRFID = True
                        st_check = time.time()
                        while getRFID:
                            rfid = AC_handler.rfid.read_tag()
                            pyb.delay(50)
                            #rfid = '116000039959'
                            #rfid = '116000039953'
                            #if read an RFID TAG
                            if rfid is not None:
                                com.write(build_msg('RFID:' + str(rfid)))
                                getRFID = False
                                state = 'enter_training_chamber'
                                NEWSTATE = True
                                pyb.delay(self.forced_delay)

                            #if no RFID tag read in 20s
                            if (time.time() - st_check) > 30:
                                getRFID = False
                                state = 'allow_exit'

                else:
                    rfid = AC_handler.rfid.read_tag()
                    rfid = None

                #in this state allow a mouse to leave the access control system and
                #move into the training room. Once the door to the training room has
                #opened leave this state
                if state == 'enter_training_chamber':

                    if NEWSTATE:
                        com.write(build_msg('state:' + state))
                        NEWSTATE = False
                    for mag in range(4):
                        if mag in [0, 2, 3]:
                            MAGs[mag].value(1)
                        else:
                            MAGs[mag].value(0)

                    #if the mouse had opened the door to training chamber
                    weight = AC_handler.loadcell.weigh(times=1)
                    #if P_read_en2.value()==1:
                    if weight < ONE_MOUSE:
                        state = 'check_mouse_in_training'
                        NEWSTATE = True
                        pyb.delay(self.forced_delay)

                #once the door to the training chamber has closed again, make sure that
                #the mouse has left
                if state == 'check_mouse_in_training':
                    if NEWSTATE:
                        com.write(build_msg('state:' + state))
                        NEWSTATE = False
                        MAGs[1].value(1)

                    #if door entry to chamber is closed again
                    if P_read_en2.value() == 0:

                        weight = AC_handler.loadcell.weigh(
                        )  # - self.baseline_read   #RETURN
                        pyb.delay(10)

                        if weight < ONE_MOUSE:
                            state = 'mouse_training'
                            NEWSTATE = True
                            pyb.delay(self.forced_delay)
                        else:
                            state = 'enter_training_chamber'
                            NEWSTATE = True
                            pyb.delay(self.forced_delay)

                if state == 'mouse_training':  #now the mouse is in the training apparatus
                    if NEWSTATE:
                        com.write(build_msg('state:' + state))
                        NEWSTATE = False

                    for mag in range(4):
                        if mag in [0, 1, 3]:
                            MAGs[mag].value(1)
                        else:
                            MAGs[mag].value(0)
                    weight = AC_handler.loadcell.weigh()
                    if weight > ONE_MOUSE:
                        #if P_read_ex1.value()==1:
                        state = 'check_mouse_in_ac'
                        NEWSTATE = True
                        MAGs[2].value(1)
                        pyb.delay(self.forced_delay)

                if state == 'check_mouse_in_ac':
                    if NEWSTATE:
                        com.write(build_msg('state:' + state))
                        NEWSTATE = False

                    #YVES UPDATE 160221 think this is unncessary
                    #for mag in range(4):
                    #    MAGs[mag].value(1)

                    if P_read_ex1.value() == 0:

                        weight = AC_handler.loadcell.weigh(
                        )  # - self.baseline_read
                        pyb.delay(10)

                        if weight < ONE_MOUSE:  #in this case the mouse opened and closed the door without going back into the training room
                            state = 'mouse_training'
                            NEWSTATE = True
                            pyb.delay(self.forced_delay)
                        else:
                            state = 'allow_exit'
                            NEWSTATE = True
                            pyb.delay(self.forced_delay)

                if (state == 'mouse_training') or (state == 'allow_entry'):
                    ##here re-baseline the scale
                    if abs(micros.counter() - last_check) > (
                            10**6):  #do handshake once per second
                        last_check = micros.counter()

                        #if abs(CW-self.baseline_read)<1:
                        Wbase = float(AC_handler.loadcell.weigh(times=1))
                        com.write(build_msg('Wbase:' + str(Wbase)))
                        #com.write(build_msg('Wbase:' + str(Wbase)))

                        #if one Wbase weight is greater than the weight of one mouse, then double check
                        #that weight by weighing 10 times. If that weight is still above the weight of one
                        #mouse, then come back in 1s and check again. If the weight is still too high, go
                        #into an error state
                        if Wbase > ONE_MOUSE:
                            CW = AC_handler.loadcell.weigh(times=2)
                            if float(CW) > ONE_MOUSE:
                                if num_times_checked_for_error > 30:
                                    state = 'error_state'
                                    com.write(build_msg('state:' + str(state)))
                                num_times_checked_for_error += 1
                        else:
                            num_times_checked_for_error = 0
                            self.baseline_read = self.baseline_alpha * Wbase + (
                                1 - self.baseline_alpha) * self.baseline_read

                if state == 'allow_exit':

                    if NEWSTATE:
                        com.write(build_msg('state:' + state))
                        NEWSTATE = False

                    weight = AC_handler.loadcell.weigh(times=1)
                    com.write(build_msg('temp_w_out:' + str(weight)))

                    for mag in range(4):
                        if mag in [0, 1, 2]:
                            MAGs[mag].value(1)
                        else:
                            MAGs[mag].value(0)

                    if weight < ONE_MOUSE:
                        #if P_read_ex2.value()==1:   #if the door is opened
                        state = 'check_exit'
                        NEWSTATE = True
                        MAGs[3].value(1)
                        pyb.delay(self.forced_delay)

                if state == 'check_exit':
                    if NEWSTATE:
                        com.write(build_msg('state:' + state))
                        NEWSTATE = False

                    if P_read_ex2.value() == 0:  #if exit door is closed

                        weight = AC_handler.loadcell.weigh(
                        ) - self.baseline_read
                        pyb.delay(10)

                        if weight < ONE_MOUSE:  #in this case the mouse has left and we restart
                            state = 'allow_entry'
                            NEWSTATE = True
                            pyb.delay(self.forced_delay)
                        else:
                            state = 'allow_exit'
                            NEWSTATE = True
                            pyb.delay(self.forced_delay)

                if state == 'error_state':
                    if not has_send_error:
                        com.write(build_msg('state:' + 'error_state'))
                        has_send_error = True
                    for mag in range(4):
                        MAGs[mag].value(0)

                sent_data = com.readline()

                if sent_data is not None:
                    sent_data = sent_data.decode('utf8')
                    if sent_data == 'tare':

                        AC_handler.loadcell.tare()

                        weight = AC_handler.loadcell.weigh()
                        pyb.delay(10)
                        com.write(build_msg('calT:' + str(weight)))
                    elif 'calibrate' in sent_data:
                        w_ = float(sent_data[10:])
                        AC_handler.loadcell.calibrate(weight=w_)
                        #com.write(build_message(str(sent_data)))

                        weight = AC_handler.loadcell.weigh()
                        pyb.delay(10)
                        com.write(build_msg('calC:' + str(weight)))

                    elif sent_data == 'weigh':

                        weight = AC_handler.loadcell.weigh()
                        pyb.delay(10)
                        com.write(build_msg('calW:' + str(weight)))
        except Exception as e:
            for mag in range(4):
                MAGs[mag].value(0)

            state = 'error_state'
            com.write(build_msg('state:' + str(state)))
            com.write(build_msg(str(e)))
Exemplo n.º 15
0
import ustruct as struct

while (True):
    ##############################
    # Initialize camera and connection
    # (only runs once upon establishing
    # serial connection)
    sensor.reset()  # Initialize the camera sensor.
    RED_LED_PIN = 1
    BLUE_LED_PIN = 3
    sensor.set_pixformat(sensor.GRAYSCALE)  # or sensor.GRAYSCALE
    sensor.set_framesize(sensor.QQVGA)  # or sensor.QQVGA (or others)
    sensor.skip_frames(time=2000)  # Let new settings take affect.

    # create a new USB_VCP object
    usb_vcp = pyb.USB_VCP()
    usb_vcp.setinterrupt(-1)

    connected = usb_vcp.isconnected()
    if connected:
        pyb.LED(BLUE_LED_PIN).on()
        pyb.delay(100)
        pyb.LED(BLUE_LED_PIN).off()
    #print(connected)
    usb_vcp.send(int(connected))
    nBytes = 13
    # end of initialization code
    ##############################

    while connected:
        ###########################
Exemplo n.º 16
0
def main(v_flip=False, h_flip=False):

    global PIR_flag

    ## The 9 inch board has X19/X20 swapped. For this board, use the alternative code
    if TFT_SIZE == 9:
        adc = pyb.ADC(pyb.Pin.board.X19)  # read battery voltage (large PCB)
    else:
        adc = pyb.ADC(pyb.Pin.board.X20)  # read battery voltage
    vbus = pyb.Pin('USB_VBUS')
    if vbus.value():
        USBSUPPLY = True
    else:
        USBSUPPLY = False

    usb = pyb.USB_VCP()

    batval = adc.read()
    if (TOOLOWBAT < batval <
            LOWBAT) and USBSUPPLY == False:  # low battery, switch off
        while True:  # stay there until reset
            pyb.stop()  # go to sleep. Only the PIR Sensor may wake me up
# Battery OK, or suppy by USB, start TFT.
    if TFT_SIZE == 7:
        mytft = tft.TFT("SSD1963", "AT070TN92", tft.PORTRAIT, v_flip, h_flip)
    elif TFT_SIZE == 4:
        mytft = tft.TFT("SSD1963", "LB04301", tft.LANDSCAPE, v_flip, h_flip)
    elif TFT_SIZE == 9:
        mytft = tft.TFT("SSD1963", "AT090TN10", tft.PORTRAIT, False, True)
    mytft.clrSCR()
    width, height = mytft.getScreensize()

    if TFT_SIZE == 9:
        ## The 9 inch board has X19/X20 swapped. For this board, use the alternative code
        extint = pyb.ExtInt(pyb.Pin.board.X20, pyb.ExtInt.IRQ_RISING,
                            pyb.Pin.PULL_DOWN, callback)  ## large PCB
    else:
        extint = pyb.ExtInt(pyb.Pin.board.X19, pyb.ExtInt.IRQ_RISING,
                            pyb.Pin.PULL_NONE, callback)
    extint.enable()

    files, has_banner, shuffle = get_files("/sd/serie", "/sd/zufall")

    start = COUNTER  # reset timer once
    PIR_flag = False

    file_index = 0
    while True:
        TESTMODE = usb.isconnected()  # On USB, run test mode
        # on every series start create a random shuffle
        if file_index == 0 and shuffle == True:
            files = list_shuffle(files)
        name = files[file_index]
        file_index = (file_index + 1) % len(files)
        ## on USB supply assume good battery
        if USBSUPPLY == False:
            batval = adc.read()
        else:
            batval = WARNBAT + 1
        if TESTMODE:
            print("Battery: ", batval, ", Files: ", len(files), ", File: ",
                  name)


## test for low battery, switch off
        if (TOOLOWBAT < batval < LOWBAT) and USBSUPPLY == False:
            tft_standby(mytft)
            while True:  # stay there until reset
                pyb.stop()

        if (file_index % BANNER_COUNTER) == 1 and has_banner == True:
            displayfile(mytft, BANNER_NAME, width, height)
            display_batlevel(mytft, batval)
            pyb.delay(BANNER_TIME)

        if displayfile(mytft, name, width, height):
            display_batlevel(mytft, batval)
            pyb.delay(PICT_TIME)

        if PIR_flag == False:  ## For one picture activity, check inactivity counter
            start -= 1
            if start <= 0:  # no activity,  long enough
                if TESTMODE == False:
                    tft_standby(mytft)  # switch TFT off and ports inactive
                    pyb.delay(200)
                    pyb.stop()  # go to sleep Only PIR Sensor may wake me up
                    pyb.hard_reset()  # will do all the re-init
                else:
                    print("Should switch off here for a second")
                    mytft.clrSCR()
                    mytft.setTextStyle((255, 255, 255), None, 0, font14)
                    mytft.setTextPos(0, 0)
                    pyb.delay(100)
                    batval = adc.read()
                    mytft.printString("{:.3}V - {}".format(
                        ((batval * 3.3 * SCALING) / 4096) + OFFSET,
                        file_index))
                    mytft.printNewline()
                    mytft.printCR()
                    mytft.printString("Should switch off here for a second")
                    pyb.delay(3000)
                PIR_flag = False
                start = COUNTER  # reset timer
        else:  # activity. restart counter
            PIR_flag = False
            start = COUNTER  # reset timer
Exemplo n.º 17
0
###############################################################
# Code for OpenMV M7 camera
# Save the reset status to a file named "reset_status.txt". No luck with anything but "False" being written.
# Author: Adam A. Koch (aakoch)
# Date: 2018-04-03
# Copyright (c) 2018 Adam A. Koch
# This work is licensed under the MIT license.
###############################################################
import time, pyb, uio, uos, machine
from pyb import RTC

rtc = RTC()

filename = "reset_status.txt"
connectedToUsb = pyb.USB_VCP().isconnected()

if (connectedToUsb):
    print("current directory=%s" % uos.getcwd())
    print("directory contents=%s" % uos.listdir())

    file = uio.open(filename, "rt")
    #print("file contents:")
    #print(file.read());
    lines = str.split(file.read())

    powerOnReset = str.split(lines[0], "=")[1]
    externalReset = str.split(lines[1], "=")[1]
else:
    powerOnReset = rtc.info() & 0x00010000 != 0
    externalReset = rtc.info() & 0x00020000 != 0
Exemplo n.º 18
0
        sz = jpg.size()
        packed_size = ustruct.pack('@i', sz)
        port.write(packed_size)
        port.send(jpg)
        return 1
    except:
        return -1


sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time=2000)
clock = time.clock()

brd = pyb.USB_VCP()
brd.setinterrupt(-1)

led1 = pyb.LED(1)
led2 = pyb.LED(2)

triggerstring = 'Go'

while (1):
    if brd.isconnected():  # Listen for the command/trigger
        cmd = recv_msg(brd)[0].decode()  # Looks for initialization command
        if cmd == triggerstring:
            avg_data = recv_msg(
                brd)  #Receive calibration data/moving averages from BB

            ##############################################
Exemplo n.º 19
0
    def server(self):
        led = pyb.Pin('PC15', mode=pyb.Pin.OUT_PP)
        self.show()
        self.com = pyb.USB_VCP()
        if not self.com.isconnected():
            led.low()
            print("No client connected")
        else:
            led.high()
        # This is a raw data stream .. os disable the CTRL-C interrupt
        self._com.setinterrupt(-1)
        HELLO, WIDTH, HEIGHT, DEPTH, PIXEL, FILL, CLEAR, TEXT = range(
            48, 48 + 8)
        ANSW_OK, ANSW_ERROR = b'\0', b'\1'
        while True:
            answ = ANSW_OK
            data = self.get_cmd_from_client()
            if not data or len(data) == 0:
                continue
            data_idx = 0
            cmd = data[data_idx]
            data_idx += 1
            if self.DEBUG:
                print("Received command: %d" % cmd)
            if cmd == HELLO:
                text = bytes(os.uname()[-1], 'utf-8')
                answ += struct.pack('B', len(text))
                answ += text
            elif cmd == WIDTH:
                answ += struct.pack("H", self._width)
            elif cmd == HEIGHT:
                answ += struct.pack("H", self._height)
            elif cmd == DEPTH:
                answ += struct.pack("H", self._depth)
            elif cmd == PIXEL:
                x, y, cnt = self.get_coord(data[data_idx:])
                data_idx += cnt
                if cnt == 0:
                    answ = ANSW_ERROR
                else:
                    r, g, b, cnt = self.get_rgb(data[data_idx:])
                    data_idx += cnt
                    if cnt == 0:
                        color = self.pixel((x, y))
                        answ += struct.pack('BBB', color[0], color[1],
                                            color[2])
                    else:
                        self.pixel((x, y), (r, g, b))
            elif cmd == FILL:
                r, g, b, cnt = self.get_rgb(data[data_idx:])
                data_idx += cnt
                if cnt == 3:
                    self.fill((r, g, b))
                else:
                    answ = ANSW_ERROR
            elif cmd == CLEAR:
                self.clear()
            elif cmd == TEXT:
                text, cnt = self.get_string(data[data_idx:])
                data_idx += cnt
                if cnt != 0:
                    x, y, cnt = self.get_coord(data[data_idx:])
                    data_idx += cnt
                    if cnt == 0:
                        answ = ANSW_ERROR
                    else:
                        r, g, b, cnt = self.get_rgb(data[data_idx:])
                        data_idx += cnt
                        if cnt == 3:
                            self.text(text, (x, y), (r, g, b))
                else:
                    answ = ANSW_ERROR
            else:
                answ = ANSW_ERROR

            answ += b'\x0d\x0a'
            self.com.write(answ)
            if self.DEBUG:
                bStr = "".join([" 0x%02x" % i for i in answ])
                print("Send bytes: %s" % bStr)
Exemplo n.º 20
0
# boot.py -- run on boot-up
# can run arbitrary Python, but best to keep it minimal

import machine, pyb, time, bmp, dap

pyb.country('US')  # ISO 3166-1 Alpha-2 code, eg US, GB, DE, AU
#pyb.main('main.py') # main script to run after this one

if 0:
    pyb.usb_mode('VCP+HID', vid=0x1d50, pid=0x6018, hid=dap.hid_info)
    time.sleep(1)
    dap.init()
    print('dap')

if 0:
    pyb.usb_mode('VCP+VCP', vid=0x1d50, pid=0x6018)
    bmp.init(stream=pyb.USB_VCP(1))
    print('bmp usb')

# not truncated
    def turret_hub_fun(self):
        ''' Defines the task function method for a turret hub object.
        '''
        vcp = pyb.USB_VCP()

        STATE_0 = micropython.const(0)
        STATE_1 = micropython.const(1)
        STATE_2 = micropython.const(2)
        STATE_3 = micropython.const(3)
        STATE_4 = micropython.const(4)
        STATE_5 = micropython.const(5)

        self.state = STATE_0
        self.pan_coords.put(0)
        self.tilt_coords.put(0)

        while True:
            ## STATE 0: CALIBRATE GRID - POINT I
            if self.state == STATE_0:
                #                print(' calibration')

                if vcp.any():
                    self.GUI_input = float(vcp.read(2).decode('UTF-8'))
                    self.GUI_Lookup_Table(self.GUI_input)
#                    print(self.pan_position.get())
#                    print(self.tilt_angle.get())
                yield (self.state)

                if self.CALIBRATION_I_DONE:
                    #                    print(self.pan_position.get())
                    #                    print(self.tilt_angle.get())
                    self.state = STATE_1

            ## STATE 1: CALIBRATE GRID - POINT II
            elif self.state == STATE_1:
                if vcp.any():
                    self.GUI_input = float(vcp.read(2).decode('UTF-8'))
                    self.GUI_Lookup_Table(self.GUI_input)
                yield (self.state)

                if self.CALIBRATION_II_DONE:
                    #                    print(self.pan_position.get())
                    #                    print(self.tilt_angle.get())
                    self.state = STATE_2

            ## STATE 2: CALIBRATE GRID - POINT III
            elif self.state == STATE_2:
                if vcp.any():
                    self.GUI_input = float(vcp.read(2).decode('UTF-8'))
                    self.GUI_Lookup_Table(self.GUI_input)
                yield (self.state)

                if self.CALIBRATION_III_DONE:
                    print('Pan Calibration:')
                    print(self.I_location[0])
                    print(self.II_location[0])

                    self.pan_delta = (self.II_location[0] -
                                      self.I_location[0]) / 5
                    self.pan_centroids[
                        0] = self.I_location[0] + self.pan_delta / 2
                    self.pan_centroids[
                        1] = self.pan_centroids[0] + self.pan_delta
                    self.pan_centroids[
                        2] = self.pan_centroids[1] + self.pan_delta
                    self.pan_centroids[
                        3] = self.pan_centroids[2] + self.pan_delta
                    self.pan_centroids[
                        4] = self.pan_centroids[3] + self.pan_delta

                    print('Tilt Calibration:')
                    print(self.II_location[1])
                    print(self.III_location[1])

                    self.tilt_delta = (self.II_location[1] -
                                       self.III_location[1]) / 5
                    self.tilt_centroids[
                        0] = self.I_location[1] - self.tilt_delta / 2
                    self.tilt_centroids[
                        1] = self.tilt_centroids[0] - self.tilt_delta
                    self.tilt_centroids[
                        2] = self.tilt_centroids[1] - self.tilt_delta
                    self.tilt_centroids[
                        3] = self.tilt_centroids[2] - self.tilt_delta
                    self.tilt_centroids[
                        4] = self.tilt_centroids[3] - self.tilt_delta

                    print(self.pan_centroids)
                    print('\n')
                    print(self.tilt_centroids)
                    print(self.pan_position.get())
                    print(self.tilt_angle.get())

                    # begin winding up gun!!!
                    self.WINDUP_GUN.put(1)

                    #                    self.GUI_Lookup_Table(13) # aim at C3
                    self.state = STATE_3

            ## STATE 3: STOPPED, NOT SHOOTING
            elif self.state == STATE_3:

                # added this print statement for debugging the tilt windup issue... comment out when done
                print('Pan: ' + str(self.pan_position.get()))
                print('Tilt: ' + str(self.tilt_angle.get()))

                if vcp.any():
                    self.GUI_input = float(vcp.read(2).decode('UTF-8'))
                    self.GUI_Lookup_Table(self.GUI_input)
                yield (self.state)

                if self.TARGET_CMD:
                    self.FEED_BULLETS.put(1)
                    self.state = STATE_4

            ## STATE 4: MOVING, SHOOTING
            elif self.state == STATE_4:
                # clear the target cmd flag for state 1 next time
                self.TARGET_CMD = False
                self.state = STATE_5

            ## STATE 5: STOPPED, SHOOTING
            elif self.state == STATE_5:
                if vcp.any():
                    self.GUI_input = float(vcp.read(2).decode('UTF-8'))
                    self.GUI_Lookup_Table(self.GUI_input)
                yield (self.state)

                if not self.FEED_BULLETS.get():
                    self.state = STATE_3

            yield (self.state)
Exemplo n.º 22
0
 def __init__(self): # private
     self.__usb_vcp = pyb.USB_VCP()
     if self.__usb_vcp.debug_mode_enabled(): raise OSError("You cannot use the USB VCP while the IDE is connected!")
     self.__usb_vcp.setinterrupt(-1)
     rpc_slave.__init__(self)
Exemplo n.º 23
0
#constants.py
"""Constants"""
__filename__="constants.py"

import micropython, pyb, math
from micropython import const
AREA_THRESHOLD = const(20)
PIXELS_THRESHOLD = const(20)

# This is a serial port object that allows you to
# communciate with your computer. While it is not open the code below runs.
usb_is_connected = pyb.USB_VCP().isconnected()

MAG_THRESHOLD = const(8)

DEG_120 = micropython.const(round(2 * math.pi / 3)) # 2PI/3 = 120º
DEG_240 = micropython.const(round(4 * math.pi / 3)) # 4PI/3 = 240º
RBG_MAX = micropython.const(97)
LED_TIMER_ID = micropython.const(4)
Exemplo n.º 24
0
# main.py -- put your code here!
from pyb import Timer, UART, ADC, Pin, ExtInt
import pyb
import time

# Virtual UART Port
ser = pyb.USB_VCP(0)

# Tracks the toggle state of the current device
dc_state1 = [0]
dc_state2 = [0]
dc_state3 = [0]
dc_state4 = [0]
sol_state = [0]

Pins = {
    # Manafold
    0: {
        0: {
            0:
            "(Timer(2, freq=850)).channel(3, Timer.PWM, pin=Pin('X3'))",  # PWM Pin
            1: Pin('X9', Pin.OUT_PP),  # Dir Pin
            2: Pin('X10', Pin.OUT_PP)  # ENA Pin
        }
    },
    # Spectroscopy
    1: {
        0: {
            0: "(Timer(2, freq=850)).channel(4, Timer.PWM, pin=Pin('X4'))",
            1: Pin('X11', Pin.OUT_PP),
            2: Pin('Y12', Pin.OUT_PP)
Exemplo n.º 25
0
        threshold5 = [(127, 255)]
    else:
        threshold5 = GRAYSCALE_THRESHOLDS

if COLOR_LINE_FOLLOWING:
    lineColor = (127, 127, 127)
else:
    lineColor = 127


if WRITE_FILE:
    f = uio.open("out.txt", "at")
else:
    f = None

usb = pyb.USB_VCP() # This is a serial port object that allows you to
# communciate with your computer. While it is not open the code below runs.
usb_is_connected = usb.isconnected()

line_lost_count = 0
delta_time = 0

start_time = pyb.millis()

i = 0
while i > -100:
    print(i)
    set_servos(i, 90)

    i = i - 1
Exemplo n.º 26
0
async def usb_keypad_emu():
    # Take keypresses on USB virtual serial port (when not in REPL mode)
    # and converts them into keypad events. Super handy for UX testing/dev.
    #
    # IMPORTANT: 
    # - code is **not** used in real product, but left here for devs to use
    # - this code isn't even called; unless you add code to do so, see ../stm32/my_lib_boot2.py
    #
    from ux import the_ux
    from menu import MenuSystem
    from seed import WordNestMenu

    u = pyb.USB_VCP()

    remap = {  '\r': 'y',
             '\x1b': 'x', 
           '\x1b[A': '5', 
           '\x1b[B': '8', 
           '\x1b[C': '9', 
           '\x1b[D': '7' }

    while 1:
        await sleep_ms(100)

        while u.isconnected() and u.any():
            from main import numpad

            k = u.read(3).decode()

            if k in '\x04':     # ^D
                # warm reset
                from machine import soft_reset
                soft_reset()

            if 0:
                if k == 'd':
                    numpad.debug = (numpad.debug + 1) % 3
                    continue

                if k == 'n':
                    if numpad.disabled:
                        numpad.start()
                    else:
                        numpad.stop()

                    print("npdis = %d" % numpad.disabled)
                    continue

            if k == 'U':
                # enter DFU
                import callgate
                callgate.enter_dfu()
                # not reached

            if k == 'T':
                ckcc.vcp_enabled(True)
                print("Repl enabled")
                continue

            if k == 'M':
                import gc
                print("Memory: %d" % gc.mem_free())
                continue

            # word menus: shortcut for first letter
            top = the_ux.top_of_stack()
            if top and isinstance(top, WordNestMenu) and len(top.items) > 6:
                pos = min(len(i.label) for i in top.items)
                if pos >= 2:
                    for n, it in enumerate(top.items):
                        if it.label[pos-2] == k:
                            top.goto_idx(n)
                            top.show()
                            k = None
                            break

                    if k is None: continue

            if k in remap:
                k = remap[k]

            if k in '0123456789xy':
                numpad.inject(k)
                continue
            
            print('? %r' % k)
    def turret_hub_fun(self):
        ''' Defines the task function method for a turret hub object.
        '''
        vcp = pyb.USB_VCP()

        STATE_0 = micropython.const(0)
        STATE_1 = micropython.const(1)
        STATE_2 = micropython.const(2)
        STATE_3 = micropython.const(3)
        STATE_4 = micropython.const(4)
        STATE_5 = micropython.const(5)

        self.state = STATE_0
        self.pan_coords.put(0)
        self.tilt_coords.put(0)

        while True:
            ## STATE 0: CALIBRATE GRID - POINT I

            if self.state == STATE_0:
                #                print(' calibration')

                if vcp.any():
                    self.GUI_input = float(vcp.read(2).decode('UTF-8'))
                    self.GUI_Lookup_Table(self.GUI_input)
#                    print(self.pan_position.get())
#                    print(self.tilt_angle.get())
                yield (self.state)

                if self.CALIBRATION_I_DONE:
                    #                    print(self.pan_position.get())
                    #                    print(self.tilt_angle.get())
                    self.state = STATE_1

            ## STATE 1: CALIBRATE GRID - POINT II
            elif self.state == STATE_1:
                if vcp.any():
                    self.GUI_input = float(vcp.read(2).decode('UTF-8'))
                    self.GUI_Lookup_Table(self.GUI_input)
                yield (self.state)

                if self.CALIBRATION_II_DONE:
                    #                    print(self.pan_position.get())
                    #                    print(self.tilt_angle.get())
                    self.state = STATE_2

            ## STATE 2: CALIBRATE GRID - POINT III
            elif self.state == STATE_2:
                if vcp.any():
                    self.GUI_input = float(vcp.read(2).decode('UTF-8'))
                    self.GUI_Lookup_Table(self.GUI_input)
                yield (self.state)

                if self.CALIBRATION_III_DONE:
                    print('Pan Calibration:')
                    print(self.I_location[0])
                    print(self.II_location[0])

                    self.pan_delta = (self.II_location[0] -
                                      self.I_location[0]) / 5
                    self.pan_centroids[
                        0] = self.I_location[0] + self.pan_delta / 2
                    self.pan_centroids[
                        1] = self.pan_centroids[0] + self.pan_delta
                    self.pan_centroids[
                        2] = self.pan_centroids[1] + self.pan_delta
                    self.pan_centroids[
                        3] = self.pan_centroids[2] + self.pan_delta
                    self.pan_centroids[
                        4] = self.pan_centroids[3] + self.pan_delta

                    print('Tilt Calibration:')
                    print(self.II_location[1])
                    print(self.III_location[1])

                    self.tilt_delta = (self.II_location[1] -
                                       self.III_location[1]) / 5
                    self.tilt_centroids[
                        0] = self.I_location[1] - self.tilt_delta / 2
                    self.tilt_centroids[
                        1] = self.tilt_centroids[0] - self.tilt_delta
                    self.tilt_centroids[
                        2] = self.tilt_centroids[1] - self.tilt_delta
                    self.tilt_centroids[
                        3] = self.tilt_centroids[2] - self.tilt_delta
                    self.tilt_centroids[
                        4] = self.tilt_centroids[3] - self.tilt_delta

                    print(self.pan_centroids)
                    print('\n')
                    print(self.tilt_centroids)
                    print(self.pan_position.get())
                    print(self.tilt_angle.get())
                    self.state = STATE_3

            ## STATE 3: STOPPED, NOT SHOOTING
            elif self.state == STATE_3:
                if vcp.any():
                    self.GUI_input = float(vcp.read(2).decode('UTF-8'))
                    self.GUI_Lookup_Table(self.GUI_input)
                yield (self.state)

                if self.TARGET_CMD:
                    self.WINDUP_GUN.put(1)
                    wind_time = utime.ticks_ms()
                    while (utime.ticks_ms() - wind_time) < 200:
                        yield (self.state)
                    self.FEED_BULLETS.put(1)
                    self.state = STATE_4

            ## STATE 4: MOVING, SHOOTING
            elif self.state == STATE_4:
                print(self.pan_completion.get())
                print(self.tilt_completion.get())

                if self.pan_completion.get(
                ) > 50.0 and self.tilt_completion.get() > 50.0:
                    # init the time for keeping track of how long to shoot
                    self.timer_init = utime.ticks_ms()
                    # clear the target cmd flag for state 1 next time
                    self.TARGET_CMD = False
                    self.state = STATE_5

            ## STATE 5: STOPPED, SHOOTING
            elif self.state == STATE_5:
                if (utime.ticks_ms() - self.timer_init) > self.timeout:
                    self.FEED_BULLETS.put(0)
                    # delay 1 second to wait for feeder to stop..
                    while (utime.ticks_ms() - self.timeout) < 1000:
                        yield (self.state)
                    self.WINDUP_GUN.put(0)
                    #                    self.timer_init = 0
                    self.state = STATE_3

            yield (self.state)
Exemplo n.º 28
0
async def usb_keypad_emu():
    # Take keypresses on USB virtual serial port (when not in REPL mode)
    # and converts them into keypad events. Super handy for UX testing/dev.
    #
    # IMPORTANT:
    # - code is **not** used in real product, but left here for devs to use
    # - this code isn't even called; unless you add code to do so.
    #
    u = pyb.USB_VCP()

    while 1:
        await sleep_ms(100)

        while u.isconnected() and u.any():
            from main import numpad

            k = u.read(3).decode()

            remap = {
                '\r': 'y',
                '\x1b': 'x',
                'q': 'x',
                '\x1b[A': '5',
                '\x1b[B': '8',
                '\x1b[C': '9',
                '\x1b[D': '7'
            }

            if k in remap: k = remap[k]

            if k in '\x04':  # ^D
                # warm reset
                from machine import soft_reset
                soft_reset()

            if k == 'T':
                numpad.debug = 2
                continue
            if k == 't':
                numpad.debug = 1
                continue
            if k == 'n':
                numpad.debug = 0
                continue
            if k == 'r':
                numpad.trigger_baseline = True
                continue
            if k == 's':
                numpad.sensitivity = (numpad.sensitivity + 1) % 3
                print("sensi = %d" % numpad.sensitivity)
                continue

            if k == 'U':
                # enter DFU
                import callgate
                callgate.enter_dfu()

            if k in '0123456789xy':
                numpad.inject(k)
            else:
                print('? %r' % k)
state_machine = None  # State machine object.

timer = Timer()  # Instantiate timer_array object.

event_queue = Event_queue()  # Instantiate event que object.

data_output_queue = Event_queue(
)  # Queue used for outputing events to serial line.

data_output = True  # Whether to output data to the serial line.

current_time = None  # Time since run started (milliseconds).

running = False  # Set to True when framework is running, set to False to stop run.

usb_serial = pyb.USB_VCP()  # USB serial port object.

states = {}  # Dictionary of {state_name: state_ID}

events = {}  # Dictionary of {event_name: event_ID}

ID2name = {}  # Dictionary of {ID: state_or_event_name}

clock = pyb.Timer(1)  # Timer which generates clock tick.

check_timers = False  # Flag to say timers need to be checked, set True by clock tick.

start_time = 0  # Time at which framework run is started.

# Framework functions ---------------------------------------------------------
Exemplo n.º 30
0
# Sensor settings
sensor.set_contrast(3)
sensor.set_gainceiling(16)
sensor.set_framesize(sensor.HQVGA)
sensor.set_pixformat(sensor.GRAYSCALE)

# Load Haar Cascade
# By default this will use all stages, lower satges is faster but less accurate.
face_cascade = image.HaarCascade("frontalface", stages=25)

# FPS clock
clock = time.clock()

# Setup UART
uart = pyb.USB_VCP()
pyb.enable_irq(True)
uart.setinterrupt(3)

while True:
    # Capture a snapshot
    img = sensor.snapshot()

    # detect objects
    try:
        # Find a face
        # HINT: Lower scale factor scales-down the image more and detects smaller objects.
        # Higher threshold results in a higher detection rate, with more false positives.
        faces = img.find_features(face_cascade, threshold=0.75, scale=1.25)
    except MemoryError:
        print('Out of memory during faces recnition!')