Example #1
0
def enable_usb(loop, repl_enable=False):
    # start it.
    cur = pyb.usb_mode()

    # allow/block REPL access
    ckcc.vcp_enabled(repl_enable)

    if cur:
        # We can't change it on the fly; must be disabled before here
        print("USB already enabled")
    else:
        # subclass, protocol, max packet length, polling interval, report descriptor
        hid_info = (0x0, 0x0, 64, 5, hid_descp)
        try:
            pyb.usb_mode('VCP+HID',
                         vid=COINKITE_VID,
                         pid=CKCC_PID,
                         hid=hid_info)
        except:
            assert False, 'bad usb mode'
            return

    global handler
    if loop and not handler:
        handler = USBHandler()
        loop.create_task(handler.usb_hid_recv())
Example #2
0
def set_usb_mode(dev=False, usb=False):
    if simulator:
        print("dev:", dev, ", usb:", usb)
    # now get correct mode
    if usb:  # and not dev:
        pyb.usb_mode("VCP")
        if not simulator:
            os.dupterm(None, 0)
            os.dupterm(None, 1)
    # elif usb and dev:
    #     pyb.usb_mode("VCP+MSC")
    #     if not simulator:
    #         # duplicate repl to stlink
    #         # as usb is busy for communication
    #         os.dupterm(stlk, 0)
    #         os.dupterm(None, 1)
    # elif not usb and dev:
    #     pyb.usb_mode("VCP+MSC")
    #     usb = pyb.USB_VCP()
    #     if not simulator:
    #         os.dupterm(None, 0)
    #         os.dupterm(usb, 1)
    else:
        pyb.usb_mode(None)
        if not simulator:
            os.dupterm(None, 0)
            os.dupterm(None, 1)
Example #3
0
def enable_usb():
    # We can't change it on the fly; must be disabled before here
    cur = pyb.usb_mode()
    if cur:
        print("USB already enabled: %s" % cur)
    else:
        # subclass, protocol, max packet length, polling interval, report descriptor
        hid_info = (0x0, 0x0, 64, 5, hid_descp)
        pyb.usb_mode('VCP+HID', vid=COINKITE_VID, pid=CKCC_PID, hid=hid_info)

    global handler
    if not handler:
        handler = USBHandler()
        from imptask import IMPT
        IMPT.start_task('USB', handler.usb_hid_recv())
Example #4
0
async def dev_enable_disk(*a):
    # Enable disk emulation, which allows them to change code.
    #
    cur = pyb.usb_mode()

    if cur and 'MSC' in cur:
        await ux_show_story("""The USB disk emulation is already enabled.""")
        return

    # serial port and disk (but no HID-based USB protocol)
    pyb.usb_mode(None)
    pyb.usb_mode('VCP+MSC')

    await ux_show_story("""\
The disk emulation has now been enabled. Your code can go into /lib. \
Keep tmp files and other junk out!""")
Example #5
0
async def dev_enable_protocol(*a):
    # Turn off disk emulation. Keep VCP enabled, since they are still devs.
    from main import loop

    cur = pyb.usb_mode()
    if cur and 'HID' in cur:
        await ux_show_story('Coldcard USB protocol is already enabled (HID mode)')
        return

    # might need to reset stuff?
    from usb import enable_usb

    # reset / re-enable
    pyb.usb_mode(None)
    enable_usb(loop, True)

    await ux_show_story('Back to normal USB mode.')
Example #6
0
 def run(self):
     while True:
         self._scan_matrix()
         if self.hid is not None:
             pyb.LED(1).on()
             self.hid.send(self.send_buf)
             pyb.LED(1).off()
         else:
             if 'HID' in pyb.usb_mode():
                 self.hid = pyb.USB_HID()
Example #7
0
    def set_it(idx, text):
        settings.set('du', idx)

        import pyb
        from usb import enable_usb, disable_usb
        cur = pyb.usb_mode()
        if cur and idx:
            # usb enabled, but should not be now
            disable_usb()
        elif not cur and not idx:
            # USB disabled, but now should be
            enable_usb()
Example #8
0
    def __init__(self):
        self.hid = pyb.USB_HID() if 'HID' in pyb.usb_mode() else None

        if self.hid is not None:
            _thread.start_new_thread(thread_entry, (self,))

        self.send_buf = bytearray(SEND_SIZE)
        self.recv_buf = bytearray(RECV_SIZE)

        self.fn = False
        self.row_pins = [pyb.Pin(x) for x in ROW_PINS]
        self.col_pins = [pyb.Pin(x) for x in COL_PINS]

        for row_pin in self.row_pins:
            row_pin.init(pyb.Pin.OUT_OD)
            row_pin.high()
        for col_pin in self.col_pins:
            col_pin.init(pyb.Pin.IN, pull=pyb.Pin.PULL_UP)
Example #9
0
async def dev_enable_vcp(*a):
    # Enable USB serial port emulation, for devs.
    #
    from usb import is_vcp_active

    if is_vcp_active():
        await ux_show_story("""The USB virtual serial port is already enabled.""")
        return

    was = pyb.usb_mode()
    pyb.usb_mode(None)
    if was and 'MSC' in was:
        pyb.usb_mode('VCP+MSC')
    else:
        pyb.usb_mode('VCP+HID')

    # allow REPL access
    ckcc.vcp_enabled(True)

    await ux_show_story("""\
The USB virtual serial port has now been enabled. Use a real computer to connect to it.""")
# boot.py -- run on boot-up
#
# This is some common initialization that I like to keep around.

import pyb
import micropython
import sys
#pyb.main('main.py') # main script to run after this one
before_mode = pyb.usb_mode()
pyb.usb_mode('CDC') # act as a serial only
after_mode = pyb.usb_mode()

#pyb.usb_mode('CDC+MSC') # act as a serial and a storage device
#pyb.usb_mode('CDC+HID') # act as a serial device and a mouse

def bl():
    pyb.bootloader()

def pins():
    for pin_name in dir(pyb.Pin.board):
        pin = pyb.Pin(pin_name)
        print('{:10s} {:s}'.format(pin_name, str(pin)))

def af():
    for pin_name in dir(pyb.Pin.board):
        pin = pyb.Pin(pin_name)
        print('{:10s} {:s}'.format(pin_name, str(pin.af_list())))

def init():
    if False:
        uart = pyb.UART(6,115200)
Example #11
0
import pyb
pyb.usb_mode('CDC+MSC')  # act as a serial and a storage device
pyb.main('ucode.py')  # main script to run after this one
Example #12
0
# boot.py -- run on boot-up
# can run arbitrary Python, but best to keep it minimal

import pyb
#pyb.main('main.py') # main script to run after this one
#pyb.usb_mode('CDC+MSC') # act as a serial and a storage device
pyb.usb_mode('CDC+HID')  # act as a serial device and a mouse
Example #13
0
# boot.py -- run on boot-up
# can run arbitrary Python, but best to keep it minimal

import pyb
import os, sys

#pyb.main('main.py') # main script to run after this one
#pyb.usb_mode('CDC+MSC') # act as a serial and a storage device
#pyb.usb_mode('CDC+HID') # act as a serial device and a mouse

if pyb.SDCard().present():
    pyb.usb_mode('VCP+MSC', msc=(pyb.SDCard(), ))  # expose SD card to the PC

    os.mount(pyb.SDCard(), '/sd')
    sys.path[1:1] = ['/sd', '/sd/lib']
    print("SD Mounted")

if pyb.SDCard().present():
    # Try starting from the SD card
    pyb.main('/sd/smain.py')  # main script to run after this one
    print("Started /sd/smain.py")
else:
    # If that fails (no SD card), start the flash
    pyb.main('/flash/main.py')  # main script to run after this one
    print("Started /flash/main.py")
Example #14
0
# boot.py -- run on boot-up
# can run arbitrary Python, but best to keep it minimal
import pyb

# pyb.main('main.py') # main script to run after this one
# pyb.usb_mode('VCP+MSC') # act as a serial and a storage device
# pyb.usb_mode('VCP+HID') # act as a serial device and a mouse

pyb.usb_mode('CDC')
pyb.main('main.py')

# pyb.usb_mode('CDC+MSC')
# pyb.main('cardreader.py')
# pyb.main('datalogger.py')
# pyb.main('main.py')
Example #15
0
# boot.py -- run on boot-up
import machine
import pyb
pyb.usb_mode('VCP') # act as a serial and not as a storage device
pyb.main('pulser_main.py')
Example #16
0
    except Exception as e:
        f = open('error.log', 'a')
        f.write(str(e.args))
        f.flush()
        f.close()

        for x in range(3):
            pyb.LED(3).toggle()
            pyb.delay(100)

    u.send("#DONE\n")
    return True


pyb.LED(3).on()
u = pyb.USB_VCP()
u.send(b"#READY TO UPLOAD\n", timeout=200)

while read_file():
    pass

if pyb.Switch()():
    pyb.usb_mode('CDC+MSC')  # act as a serial and a storage device
else:
    pyb.usb_mode('CDC+HID')  # act as a serial device and a mouse

os.sync()

pyb.LED(3).off()
Example #17
0
# boot.py -- runs on boot-up
# Let's you choose which script to run.
# > To run 'datalogger.py':
#       * press reset and do nothing else
# > To run 'cardreader.py':
#       * press reset
#       * press user switch and hold until orange LED goes out

import pyb

pyb.LED(3).on()  # indicate we are waiting for switch press
pyb.delay(2000)  # wait for user to maybe press the switch
switch_value = pyb.Switch()()  # sample the switch at end of delay
pyb.LED(3).off()  # indicate that we finished waiting for the switch

pyb.LED(4).on()  # indicate that we are selecting the mode

if switch_value:
    pyb.usb_mode("VCP+MSC")
    pyb.main("cardreader.py")  # if switch was pressed, run this
else:
    pyb.usb_mode("VCP+HID")
    pyb.main("datalogger.py")  # if switch wasn't pressed, run this

pyb.LED(4).off()  # indicate that we finished selecting the mode
Example #18
0
def is_vcp_active():
    # VCP = Virtual Comm Port
    en = ckcc.vcp_enabled(None)
    cur = pyb.usb_mode()

    return cur and ('VCP' in cur) and en
Example #19
0
# This file is executed on every boot (including wake-boot from deepsleep)
import machine
import uos as os

try:
    import esp

    esp.osdebug(None)
except:
    pass

try:
    import pyb

    pyb.country("US")  # ISO 3166-1 Alpha-2 code, eg US, GB, DE, AU
    pyb.usb_mode("VCP+MSC")  # act as a serial and a storage device
    # pyb.main('main.py') # main script to run after this one
    # pyb.usb_mode('VCP+HID') # act as a serial device and a mouse
except:
    pass

SD = False
if SD:
    # Mount SD to /sd
    try:
        # Some boards have pulldown and/or LED on GPIO2, pullup avoids issues on TTGO 8 v1.8
        # machine.Pin(2,mode=machine.Pin.IN, pull=machine.Pin.PULL_UP)
        # os.mount(machine.SDCard(slot=1, width=4), "/sd")  # SD mode 4 bit
        if esp:
            # # SPI 1 bit M5Stack Core
            os.mount(
Example #20
0
# boot.py -- run on boot-up
# can run arbitrary Python, but best to keep it minimal

import pyb
#pyb.main('main.py') # main script to run after this one
#pyb.usb_mode('CDC+MSC') # act as a serial and a storage device
#pyb.usb_mode('CDC+HID') # act as a serial device and a mouse

# Config for rapid C dev, DFU and debug
# Use USB port only for DFU and power
pyb.usb_mode(None)
# Configure REPL to use UART (and outside USB / Serial adapter)
# uart = pyb.UART(4, 9600)
uart = pyb.UART(4, 115200)
pyb.repl_uart(uart)
Example #21
0
# boot.py -- run on boot-up
# can run arbitrary Python, but best to keep it minimal

import pyb

pyb.usb_mode('CDC+MSC')

# pyb.main('quasar/quasar_main.py')  # main script to run after this on
# pyb.main('turret/turret_main.py')
# pyb.main("tests/lidar_turret_test.py")
pyb.main("tests/bno055_test.py")
# pyb.main("tests/gps_test.py")
# pyb.main("tests/stepper_test.py")
Example #22
0
import pyb

pyb.usb_mode('CDC+HID') # act as a serial and a mouse
Example #23
0
def log(t):
    """ A function for logging data from an MS5803 sensor to file at a regular interval.
    The function saves a line of text at each interval representing conductivity, temperature,
    pressure. The device then goes into standby mode for interval t.  After interval t, the
    device awakes as if from a hard reset.  The function is designed to be called from
    main.py. Puts device in standby mode upon completion.
    Parameters
    ----------
    t: int
        logging interval (seconds)
    
    Example
    -------
    To log data at 30 second intervals, save the following two lines as main.py
	
    >>> import logger_pres_temp as logger
    >>> logger.log(30)
	
    Note
    ----
    For more robust logging, the lines related to the watchdog timer can be enabled
    by removing the comments.  However, once the watchdog timer is set, it will automatically
    reset the board after the watchdog timer interval unless the timer is fed. This ensures
    that the board will continue to log even if an error is encountered, but it can
    cause unexpected results if the user wishes to interact with the board over serial.
    """ 
    
    #from machine import WDT
    #wdt = machine.WDT(timeout=30000)
    red = pyb.LED(1)
    green = pyb.LED(2)
    yellow = pyb.LED(3)
    blue = pyb.LED(4)
    
    green.on()
    blue.on()
    #wait 10 seconds to allow user to jump in
    time.sleep(10)
    green.off()
    blue.off()
    
    #write file header
    outputtxt = 'date,time,pressure(mbar),temperature(C)\r\n'
    try:
        f = open('datalogCTD.txt','a')
        f.write(outputtxt)
        f.close()
    except:
        #briefly turn all leds on if fails to write
        red.on()
        green.on()
        yellow.on()
        blue.on()
        time.sleep(1)
        red.off()
        green.off()
        blue.off()
        yellow.off()
    
    start_time = time.time()
    
    while True:

        try:
            wdt.feed()
        except:
            pass
                  
        #flash LED to let user know reading is being taken
        green.off()
        time.sleep(0.5)
        green.on()

        #define clock object, set next wakeup time (in milliseconds) and get the time
        rtc = pyb.RTC()
        datetime = rtc.datetime()
        log_time = start_time + t
        start_time = log_time

        try:
            wdt.feed()
        except:
            pass
            
        #define pressure sensor in Pressure.py.  Connect SCL to X9, SDA to X10, VCC to Y7, GND to Y8
        pres_power = Pin('Y7', Pin.OUT_PP)
        pres_gnd = Pin('Y8', Pin.OUT_PP)
        i2c = machine.I2C(scl='Y10', sda='Y9', freq = 100000)
                    
        #write header in textfile
        #headerline = 'YY/MM/DD,Hour:Min:Sec,count1,count2,r1,r2,temp,pressure\r\n'
        #f = open('datalogDuw.txt','a')
        #f.write(headerline)
        #f.close()

        #read values from sensors
        try:
            [pres, ctemp] = pressure.MS5803(i2c, pres_power, pres_gnd)
        except:
            pres = -999
            ctemp = -999
            print('Pressure reading failed')
            yellow.on()
            time.sleep(1)
            yellow.off()
        try:
            wdt.feed()
        except:
            pass
        
        #write results to file
        outputtxt = ('%s/%s/%s,%s:%s:%s,' % (datetime[0], datetime[1], datetime[2], datetime[4], datetime[5], datetime[6]))
        outputtxt += ('%s,%s\r\n' % (pres, ctemp))
        print (outputtxt)
        try:
            f = open('datalogCTD.txt','a')
            f.write(outputtxt)
            f.close()
        except:
            #briefly turn all leds on if fails to write
            red.on()
            green.on()
            yellow.on()
            blue.on()
            time.sleep(1)
            red.off()
            green.off()
            blue.off()
            yellow.off()
            
        sw = pyb.Switch()    
        while time.time() < log_time:    
            try:
                wdt.feed()
            except:
                pass          
            green.on()
            time.sleep(0.005)
            green.off()
            if sw():
                pyb.usb_mode(None)
                yellow.on()
                time.sleep(5)
                pyb.usb_mode('VCP+MSC')
                try:
                    wdt.feed()
                except:
                    pass
                break
            rtc.wakeup(2000)
            pyb.stop()
Example #24
0
def disable_usb():
    pyb.usb_mode(None)
Example #25
0
# boot.py -- run on boot-up
# can run arbitrary Python, but best to keep it minimal

import pyb

# Ucitavamo led
crvena = pyb.LED(1)             
plava = pyb.LED(4)
zuta = pyb.LED(3)


crvena.on()                     # Palimo led kao oznaku da cekamo da neko pritisne taster   
pyb.delay(2000)                 # Dajemo 2 sekunde da neko pritisne
switch_value = pyb.Switch()()   # Ocitavamo da li je pritisnuto
crvena.off()                    # Gasimo led da bi oznacili kraj izbora moda u kome radi

plava.on()                      # Oznaka da selektujemo mod   

if switch_value:
    #crvena.on()
    pyb.usb_mode('CDC+MSC')     # act as a serial and a storage device
    crvena.on()
    pyb.main('submain1.py')     # Skripta koja se izvrsava ako je taster bio pritisnut
else:
    zuta = pyb.LED(3)
    pyb.usb_mode('CDC+HID')     # act as a serial device and a mouse
    pyb.main('submain2.py')     # Skripta koja se izvrsava ako taster nije bio pritisnut

Example #26
0
    fail = True
    if 'uname' in dir(os):
        datestring = os.uname()[3]
        date = datestring.split(' on')[1]
        idate = tuple([int(x) for x in date.split('-')])
        fail = idate < tupTarget
    if fail:
        raise OSError(
            'This driver requires a firmware build dated {:4d}-{:02d}-{:02d} or later'
            .format(*tupTarget))


buildcheck((2016, 10, 1))  # y,m,d

usb_connected = False
if pyb.usb_mode() is not None:  # User has enabled CDC in boot.py
    usb_connected = pyb.Pin.board.USB_VBUS.value() == 1
    if not usb_connected:
        pyb.usb_mode(None)  # Save power

# CODE RUNS ON IMPORT **** END ****


def bounds(val, minval, maxval, msg):  # Bounds check
    if not (val >= minval and val <= maxval):
        raise ValueError(msg)


def singleton(cls):
    instances = {}
Example #27
0
    Adafruit Ultimate GPS
    Sparkfun Razor IMU
    XBee Pro with sparkfun breakout board
    210 RPM Gearmotor With 48 CPR Encoders
    md07a High-power Pololu Motor Drivers
    '''

################## Importing Necessary files ###############
import pyb
'''from pyb import UART
from pyboard_razor_IMU import Razor
from pyb import Pin
from micropyGPS import MicropyGPS
from motor import motor
import time
import math
'''
#Light Sequence Distinguishing setup is in progress
pyb.LED(3).on()
pyb.delay(2000)
pyb.LED(3).off()
pyb.LED(4).on()

# Running main.py after setup is finished
pyb.usb_mode(
    'CDC+MSC')  #Setup for quick diagnostic via usb cable to REPL prompt
pyb.main('main.py')  #Run the main process after boot has finished

#Indicate that setup has been completed
pyb.LED(4).off()
Example #28
0
# - main.loop is imported and "run forever" by boot.py, forced into place by COLDCARD/initfs code
# - cannot be changed by /flash/lib overrides, because already imported before that.
#

# see RAM_HEADER_BASE, and coldcardFirmwareHeader_t in sigheader.h
import pyb, sys, version, gc

# this makes the GC run when larger objects are free in an attempt to reduce fragmentation.
gc.threshold(4096)

if 0:
    # useful for debug: keep this stub!
    import ckcc
    ckcc.vcp_enabled(True)
    #pyb.usb_mode('VCP+MSC')            # handy but annoying disk issues
    pyb.usb_mode('VCP')
    raise SystemExit

# what firmware signing key did we boot with? are we in dev mode?
is_devmode = version.is_devmode()

if is_devmode:
    # For devs only: allow code in this directory to overide compiled-in stuff. Dangerous!
    # - using relative paths here so works better on simulator
    # - you must boot w/ non-production-signed firmware to get here
    sys.path.insert(0, 'flash/lib')

    # Give external devs a way to start stuff early
    try:
        import boot2
    except: pass
Example #29
0
# boot.py -- runs on boot-up
# Let's you choose which script to run.
# > To run 'datalogger.py':
#       * press reset and do nothing else
# > To run 'cardreader.py':
#       * press reset
#       * press user switch and hold until orange LED goes out

import pyb

pyb.LED(3).on()                 # indicate we are waiting for switch press
pyb.delay(2000)                 # wait for user to maybe press the switch
switch_value = pyb.Switch()()   # sample the switch at end of delay
pyb.LED(3).off()                # indicate that we finished waiting for the switch

pyb.LED(4).on()                 # indicate that we are selecting the mode

if switch_value:
    pyb.usb_mode('VCP+MSC')
    pyb.main('cardreader.py')           # if switch was pressed, run this
else:
    pyb.usb_mode('VCP+HID')
    pyb.main('datalogger.py')           # if switch wasn't pressed, run this

pyb.LED(4).off()                # indicate that we finished selecting the mode
Example #30
0
import pyb

from kmk.micropython.pyb_hid import generate_pyb_hid_descriptor

# act as a serial device and a KMK device
pyb.usb_mode('VCP+HID', hid=generate_pyb_hid_descriptor())
Example #31
0
# boot.py -- run on boot-up
# can run arbitrary Python, but best to keep it minimal

import pyb, sys
sys.path.append('/sd/bioloid3')
pyb.main('roz.py') # main script to run after this one
pyb.usb_mode('CDC') # act as a serial device
#pyb.usb_mode('CDC+MSC') # act as a serial and a storage device
#pyb.usb_mode('CDC+HID') # act as a serial device and a mouse
Example #32
0
# Copied from: https://github.com/turbinenreiter/micropython/blob/master/examples/SDdatalogger/boot.py

# boot.py -- runs on boot-up
# Let's you choose which script to run.
# > To run 'datalogger.py':
#       * press reset and do nothing else
# > To run 'cardreader.py':
#       * press reset
#       * press user switch and hold until orange LED goes out

import pyb

pyb.LED(3).on()  # indicate we are waiting for switch press
pyb.delay(2000)  # wait for user to maybe press the switch
switch_value = pyb.Switch()()  # sample the switch at end of delay
pyb.LED(3).off()  # indicate that we finished waiting for the switch

pyb.LED(4).on()  # indicate that we are selecting the mode

if switch_value:
    pyb.usb_mode('VCP+MSC')
    pyb.main('cardreader.py')  # if switch was pressed, run this
else:
    pyb.usb_mode('VCP+HID')
    pyb.main('datalogger.py')  # if switch wasn't pressed, run this

pyb.LED(4).off()  # indicate that we finished selecting the mode
Example #33
0
# boot.py -- run on boot-up
# can run arbitrary Python, but best to keep it minimal

import pyb

col1 = pyb.Pin('X9', pyb.Pin.IN, pyb.Pin.PULL_UP)
row1 = pyb.Pin('X19', pyb.Pin.OUT_PP)
row1.low()
pyb.delay(2000)

if not col1.value():
    pyb.usb_mode('CDC+MSC')
    pyb.main('unloop.py')           # if Escape pressed on boot, enable programming mode
else:
    pyb.main('main.py')
    pyb.usb_mode('CDC+HID', hid=pyb.hid_keyboard)

# main script to run after this one
# pyb.usb_mode('CDC+MSC') # act as a serial and a storage device
# pyb.usb_mode('CDC+HID') # act as a serial device and a mouse

Example #34
0
# boot.py -- run on boot-up
# can run arbitrary Python, but best to keep it minimal

import pyb

# main script to run after this one
pyb.main('main.py')

pyb.LED(3).on()
pyb.delay(1000)
usr_switch = pyb.Switch()()
pyb.LED(3).off()

if usr_switch:
    for _ in range(5):
        pyb.LED(3).on()
        pyb.delay(100)
        pyb.LED(3).off()
        pyb.delay(100)

    # act as a serial and a storage device
    pyb.usb_mode('VCP+MSC')
else:
    pyb.usb_mode('VCP')

# pyb.usb_mode('VCP+HID') # act as a serial device and a mouse
    if sw():
        while True:
            mode_led(mode)
            pyb.delay(500)
            if not sw():
                mode_led(-1)
                break
            mode = (mode + 1) % 3
        break

for i in range(3):
    mode_led(mode)
    pyb.delay(100)
    mode_led(-1)
    pyb.delay(100)

usb_mode = ('CDC+MSC', 'CDC+HID', 'CDC')[mode]
if mode != persisted_mode:
    with open('/flash/boot_mode.py', 'w') as f:
        f.write('mode = %d\n' % mode)
        f.write("usb_mode = '%s'\n" % usb_mode)
    pyb.sync()

pyb.usb_mode(usb_mode)
# Note: prints which occur before the call pyb.usb_mode() will not show on the
#       USB serial port.
print('usb_mode = %s' % usb_mode)

# Cleanup the namespace (since anything from boot.py shows up in the REPL)
del led, leds, mode, usb_mode, persisted_mode, i, sw, mode_led, boot_mode
Example #36
0
# boot.py -- runs on boot-up
# Let's you choose which script to run.
# > To run 'datalogger.py':
#       * press reset and do nothing else
# > To run 'cardreader.py':
#       * press reset
#       * press user switch and hold until orange LED goes out

import pyb

pyb.LED(3).on()  # indicate we are waiting for switch press
pyb.delay(2000)  # wait for user to maybe press the switch
switch_value = pyb.Switch()()  # sample the switch at end of delay
pyb.LED(3).off()  # indicate that we finished waiting for the switch

pyb.LED(4).on()  # indicate that we are selecting the mode

if switch_value:
    pyb.usb_mode('CDC+MSC')
    pyb.main('cardreader.py')  # if switch was pressed, run this
else:
    pyb.usb_mode('CDC+HID')
    pyb.main('datalogger.py')  # if switch wasn't pressed, run this

pyb.LED(4).off()  # indicate that we finished selecting the mode
Example #37
0
def enable_usb():
    pyb.usb_mode("VCP")
Example #38
0
# This file is executed on every boot (including wake-boot from deepsleep)
import micropython
import machine
import pyb
import gc

micropython.alloc_emergency_exception_buf(
    100)  # 设置紧急情况下的(栈溢出,普通RAM不足等)保险RAM分配,使在紧急情况下仍有RAM可用。
machine.freq(168000000)  # 设置CPU频率为168MHz
gc.enable()  # 自动回收内存碎片

pyb.main('main.py')

# https://docs.micropython.org/en/latest/library/pyb.html#pyb.usb_mode
pyb.usb_mode('VCP')  # 仅串口模式,默认串口加硬盘挂载'VCP+MSC'

print(pyb.usb_mode())
Example #39
0
# CODE RUNS ON IMPORT **** START ****

def buildcheck(tupTarget):
    fail = True
    if 'uname' in dir(os):
        datestring = os.uname()[3]
        date = datestring.split(' on')[1]
        idate = tuple([int(x) for x in date.split('-')])
        fail = idate < tupTarget
    if fail:
        raise OSError('This driver requires a firmware build dated {:4d}-{:02d}-{:02d} or later'.format(*tupTarget))

buildcheck((2016, 02, 11))                      # Version allows 32 bit write to stm register

usb_connected = False
if pyb.usb_mode() is not None:                  # User has enabled CDC in boot.py
    usb_connected = pyb.Pin.board.USB_VBUS.value() == 1
    if not usb_connected:
        pyb.usb_mode(None)                      # Save power

# CODE RUNS ON IMPORT **** END ****

def bounds(val, minval, maxval, msg):           # Bounds check
    if not (val >= minval and val <= maxval):
        raise ValueError(msg)

def singleton(cls):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
Example #40
0
# boot.py -- run on boot-up
# can run arbitrary Python, but best to keep it minimal

import pyb
pyb.main('main.py') # main script to run after this one
pyb.usb_mode('CDC+MSC') # act as a serial and a storage device
#pyb.usb_mode('CDC+HID') # act as a serial device and a mouse
Example #41
0
from os import uname
from rtc_time_cfg import enabled, disable_3v3, disable_leds

if not enabled:  # uasyncio traps this and uses utime
    raise ImportError('rtc_time is not enabled.')

# 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[:5] == '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).
if d_series:
Example #42
0
        # stop battery manangement
        if 112 in i2c.scan():
            i2c.mem_write(0, 112, 0)
        # sync filesystem
        os.sync()
        time.sleep_ms(300)
    finally:
        # disable power
        pwr.off()
    time.sleep_ms(300)
    # will never reach here
    for led in leds:
        led.toggle()


pyb.ExtInt(pyb.Pin('B1'), pyb.ExtInt.IRQ_FALLING, pyb.Pin.PULL_NONE, pwrcb)

# configure usb from start if you want,
# otherwise will be configured after PIN
# pyb.usb_mode("VCP+MSC") # debug mode with USB and mounted storages from start
# pyb.usb_mode("VCP") # debug mode with USB from start
# disable at start
pyb.usb_mode(None)
os.dupterm(None, 0)
os.dupterm(None, 1)

# inject version and i2c to platform module
import platform
platform.version = version
platform.i2c = i2c
Example #43
0
# boot.py -- run on boot-up
# can run arbitrary Python, but best to keep it minimal

import pyb
pyb.usb_mode('VCP')
pyb.main('main.py')