예제 #1
0
* Author(s): Tony DiCola
"""
import ustruct

from micropython import const

import adafruit_bus_device.i2c_device as i2c_device


__version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_MMA8451.git"


#pylint: disable=bad-whitespace
# Internal constants:
_MMA8451_DEFAULT_ADDRESS   = const(0x1D)
_MMA8451_REG_OUT_X_MSB     = const(0x01)
_MMA8451_REG_SYSMOD        = const(0x0B)
_MMA8451_REG_WHOAMI        = const(0x0D)
_MMA8451_REG_XYZ_DATA_CFG  = const(0x0E)
_MMA8451_REG_PL_STATUS     = const(0x10)
_MMA8451_REG_PL_CFG        = const(0x11)
_MMA8451_REG_CTRL_REG1     = const(0x2A)
_MMA8451_REG_CTRL_REG2     = const(0x2B)
_MMA8451_REG_CTRL_REG4     = const(0x2D)
_MMA8451_REG_CTRL_REG5     = const(0x2E)
_MMA8451_DATARATE_MASK     = const(0b111)
_SENSORS_GRAVITY_EARTH     = 9.80665

# External user-facing constants:
PL_PUF           = 0      # Portrait, up, front
예제 #2
0
파일: i2c.py 프로젝트: eiselekd/hw
* Author(s): Original Raspberry Pi code by Tony DiCola, CircuitPython by ladyada,
             refactor by Carter Nelson

"""

__version__ = "2.0.1"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_PN532.git"

import time
import adafruit_bus_device.i2c_device as i2c_device
from digitalio import Direction
from micropython import const
from adafruit_pn532.adafruit_pn532 import PN532, BusyError, _reset

# pylint: disable=bad-whitespace
_I2C_ADDRESS                   = const(0x24)

class PN532_I2C(PN532):
    """Driver for the PN532 connected over I2C."""
    def __init__(self, i2c, *, irq=None, reset=None, req=None, debug=False):
        """Create an instance of the PN532 class using I2C. Note that PN532
        uses clock stretching. Optional IRQ pin (not used),
        reset pin and debugging output.
        """
        self.debug = debug
        self._irq = irq
        self._req = req
        if reset:
            _reset(reset)
        self._i2c = i2c_device.I2CDevice(i2c, _I2C_ADDRESS)
        super().__init__(debug=debug, reset=reset)
예제 #3
0
* Author(s): Tony DiCola, Michael McWethy
"""

import time

from micropython import const
from adafruit_bus_device import i2c_device, spi_device
import framebuf

__version__ = "2.4.1"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_SSD1306.git"

#pylint: disable-msg=bad-whitespace
# register definitions
SET_CONTRAST        = const(0x81)
SET_ENTIRE_ON       = const(0xa4)
SET_NORM_INV        = const(0xa6)
SET_DISP            = const(0xae)
SET_MEM_ADDR        = const(0x20)
SET_COL_ADDR        = const(0x21)
SET_PAGE_ADDR       = const(0x22)
SET_DISP_START_LINE = const(0x40)
SET_SEG_REMAP       = const(0xa0)
SET_MUX_RATIO       = const(0xa8)
SET_COM_OUT_DIR     = const(0xc0)
SET_DISP_OFFSET     = const(0xd3)
SET_COM_PIN_CFG     = const(0xda)
SET_DISP_CLK_DIV    = const(0xd5)
SET_PRECHARGE       = const(0xd9)
SET_VCOM_DESEL      = const(0xdb)
예제 #4
0
# test constant optimisation

from micropython import const

X = const(123)
Y = const(X + 456)

print(X, Y + 1)

def f():
    print(X, Y + 1)

f()

_X = const(12)
_Y = const(_X + 34)

print(_X, _Y)

class A:
    Z = const(1)
    _Z = const(2)
    print(Z, _Z)

print(hasattr(A, 'Z'), hasattr(A, '_Z'))
예제 #5
0
    import struct
except ImportError:
    import ustruct as struct

from micropython import const

import adafruit_bus_device.i2c_device as i2c_device


__version__ = "1.2.1"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_MMA8451.git"


#pylint: disable=bad-whitespace
# Internal constants:
_MMA8451_DEFAULT_ADDRESS   = const(0x1D)
_MMA8451_REG_OUT_X_MSB     = const(0x01)
_MMA8451_REG_SYSMOD        = const(0x0B)
_MMA8451_REG_WHOAMI        = const(0x0D)
_MMA8451_REG_XYZ_DATA_CFG  = const(0x0E)
_MMA8451_REG_PL_STATUS     = const(0x10)
_MMA8451_REG_PL_CFG        = const(0x11)
_MMA8451_REG_CTRL_REG1     = const(0x2A)
_MMA8451_REG_CTRL_REG2     = const(0x2B)
_MMA8451_REG_CTRL_REG4     = const(0x2D)
_MMA8451_REG_CTRL_REG5     = const(0x2E)
_MMA8451_DATARATE_MASK     = const(0b111)
_SENSORS_GRAVITY_EARTH     = 9.80665

# External user-facing constants:
PL_PUF           = 0      # Portrait, up, front
예제 #6
0
* Adafruit CircuitPython firmware (2.2.0+) for the ESP8622 and M0-based boards:
  https://github.com/adafruit/circuitpython/releases

* Adafruit's Bus Device library: https://github.com/adafruit/Adafruit_CircuitPython_BusDevice
"""
try:
    import ustruct as struct
except ImportError:
    import struct

import adafruit_bus_device.i2c_device as i2c_dev
from micropython import const

# Register addresses and other constants:
# pylint: disable=bad-whitespace
_FXOS8700_ADDRESS               = const(0x1F)   # 0011111
_FXOS8700_ID                    = const(0xC7)   # 1100 0111
_FXOS8700_REGISTER_STATUS       = const(0x00)
_FXOS8700_REGISTER_OUT_X_MSB    = const(0x01)
_FXOS8700_REGISTER_OUT_X_LSB    = const(0x02)
_FXOS8700_REGISTER_OUT_Y_MSB    = const(0x03)
_FXOS8700_REGISTER_OUT_Y_LSB    = const(0x04)
_FXOS8700_REGISTER_OUT_Z_MSB    = const(0x05)
_FXOS8700_REGISTER_OUT_Z_LSB    = const(0x06)
_FXOS8700_REGISTER_WHO_AM_I     = const(0x0D)   # 11000111   r
_FXOS8700_REGISTER_XYZ_DATA_CFG = const(0x0E)
_FXOS8700_REGISTER_CTRL_REG1    = const(0x2A)   # 00000000   r/w
_FXOS8700_REGISTER_CTRL_REG2    = const(0x2B)   # 00000000   r/w
_FXOS8700_REGISTER_CTRL_REG3    = const(0x2C)   # 00000000   r/w
_FXOS8700_REGISTER_CTRL_REG4    = const(0x2D)   # 00000000   r/w
_FXOS8700_REGISTER_CTRL_REG5    = const(0x2E)   # 00000000   r/w
예제 #7
0
* Adafruit CircuitPython firmware for the ESP8622 and M0-based boards:
  https://github.com/adafruit/circuitpython/releases
* Adafruit's Bus Device library: https://github.com/adafruit/Adafruit_CircuitPython_BusDevice
"""

import time

import adafruit_bus_device.i2c_device as i2c_device
from micropython import const

__version__ = "2.0.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_VL53L0X.git"

# Register addresses.  Unused registers commented out to save memory.
# pylint: disable=bad-whitespace
MPR121_I2CADDR_DEFAULT = const(0x5A)
MPR121_TOUCHSTATUS_L   = const(0x00)
#MPR121_TOUCHSTATUS_H   = const(0x01)
MPR121_FILTDATA_0L     = const(0x04)
#MPR121_FILTDATA_0H     = const(0x05)
MPR121_BASELINE_0      = const(0x1E)
MPR121_MHDR            = const(0x2B)
MPR121_NHDR            = const(0x2C)
MPR121_NCLR            = const(0x2D)
MPR121_FDLR            = const(0x2E)
MPR121_MHDF            = const(0x2F)
MPR121_NHDF            = const(0x30)
MPR121_NCLF            = const(0x31)
MPR121_FDLF            = const(0x32)
MPR121_NHDT            = const(0x33)
MPR121_NCLT            = const(0x34)
예제 #8
0
from trezor.messages.TxRequestSerializedType import TxRequestSerializedType

from apps.common import address_type, coins
from apps.common.coininfo import CoinInfo
from apps.wallet.sign_tx.addresses import *
from apps.wallet.sign_tx.helpers import *
from apps.wallet.sign_tx.multisig import *
from apps.wallet.sign_tx.scripts import *
from apps.wallet.sign_tx.segwit_bip143 import Bip143, Bip143Error  # noqa:F401
from apps.wallet.sign_tx.overwinter_zip143 import Zip143, Zip143Error, OVERWINTERED  # noqa:F401
from apps.wallet.sign_tx.tx_weight_calculator import *
from apps.wallet.sign_tx.writers import *
from apps.wallet.sign_tx import progress

# the number of bip32 levels used in a wallet (chain and address)
_BIP32_WALLET_DEPTH = const(2)

# the chain id used for change
_BIP32_CHANGE_CHAIN = const(1)

# the maximum allowed change address.  this should be large enough for normal
# use and still allow to quickly brute-force the correct bip32 path
_BIP32_MAX_LAST_ELEMENT = const(1000000)


class SigningError(ValueError):
    pass


# Transaction signing
# ===
  https://github.com/adafruit/circuitpython/releases

* Adafruit's Bus Device library: https://github.com/adafruit/Adafruit_CircuitPython_BusDevice
"""

import time
from random import randint
from micropython import const
import adafruit_bus_device.spi_device
from adafruit_tinylora.adafruit_tinylora_encryption import AES

__version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_TinyLoRa.git"

# RFM Module Settings
_MODE_SLEEP = const(0x00)
_MODE_LORA = const(0x80)
_MODE_STDBY = const(0x01)
_MODE_TX = const(0x83)
_TRANSMIT_DIRECTION_UP = const(0x00)
# RFM Registers
_REG_PA_CONFIG = const(0x09)
_REG_PREAMBLE_MSB = const(0x20)
_REG_PREAMBLE_LSB = const(0x21)
_REG_FRF_MSB = const(0x06)
_REG_FRF_MID = const(0x07)
_REG_FRF_LSB = const(0x08)
_REG_FEI_LSB = const(0x1E)
_REG_FEI_MSB = const(0x1D)
_REG_MODEM_CONFIG = const(0x26)
_REG_PAYLOAD_LENGTH = const(0x22)
예제 #10
0
# Helpers for generating BLE advertising payloads.

from micropython import const
import struct
import bluetooth

# Advertising payloads are repeated packets of the following form:
#   1 byte data length (N + 1)
#   1 byte type (see constants below)
#   N bytes type-specific data

_ADV_TYPE_FLAGS = const(0x01)
_ADV_TYPE_NAME = const(0x09)
_ADV_TYPE_UUID16_COMPLETE = const(0x3)
_ADV_TYPE_UUID32_COMPLETE = const(0x5)
_ADV_TYPE_UUID128_COMPLETE = const(0x7)
_ADV_TYPE_UUID16_MORE = const(0x2)
_ADV_TYPE_UUID32_MORE = const(0x4)
_ADV_TYPE_UUID128_MORE = const(0x6)
_ADV_TYPE_APPEARANCE = const(0x19)


# Generate a payload to be passed to gap_advertise(adv_data=...).
def advertising_payload(limited_disc=False, br_edr=False, name=None, services=None, appearance=0):
    payload = bytearray()

    def _append(adv_type, value):
        nonlocal payload
        payload += struct.pack('BB', len(value) + 1, adv_type) + value

    _append(_ADV_TYPE_FLAGS, struct.pack('B', (0x01 if limited_disc else 0x02) + (0x00 if br_edr else 0x04)))
예제 #11
0
def split_message(message):
    chars_per_line = const(18)
    message = stringify_message(message)
    lines = chunks(message, chars_per_line)
    return lines
예제 #12
0
# Released under the MIT licence. Full text in root of this repository.

import gc
import uasyncio as asyncio
import time
gc.collect()
import ujson
from micropython import const
from machine import Pin, I2C
gc.collect()

from . import asi2c
from micropython_iot import client
gc.collect()

ID = const(0)  # Config list index
PORT = const(1)
SERVER = const(2)
TIMEOUT = const(3)
REPORT = const(4)
SSID = const(5)
PW = const(6)


class LinkClient(client.Client):
    def __init__(self, loop, config, swriter, verbose):
        super().__init__(loop,
                         config[ID],
                         config[SERVER],
                         config[PORT],
                         config[SSID],
예제 #13
0
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# pylint: disable=missing-docstring,invalid-name,too-many-public-methods,too-few-public-methods

from micropython import const

__version__ = "1.3.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_seesaw.git"

_ADC_INPUT_0_PIN = const(0x02)
_ADC_INPUT_1_PIN = const(0x03)
_ADC_INPUT_2_PIN = const(0x04)
_ADC_INPUT_3_PIN = const(0x05)

_PWM_0_PIN = const(0x04)
_PWM_1_PIN = const(0x05)
_PWM_2_PIN = const(0x06)
_PWM_3_PIN = const(0x07)

class SAMD09_Pinmap:
    analog_pins = (_ADC_INPUT_0_PIN, _ADC_INPUT_1_PIN,
                   _ADC_INPUT_2_PIN, _ADC_INPUT_3_PIN)

    pwm_width = 8
예제 #14
0
Example usage on pyboard:
    import pyb, sdcard, os
    sd = sdcard.SDCard(pyb.SPI(1), pyb.Pin.board.X5)
    pyb.mount(sd, '/sd2')
    os.listdir('/')
Example usage on ESP8266:
    import machine, sdcard, os
    sd = sdcard.SDCard(machine.SPI(1), machine.Pin(15))
    os.mount(sd, '/sd')
    os.listdir('/')
"""

from micropython import const
import time

_CMD_TIMEOUT = const(100)

_R1_IDLE_STATE = const(1 << 0)
#R1_ERASE_RESET = const(1 << 1)
_R1_ILLEGAL_COMMAND = const(1 << 2)
#R1_COM_CRC_ERROR = const(1 << 3)
#R1_ERASE_SEQUENCE_ERROR = const(1 << 4)
#R1_ADDRESS_ERROR = const(1 << 5)
#R1_PARAMETER_ERROR = const(1 << 6)
_TOKEN_CMD25 = const(0xfc)
_TOKEN_STOP_TRAN = const(0xfd)
_TOKEN_DATA = const(0xfe)


class SDCard:
    def __init__(self, spi, cs):
예제 #15
0
파일: cap1188.py 프로젝트: eiselekd/hw
**Software and Dependencies:**

* Adafruit CircuitPython firmware for the supported boards:
  https://github.com/adafruit/circuitpython/releases

* Adafruit's Bus Device library: https://github.com/adafruit/Adafruit_CircuitPython_BusDevice
"""

from micropython import const

__version__ = "1.1.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_CAP1188.git"

# pylint: disable=bad-whitespace
_CAP1188_MID                = const(0x5D)
_CAP1188_PID                = const(0x50)
_CAP1188_MAIN_CONTROL       = const(0x00)
_CAP1188_GENERAL_STATUS     = const(0x02)
_CAP1188_INPUT_STATUS       = const(0x03)
_CAP1188_LED_STATUS         = const(0x04)
_CAP1188_NOISE_FLAGS        = const(0x0A)
_CAP1188_DELTA_COUNT        =(const(0x10),
                              const(0x11),
                              const(0x12),
                              const(0x13),
                              const(0x14),
                              const(0x15),
                              const(0x16),
                              const(0x17))
_CAP1188_SENSITIVTY         = const(0x1F)
예제 #16
0
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

from micropython import const
from machine import Pin
from utime import sleep_us, sleep_ms

TM1637_CMD1 = const(64)  # 0x40 data command
TM1637_CMD2 = const(192) # 0xC0 address command
TM1637_CMD3 = const(128) # 0x80 display control command
TM1637_DSP_ON = const(8) # 0x08 display on
TM1637_DELAY = const(10) # 10us delay between clk/dio pulses
TM1637_MSB = const(128)  # msb is the decimal point or the colon depending on your display

# 0-9, a-z, blank, dash, star
_SEGMENTS = bytearray(b'\x3F\x06\x5B\x4F\x66\x6D\x7D\x07\x7F\x6F\x77\x7C\x39\x5E\x79\x71\x3D\x76\x06\x1E\x76\x38\x55\x54\x3F\x73\x67\x50\x6D\x78\x3E\x1C\x2A\x76\x6E\x5B\x00\x40\x63')

class TM1637(object):
    """Library for quad 7-segment LED modules based on the TM1637 LED driver."""
    def __init__(self, clk, dio, brightness=7):
        self.clk = clk
        self.dio = dio
예제 #17
0
# check that consts are not replaced in anything except standalone identifiers

from micropython import const

X = const(1)
Y = const(2)
Z = const(3)

# import that uses a constant
import micropython as X
print(globals()['X'])

# function name that matches a constant
def X():
    print('function X', X)
globals()['X']()

# arguments that match a constant
def f(X, *Y, **Z):
    pass
f(1)

# class name that matches a constant
class X:
    def f(self):
        print('class X', X)
globals()['X']().f()

# constant within a class
class A:
    C1 = const(4)
예제 #18
0
import micropython
micropython.opt_level(2)

import math
import time_location

PIXELS_PER_DEGREE = micropython.const(875.677409 / 2.9063) # calibrated from camera but doesn't really change the math
POLARIS_2000 = micropython.const([2, 31, 51.56, 89, 15, 51.5]) # obtained from Stellarium
POLARIS_2020 = micropython.const([2, 57, 39.08, 89, 20, 57.4]) # obtained from Stellarium

"""
The Earth's axis is very slowly wobbling
so the position of any star is very slowly moving
If you purchase a polar-scope, inside you will see that there's a ring for each year, and you line up Polaris with the ring corresponding to the current year

The code below will predict the new coordinate of Polaris according to the current date
It uses simple interpolation and transforms between coordinate systems
It accounts for leap years correctly
Testing of the code below shows that for the year 2024, the declination (the important part) is still accurate down to the arc second, and RA (not as important) is off by 0.8% (12 arc minutes)
"""

class PoleMovement(object):
    def __init__(self):
        ra2000, dec2000 = conv_ra_dec(POLARIS_2000)
        ra2020, dec2020 = conv_ra_dec(POLARIS_2020)
        self.x2000, self.y2000 = vector(ra2000, dec2000)
        self.x2020, self.y2020 = vector(ra2020, dec2020)
        self.jdn2000 = time_location.jdn(2000, 1, 1)
        self.jdn2020 = time_location.jdn(2020, 1, 1)
        dx = self.x2020 - self.x2000
        dy = self.y2020 - self.y2000
예제 #19
0
파일: apds9960.py 프로젝트: eiselekd/hw
"""
import time
import digitalio
from adafruit_register.i2c_bits import RWBits
from adafruit_register.i2c_bit import RWBit
from adafruit_bus_device.i2c_device import I2CDevice
from micropython import const


# ADDRESS_DEF = const(0x39)
# INTEGRATION_TIME_DEF = const(0x01)
# GAIN_DEF = const(0x01)

#pylint: disable-msg=bad-whitespace
#APDS9960_RAM        = const(0x00)
APDS9960_ENABLE     = const(0x80)
APDS9960_ATIME      = const(0x81)
#APDS9960_WTIME      = const(0x83)
#APDS9960_AILTIL     = const(0x84)
# APDS9960_AILTH      = const(0x85)
# APDS9960_AIHTL      = const(0x86)
# APDS9960_AIHTH      = const(0x87)
APDS9960_PILT       = const(0x89)
APDS9960_PIHT       = const(0x8B)
APDS9960_PERS       = const(0x8C)
# APDS9960_CONFIG1    = const(0x8D)
# APDS9960_PPULSE     = const(0x8E)
APDS9960_CONTROL    = const(0x8F)
# APDS9960_CONFIG2    = const(0x90)
APDS9960_ID         = const(0x92)
APDS9960_STATUS     = const(0x93)
예제 #20
0
# This program for an nRF52840 sends a one byte payload in a
# packet once every second.

from micropython import const
import machine  # so can peek and poke different registers on the nRF5x
import uctypes
import utime

radioBuffer = bytearray(100)  # allocate IO buffer for use by nRF5x radio
radioBuffer_address = uctypes.addressof(radioBuffer)

target_prefixAddress = const(0xAA)
target_baseAddress = const(0xDEADBEEF)

NRF_POWER = const(0x40000000)
DCDCEN = const(0x578)
NRF_POWER___DCDCEN = const(NRF_POWER + DCDCEN)

NRF_CLOCK = const(0x40000000)
TASKS_HFCLKSTART = const(0)
EVENTS_HFCLKSTARTED = const(0x100)
NRF_CLOCK___TASKS_HFCLKSTART = const(NRF_CLOCK + TASKS_HFCLKSTART)
NRF_CLOCK___EVENTS_HFCLKSTARTED = const(NRF_CLOCK + EVENTS_HFCLKSTARTED)

NRF_RADIO = const(0x40001000)
BASE0 = const(0x51C)
PREFIX0 = const(0x524)
FREQUENCY = const(0x508)
PCNF1 = const(0x518)
PCNF0 = const(0x514)
MODE = const(0x510)
예제 #21
0
# imports
try:
    import struct
except ImportError:
    import ustruct as struct

import time

from micropython import const
from adafruit_bus_device.i2c_device import I2CDevice

__version__ = "2.0.1"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_SHT31D.git"


SHT31_DEFAULT_ADDR = const(0x44)
SHT31_MEAS_HIGHREP_STRETCH = const(0x2C06)
SHT31_MEAS_MEDREP_STRETCH = const(0x2C0D)
SHT31_MEAS_LOWREP_STRETCH = const(0x2C10)
SHT31_MEAS_HIGHREP = const(0x2400)
SHT31_MEAS_MEDREP = const(0x240B)
SHT31_MEAS_LOWREP = const(0x2416)
SHT31_READSTATUS = const(0xF32D)
SHT31_CLEARSTATUS = const(0x3041)
SHT31_SOFTRESET = const(0x30A2)
SHT31_HEATEREN = const(0x306D)
SHT31_HEATERDIS = const(0x3066)


def _crc(data):
    crc = 0xff
예제 #22
0
from trezor.messages.MessageType import CardanoTxAck

from apps.cardano import CURVE, cbor, seed
from apps.cardano.address import (
    derive_address_and_node,
    is_safe_output_address,
    validate_full_path,
)
from apps.cardano.layout import confirm_sending, confirm_transaction, progress
from apps.common.paths import validate_path
from apps.common.seed import remove_ed25519_prefix
from apps.homescreen.homescreen import display_homescreen

# the maximum allowed change address.  this should be large enough for normal
# use and still allow to quickly brute-force the correct bip32 path
MAX_CHANGE_ADDRESS_INDEX = const(1000000)
ACCOUNT_PREFIX_DEPTH = const(2)

KNOWN_PROTOCOL_MAGICS = {764824073: "Mainnet", 1097911063: "Testnet"}


# we consider addresses from the external chain as possible change addresses as well
def is_change(output, inputs):
    for input in inputs:
        inp = input.address_n
        if (not output[:ACCOUNT_PREFIX_DEPTH] == inp[:ACCOUNT_PREFIX_DEPTH]
                or not output[-2] < 2
                or not output[-1] < MAX_CHANGE_ADDRESS_INDEX):
            return False
    return True
예제 #23
0
파일: st7735.py 프로젝트: eiselekd/hw
A simple driver for the ST7735-based displays.

* Author(s): Radomir Dopieralski, Michael McWethy
"""

try:
    import struct
except ImportError:
    import ustruct as struct
from micropython import const
from adafruit_rgb_display.rgb import DisplaySPI

__version__ = "3.1.1"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RGB_Display.git"

_NOP = const(0x00)
_SWRESET = const(0x01)
_RDDID = const(0x04)
_RDDST = const(0x09)

_SLPIN = const(0x10)
_SLPOUT = const(0x11)
_PTLON = const(0x12)
_NORON = const(0x13)

_INVOFF = const(0x20)
_INVON = const(0x21)
_DISPOFF = const(0x28)
_DISPON = const(0x29)
_CASET = const(0x2A)
_RASET = const(0x2B)
예제 #24
0
**Software and Dependencies:**

* Adafruit CircuitPython firmware for the ESP8622 and M0-based boards:
  https://github.com/adafruit/circuitpython/releases

"""
import time

from micropython import const

__version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_Thermal_Printer.git"

# pylint: disable=bad-whitespace
# Internally used constants.
_UPDOWN_MASK = const(1 << 2)
_BOLD_MASK = const(1 << 3)
_DOUBLE_HEIGHT_MASK = const(1 << 4)
_DOUBLE_WIDTH_MASK = const(1 << 5)
_STRIKE_MASK = const(1 << 6)

# External constants:
JUSTIFY_LEFT = const(0)
JUSTIFY_CENTER = const(1)
JUSTIFY_RIGHT = const(2)
SIZE_SMALL = const(0)
SIZE_MEDIUM = const(1)
SIZE_LARGE = const(2)
UNDERLINE_THIN = const(0)
UNDERLINE_THICK = const(1)
예제 #25
0
This is a CircuitPython driver for the Bosch BNO055 nine degree of freedom
inertial measurement unit module with sensor fusion.

* Author(s): Radomir Dopieralski
"""
import time

from micropython import const
from adafruit_bus_device.i2c_device import I2CDevice
from adafruit_register.i2c_struct import Struct, UnaryStruct

__version__ = "3.0.4"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_BNO055.git"

_CHIP_ID = const(0xa0)

CONFIG_MODE = const(0x00)
ACCONLY_MODE = const(0x01)
MAGONLY_MODE = const(0x02)
GYRONLY_MODE = const(0x03)
ACCMAG_MODE = const(0x04)
ACCGYRO_MODE = const(0x05)
MAGGYRO_MODE = const(0x06)
AMG_MODE = const(0x07)
IMUPLUS_MODE = const(0x08)
COMPASS_MODE = const(0x09)
M4G_MODE = const(0x0a)
NDOF_FMC_OFF_MODE = const(0x0b)
NDOF_MODE = const(0x0c)
예제 #26
0
class VCNL4040:  # pylint: disable=too-few-public-methods
    """Driver for the VCNL4040 proximity and ambient light sensor.

    :param busio.I2C i2c_bus: The I2C bus the VCNL4040 is connected to.

    """

    # Ambient light sensor integration times
    ALS_80MS = const(0x0)
    ALS_160MS = const(0x1)
    ALS_320MS = const(0x2)
    ALS_640MS = const(0x3)

    # Proximity sensor integration times
    PS_1T = const(0x0)
    PS_1_5T = const(0x1)
    PS_2T = const(0x2)
    PS_2_5T = const(0x3)
    PS_3T = const(0x4)
    PS_3_5T = const(0x5)
    PS_4T = const(0x6)
    PS_8T = const(0x7)

    # LED current settings
    LED_50MA = const(0x0)
    LED_75MA = const(0x1)
    LED_100MA = const(0x2)
    LED_120MA = const(0x3)
    LED_140MA = const(0x4)
    LED_160MA = const(0x5)
    LED_180MA = const(0x6)
    LED_200MA = const(0x7)

    # LED duty cycle settings
    LED_1_40 = const(0x0)
    LED_1_80 = const(0x1)
    LED_1_160 = const(0x2)
    LED_1_320 = const(0x3)

    # Proximity sensor interrupt enable/disable options
    PS_INT_DISABLE = const(0x0)
    PS_INT_CLOSE = const(0x1)
    PS_INT_AWAY = const(0x2)
    PS_INT_CLOSE_AWAY = const(0x3)

    # Offsets into interrupt status register for different types
    ALS_IF_L = const(0x0D)
    ALS_IF_H = const(0x0C)
    PS_IF_CLOSE = const(0x09)
    PS_IF_AWAY = const(0x08)

    # ID_LM - Device ID, address
    _device_id = UnaryStruct(0x0C, "<H")
    """The device ID."""

    # PS_Data_LM - PS output data
    proximity = ROUnaryStruct(0x08, "<H")
    """Proximity data.

    This example prints the proximity data. Move your hand towards the sensor to see the values
    change.

    .. code-block:: python

        import time
        import board
        import busio
        import adafruit_vcnl4040

        i2c = busio.I2C(board.SCL, board.SDA)
        sensor = adafruit_vcnl4040.VCNL4040(i2c)

        while True:
            print("Proximity:", sensor.proximity)
            time.sleep(0.1)
    """

    # PS_CONF1 - PS duty ratio, integration time, persistence, enable/disable
    # PS_CONF2 - PS output resolution selection, interrupt trigger method
    # PS_CONF3 - PS smart persistence, active force mode
    proximity_shutdown = RWBit(0x03, 0, register_width=2)
    """Proximity sensor shutdown. When ``True``, proximity data is disabled."""
    proximity_integration_time = RWBits(3, 0x03, 1, register_width=2)
    """Proximity sensor integration time setting. Integration times are 1T, 1.5T, 2T, 2.5T, 3T,
    3.5T, 4T, and 8T. Options are: PS_1T, PS_1_5T, PS_2T, PS_2_5T, PS_3T, PS_3_5T, PS_4T, PS_8T.
    """
    proximity_interrupt = RWBits(2, 0x03, 8, register_width=2)
    """Interrupt enable. Interrupt setting are close, away, close and away, or disabled. Options
    are: PS_INT_DISABLE, PS_INT_CLOSE, PS_INT_AWAY, PS_INT_CLOSE_AWAY."""
    proximity_bits = RWBit(0x03, 11, register_width=2)
    """Proximity data output setting. ``0`` when proximity sensor output is 12 bits, ``1`` when
    proximity sensor output is 16 bits."""

    # PS_THDL_LM - PS low interrupt threshold setting
    proximity_low_threshold = UnaryStruct(0x06, "<H")
    """Proximity sensor interrupt low threshold setting."""
    # PS_THDH_LM - PS high interrupt threshold setting
    proximity_high_threshold = UnaryStruct(0x07, "<H")
    """Proximity sensor interrupt high threshold setting."""

    interrupt_state = ROUnaryStruct(0x0B, "<H")

    # INT_FLAG - PS interrupt flag
    @property
    def proximity_high_interrupt(self):
        """If interrupt is set to ``PS_INT_CLOSE`` or ``PS_INT_CLOSE_AWAY``, trigger event when
        proximity rises above high threshold interrupt."""
        return self._get_and_clear_cached_interrupt_state(self.PS_IF_CLOSE)

    @property
    def proximity_low_interrupt(self):
        """If interrupt is set to ``PS_INT_AWAY`` or ``PS_INT_CLOSE_AWAY``, trigger event when
        proximity drops below low threshold."""
        return self._get_and_clear_cached_interrupt_state(self.PS_IF_AWAY)

    led_current = RWBits(3, 0x04, 8, register_width=2)
    """LED current selection setting, in mA. Options are LED_50MA, LED_75MA, LED_100MA, LED_120MA,
    LED_140MA, LED_160MA, LED_180MA, LED_200MA."""

    led_duty_cycle = RWBits(2, 0x03, 6, register_width=2)
    """Proximity sensor LED duty ratio setting. Ratios are 1/40, 1/80, 1/160, and 1/320. Options
    are: LED_1_40, LED_1_80, LED_1_160, LED_1_320."""

    light = ROUnaryStruct(0x09, "<H")
    """Raw ambient light data. The raw ambient light data which will change with integration time
    and gain settings changes. Use ``lux`` to get the correctly scaled value for the current
    integration time and gain settings
    """

    @property
    def lux(self):
        """Ambient light data in lux. Represents the raw sensor data scaled according to the current
        integration time and gain settings.

        This example prints the ambient light data. Cover the sensor to see the values change.

        .. code-block:: python

            import time
            import board
            import busio
            import adafruit_vcnl4040

            i2c = busio.I2C(board.SCL, board.SDA)
            sensor = adafruit_vcnl4040.VCNL4040(i2c)

            while True:
                print("Ambient light: %.2f lux"%sensor.lux)
                time.sleep(0.1)
        """
        return self.light * (0.1 / (1 << self.light_integration_time))

    # ALS_CONF - ALS integration time, persistence, interrupt, function enable/disable
    light_shutdown = RWBit(0x00, 0, register_width=2)
    """Ambient light sensor shutdown. When ``True``, ambient light data is disabled."""

    _light_integration_time = RWBits(2, 0x00, 6, register_width=2)

    @property
    def light_integration_time(self):
        """Ambient light sensor integration time setting. Longer time has higher sensitivity.
        Can be: ALS_80MS, ALS_160MS, ALS_320MS or ALS_640MS.

        This example sets the ambient light integration time to 640ms and prints the ambient light
        sensor data.

        .. code-block:: python

            import time
            import board
            import busio
            import adafruit_vcnl4040

            i2c = busio.I2C(board.SCL, board.SDA)
            sensor = adafruit_vcnl4040.VCNL4040(i2c)

            sensor.light_integration_time = sensor.ALS_640MS

            while True:
                print("Ambient light:", sensor.light)
        """
        return self._light_integration_time

    @light_integration_time.setter
    def light_integration_time(self, new_it):
        from time import sleep  # pylint: disable=import-outside-toplevel

        # IT values are in 0-3 -> 80-640ms
        old_it_ms = (8 << self._light_integration_time) * 10
        new_it_ms = (8 << new_it) * 10
        it_delay_seconds = (old_it_ms + new_it_ms + 1) * 0.001

        self._light_integration_time = new_it
        sleep(it_delay_seconds)

    light_interrupt = RWBit(0x00, 1, register_width=2)
    """Ambient light sensor interrupt enable. ``True`` to enable, and ``False`` to disable."""

    # ALS_THDL_LM - ALS low interrupt threshold setting
    light_low_threshold = UnaryStruct(0x02, "<H")
    """Ambient light interrupt low threshold."""
    # ALS_THDH_LM - ALS high interrupt threshold setting
    light_high_threshold = UnaryStruct(0x01, "<H")
    """Ambient light interrupt high threshold."""
    # INT_FLAG - ALS interrupt flag

    @property
    def light_high_interrupt(self):
        """High interrupt event. Triggered when ambient light value exceeds high threshold."""
        return self._get_and_clear_cached_interrupt_state(self.ALS_IF_H)

    @property
    def light_low_interrupt(self):
        """Low interrupt event. Triggered when ambient light value drops below low threshold."""
        return self._get_and_clear_cached_interrupt_state(self.ALS_IF_L)

    _raw_white = ROUnaryStruct(0x0A, "<H")

    @property
    def white(self):
        """White light data scaled according to the current integration time and gain settings.

        This example prints the white light data. Cover the sensor to see the values change.

        .. code-block:: python

            import time
            import board
            import busio
            import adafruit_vcnl4040

            i2c = busio.I2C(board.SCL, board.SDA)
            sensor = adafruit_vcnl4040.VCNL4040(i2c)

            while True:
                print("White light:", sensor.white)
                time.sleep(0.1)
        """
        return self._raw_white * (0.1 / (1 << self.light_integration_time))

    # PS_MS - White channel enable/disable, PS mode, PS protection setting, LED current
    # White_EN - PS_MS_H, 7th bit - White channel enable/disable
    white_shutdown = RWBit(0x04, 15, register_width=2)
    """White light channel shutdown. When ``True``, white light data is disabled."""

    def __init__(self, i2c, address=0x60):
        self.i2c_device = i2cdevice.I2CDevice(i2c, address)
        if self._device_id != 0x186:
            raise RuntimeError("Failed to find VCNL4040 - check wiring!")

        self.cached_interrupt_state = {
            self.ALS_IF_L: False,
            self.ALS_IF_H: False,
            self.PS_IF_CLOSE: False,
            self.PS_IF_AWAY: False,
        }

        self.proximity_shutdown = False
        self.light_shutdown = False
        self.white_shutdown = False

    def _update_interrupt_state(self):
        interrupts = [
            self.PS_IF_AWAY, self.PS_IF_CLOSE, self.ALS_IF_H, self.ALS_IF_L
        ]
        new_interrupt_state = self.interrupt_state
        for interrupt in interrupts:
            new_state = new_interrupt_state & (1 << interrupt) > 0
            if new_state:
                self.cached_interrupt_state[interrupt] = new_state

    def _get_and_clear_cached_interrupt_state(self, interrupt_offset):
        self._update_interrupt_state()
        new_interrupt_state = self.cached_interrupt_state[interrupt_offset]
        self.cached_interrupt_state[interrupt_offset] = False

        return new_interrupt_state
예제 #27
0
# Driver for official MicroPython LCD160CR display
# MIT license; Copyright (c) 2017 Damien P. George

from micropython import const
from utime import sleep_ms
from ustruct import calcsize, pack_into
import uerrno, machine

# for set_orient
PORTRAIT = const(0)
LANDSCAPE = const(1)
PORTRAIT_UPSIDEDOWN = const(2)
LANDSCAPE_UPSIDEDOWN = const(3)

# for set_startup_deco; can be or'd
STARTUP_DECO_NONE = const(0)
STARTUP_DECO_MLOGO = const(1)
STARTUP_DECO_INFO = const(2)

_uart_baud_table = {
    2400: 0,
    4800: 1,
    9600: 2,
    19200: 3,
    38400: 4,
    57600: 5,
    115200: 6,
    230400: 7,
    460800: 8,
}
예제 #28
0
====================================================

CircuitPython module for the DRV2605 haptic feedback motor driver.  See
examples/simpletest.py for a demo of the usage.

* Author(s): Tony DiCola
"""
from micropython import const

from adafruit_bus_device.i2c_device import I2CDevice

__version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_DRV2605.git"

# Internal constants:
_DRV2605_ADDR = const(0x5A)
_DRV2605_REG_STATUS = const(0x00)
_DRV2605_REG_MODE = const(0x01)
_DRV2605_REG_RTPIN = const(0x02)
_DRV2605_REG_LIBRARY = const(0x03)
_DRV2605_REG_WAVESEQ1 = const(0x04)
_DRV2605_REG_WAVESEQ2 = const(0x05)
_DRV2605_REG_WAVESEQ3 = const(0x06)
_DRV2605_REG_WAVESEQ4 = const(0x07)
_DRV2605_REG_WAVESEQ5 = const(0x08)
_DRV2605_REG_WAVESEQ6 = const(0x09)
_DRV2605_REG_WAVESEQ7 = const(0x0A)
_DRV2605_REG_WAVESEQ8 = const(0x0B)
_DRV2605_REG_GO = const(0x0C)
_DRV2605_REG_OVERDRIVE = const(0x0D)
_DRV2605_REG_SUSTAINPOS = const(0x0E)
예제 #29
0
  <https://www.adafruit.com/product/935>`_ (Product ID: 935)

**Software and Dependencies:**

* Adafruit CircuitPython firmware for the ESP8622 and M0-based boards:
  https://github.com/adafruit/circuitpython/releases
"""
from micropython import const

__version__ = "1.1.1"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_MCP4725.git"


# Internal constants:
_MCP4725_DEFAULT_ADDRESS = 0b01100010
_MCP4725_WRITE_FAST_MODE = const(0b00000000)


class MCP4725:
    """
    MCP4725 12-bit digital to analog converter.  This class has a similar
    interface as the CircuitPython AnalogOut class and can be used in place
    of that module.

    :param ~busio.I2C i2c: The I2C bus.
    :param int address: The address of the device if set differently from the default.
    """


    # Global buffer to prevent allocations and heap fragmentation.
    # Note this is not thread-safe or re-entrant by design!
예제 #30
0
from micropython import const

from trezor.crypto import base58

from apps.common import HARDENED
from apps.common.writers import write_bytes_unchecked, write_uint8

TEZOS_AMOUNT_DECIMALS = const(6)
TEZOS_ED25519_ADDRESS_PREFIX = "tz1"
TEZOS_ORIGINATED_ADDRESS_PREFIX = "KT1"
TEZOS_PUBLICKEY_PREFIX = "edpk"
TEZOS_SIGNATURE_PREFIX = "edsig"
TEZOS_PREFIX_BYTES = {
    # addresses
    "tz1": b"\x06\xa1\x9f",  # 06a19f
    "tz2": b"\x06\xa1\xa1",  # 06a1a1
    "tz3": b"\x06\xa1\xa4",  # 06a1a4
    "KT1": b"\x02Zy",  # 025a79
    # public keys
    "edpk": b"\r\x0f%\xd9",  # 0d0f25d9
    # signatures
    "edsig": b"\t\xf5\xcd\x86\x12",  # 09f5cd8612
    # operation hash
    "o": b"\x05t",  # 0574
    # protocol hash
    "P": b"\x02\xaa",  # 02aa
}

MICHELSON_INSTRUCTION_BYTES = {
    "DROP":
    b"\x03 ",  # 0320
예제 #31
0
* Adafruit's Bus Device library: https://github.com/adafruit/Adafruit_CircuitPython_BusDevice
"""
import time

from micropython import const

import adafruit_bus_device.spi_device as spidev


__version__ = "1.2.3"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RFM69.git"


# pylint: disable=bad-whitespace
# Internal constants:
_REG_FIFO            = const(0x00)
_REG_OP_MODE         = const(0x01)
_REG_DATA_MOD        = const(0x02)
_REG_BITRATE_MSB     = const(0x03)
_REG_BITRATE_LSB     = const(0x04)
_REG_FDEV_MSB        = const(0x05)
_REG_FDEV_LSB        = const(0x06)
_REG_FRF_MSB         = const(0x07)
_REG_FRF_MID         = const(0x08)
_REG_FRF_LSB         = const(0x09)
_REG_VERSION         = const(0x10)
_REG_PA_LEVEL        = const(0x11)
_REG_RX_BW           = const(0x19)
_REG_AFC_BW          = const(0x1A)
_REG_RSSI_VALUE      = const(0x24)
_REG_DIO_MAPPING1    = const(0x25)
예제 #32
0
# This example finds and connects to a BLE temperature sensor (e.g. the one in ble_temperature.py).

import bluetooth
import random
import struct
import time
import micropython

from ble_advertising import decode_services, decode_name

from micropython import const

_IRQ_CENTRAL_CONNECT = const(1)
_IRQ_CENTRAL_DISCONNECT = const(2)
_IRQ_GATTS_WRITE = const(3)
_IRQ_GATTS_READ_REQUEST = const(4)
_IRQ_SCAN_RESULT = const(5)
_IRQ_SCAN_DONE = const(6)
_IRQ_PERIPHERAL_CONNECT = const(7)
_IRQ_PERIPHERAL_DISCONNECT = const(8)
_IRQ_GATTC_SERVICE_RESULT = const(9)
_IRQ_GATTC_SERVICE_DONE = const(10)
_IRQ_GATTC_CHARACTERISTIC_RESULT = const(11)
_IRQ_GATTC_CHARACTERISTIC_DONE = const(12)
_IRQ_GATTC_DESCRIPTOR_RESULT = const(13)
_IRQ_GATTC_DESCRIPTOR_DONE = const(14)
_IRQ_GATTC_READ_RESULT = const(15)
_IRQ_GATTC_READ_DONE = const(16)
_IRQ_GATTC_WRITE_DONE = const(17)
_IRQ_GATTC_NOTIFY = const(18)
_IRQ_GATTC_INDICATE = const(19)
예제 #33
0
파일: s6d02a1.py 프로젝트: eiselekd/hw
"""
`adafruit_rgb_display.s6d02a1`
====================================================

A simple driver for the S6D02A1-based displays.

* Author(s): Radomir Dopieralski, Michael McWethy
"""

from micropython import const
from adafruit_rgb_display.rgb import DisplaySPI

__version__ = "3.1.1"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RGB_Display.git"

_SWRESET = const(0x01)
_DISPON = const(0x29)
_SLEEPOUT = const(0x11)
_CASET = const(0x2a)
_PASET = const(0x2b)
_RAMWR = const(0x2c)
_RAMRD = const(0x2e)
_COLMOD = const(0x3a)
_MADCTL = const(0x36)

class S6D02A1(DisplaySPI):
    """
    A simple driver for the S6D02A1-based displays.

    >>> import busio
    >>> import digitalio
예제 #34
0
파일: lvM5.py 프로젝트: tialm/m5LvglFiles
from ili9341 import ili9341

from micropython import const

BUTTON_A_PIN = const(39)
BUTTON_B_PIN = const(38)
BUTTON_C_PIN = const(37)


class M5Ili(ili9341):
    def __init__(self, hybrid=True, double_buffer=False):
        self.disp = ili9341(miso=19,
                            mosi=23,
                            clk=18,
                            cs=14,
                            dc=27,
                            rst=33,
                            backlight=32,
                            power=-1,
                            power_on=-1,
                            backlight_on=1,
                            mhz=40,
                            factor=4,
                            hybrid=hybrid,
                            width=320,
                            height=240,
                            colormode=ili9341.COLOR_MODE_BGR,
                            rot=ili9341.MADCTL_ML,
                            invert=False,
                            double_buffer=double_buffer)
예제 #35
0
__version__ = "2.0.1"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_l3gd20.git"


from micropython import const
from adafruit_register.i2c_struct import Struct
try:
    from struct import unpack
except ImportError:
    from ustruct import unpack

__version__ = "2.0.1"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_L3GD20.git"

L3DS20_RANGE_250DPS = const(0)
L3DS20_RANGE_500DPS = const(1)
L3DS20_RANGE_2000DPS = const(2)

_L3GD20_REGISTER_CTRL_REG1 = const(0x20)
_L3GD20_REGISTER_CTRL_REG4 = const(0x23)

# _L3GD20_REGISTER_OUT_X_L = const(0x28)
_L3GD20_REGISTER_OUT_X_L_X80 = const(0xA8)
_L3GD20_REGISTER_OUT_X_L_X40 = const(0x68)

_ID_REGISTER = const(0x0F)

_L3GD20_CHIP_ID = const(0xD4)
_L3GD20H_CHIP_ID = const(0xD7)
예제 #36
0
uart.start()
"""

__version__ = "1.0.0"

import struct

import bluetooth
from micropython import const

# Advertising payloads are repeated packets of the following form:
#   1 byte data length (N + 1)
#   1 byte type (see constants below)
#   N bytes type-specific data

_ADV_TYPE_FLAGS = const(0x01)
_ADV_TYPE_NAME = const(0x09)
_ADV_TYPE_UUID16_COMPLETE = const(0x3)
_ADV_TYPE_UUID32_COMPLETE = const(0x5)
_ADV_TYPE_UUID128_COMPLETE = const(0x7)
_ADV_TYPE_UUID16_MORE = const(0x2)
_ADV_TYPE_UUID32_MORE = const(0x4)
_ADV_TYPE_UUID128_MORE = const(0x6)
_ADV_TYPE_APPEARANCE = const(0x19)


# Generate a payload to be passed to gap_advertise(adv_data=...).
def advertising_payload(limited_disc=False,
                        br_edr=False,
                        name=None,
                        services=None,
예제 #37
0
See:
    STM32Cube_FW_F4_V1.1.0/Drivers/BSP/Components/lis302dl/lis302dl.h
    STM32Cube_FW_F4_V1.1.0/Drivers/BSP/Components/lis302dl/lis302dl.c
    STM32Cube_FW_F4_V1.1.0/Drivers/BSP/STM32F4-Discovery/stm32f4_discovery.c
    STM32Cube_FW_F4_V1.1.0/Drivers/BSP/STM32F4-Discovery/stm32f4_discovery.h
    STM32Cube_FW_F4_V1.1.0/Drivers/BSP/STM32F4-Discovery/stm32f4_discovery_accelerometer.c
    STM32Cube_FW_F4_V1.1.0/Drivers/BSP/STM32F4-Discovery/stm32f4_discovery_accelerometer.h
    STM32Cube_FW_F4_V1.1.0/Projects/STM32F4-Discovery/Demonstrations/Src/main.c
"""

from micropython import const
from pyb import Pin
from pyb import SPI

READWRITE_CMD = const(0x80) 
MULTIPLEBYTE_CMD = const(0x40)
WHO_AM_I_ADDR = const(0x0f)
OUT_X_ADDR = const(0x29)
OUT_Y_ADDR = const(0x2b)
OUT_Z_ADDR = const(0x2d)
OUT_T_ADDR = const(0x0c)

LIS302DL_WHO_AM_I_VAL = const(0x3b)
LIS302DL_CTRL_REG1_ADDR = const(0x20)
# Configuration for 100Hz sampling rate, +-2g range
LIS302DL_CONF = const(0b01000111)

LIS3DSH_WHO_AM_I_VAL = const(0x3f)
LIS3DSH_CTRL_REG4_ADDR = const(0x20)
LIS3DSH_CTRL_REG5_ADDR = const(0x24)
예제 #38
0
파일: stepper.py 프로젝트: 0xFF1E071F/hw
* Author(s): Tony DiCola, Scott Shawcroft
"""

import math

from micropython import const

__version__ = "1.3.3"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_Motor.git"

# Stepper Motor Shield/Wing Driver
# Based on Adafruit Motorshield library:
# https://github.com/adafruit/Adafruit_Motor_Shield_V2_Library

# Constants that specify the direction and style of steps.
FORWARD = const(1)
"""Step forward"""
BACKWARD = const(2)
""""Step backward"""
SINGLE = const(1)
"""Step so that each step only activates a single coil"""
DOUBLE = const(2)
"""Step so that each step only activates two coils to produce more torque."""
INTERLEAVE = const(3)
"""Step half a step to alternate between single coil and double coil steps."""
MICROSTEP = const(4)
"""Step a fraction of a step by partially activating two neighboring coils. Step size is determined
   by ``microsteps`` constructor argument."""

class StepperMotor:
    """A bipolar stepper motor or four coil unipolar motor.
예제 #39
0
* Adafruit's Bus Device library: https://github.com/adafruit/Adafruit_CircuitPython_BusDevice
"""
import time
try:
    import ustruct as struct
except ImportError:
    import struct

import adafruit_bus_device.i2c_device as i2c_dev
from micropython import const


# Internal constants and register values:
# pylint: disable=bad-whitespace
_FXAS21002C_ADDRESS       = const(0x21)  # 0100001
_FXAS21002C_ID            = const(0xD7)       # 1101 0111
_GYRO_REGISTER_STATUS     = const(0x00)
_GYRO_REGISTER_OUT_X_MSB  = const(0x01)
_GYRO_REGISTER_OUT_X_LSB  = const(0x02)
_GYRO_REGISTER_OUT_Y_MSB  = const(0x03)
_GYRO_REGISTER_OUT_Y_LSB  = const(0x04)
_GYRO_REGISTER_OUT_Z_MSB  = const(0x05)
_GYRO_REGISTER_OUT_Z_LSB  = const(0x06)
_GYRO_REGISTER_WHO_AM_I   = const(0x0C)   # 11010111   r
_GYRO_REGISTER_CTRL_REG0  = const(0x0D)  # 00000000   r/w
_GYRO_REGISTER_CTRL_REG1  = const(0x13)  # 00000000   r/w
_GYRO_REGISTER_CTRL_REG2  = const(0x14)  # 00000000   r/w
_GYRO_SENSITIVITY_250DPS  = 0.0078125    # Table 35 of datasheet
_GYRO_SENSITIVITY_500DPS  = 0.015625     # ..
_GYRO_SENSITIVITY_1000DPS = 0.03125     # ..
예제 #40
0
from micropython import const
from trezor import ui

TEXT_HEADER_HEIGHT = const(48)
TEXT_LINE_HEIGHT = const(26)
TEXT_MARGIN_LEFT = const(14)


class Text(ui.Widget):

    def __init__(self, header_text, header_icon, *content, icon_color=ui.ORANGE_ICON):
        self.header_text = header_text
        self.header_icon = header_icon
        self.icon_color = icon_color
        self.content = content

    def render(self):
        offset_x = TEXT_MARGIN_LEFT
        offset_y = TEXT_LINE_HEIGHT + TEXT_HEADER_HEIGHT
        style = ui.NORMAL
        fg = ui.FG
        bg = ui.BG
        ui.header(self.header_text, self.header_icon, ui.TITLE_GREY, ui.BG, self.icon_color)

        for item in self.content:
            if isinstance(item, str):
                ui.display.text(offset_x, offset_y, item, style, fg, bg)
                offset_y += TEXT_LINE_HEIGHT
            elif item == ui.MONO or item == ui.NORMAL or item == ui.BOLD:
                style = item
            else:
예제 #41
0
"""
import math
import time
from micropython import const
try:
    import struct
except ImportError:
    import ustruct as struct


__version__ = "2.2.1"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_BME280.git"

#    I2C ADDRESS/BITS/SETTINGS
#    -----------------------------------------------------------------------
_BME280_ADDRESS = const(0x77)
_BME280_CHIPID = const(0x60)

_BME280_REGISTER_CHIPID = const(0xD0)
_BME280_REGISTER_DIG_T1 = const(0x88)
_BME280_REGISTER_DIG_H1 = const(0xA1)
_BME280_REGISTER_DIG_H2 = const(0xE1)
_BME280_REGISTER_DIG_H3 = const(0xE3)
_BME280_REGISTER_DIG_H4 = const(0xE4)
_BME280_REGISTER_DIG_H5 = const(0xE5)
_BME280_REGISTER_DIG_H6 = const(0xE7)

_BME280_REGISTER_SOFTRESET = const(0xE0)
_BME280_REGISTER_CTRL_HUM = const(0xF2)
_BME280_REGISTER_STATUS = const(0xF3)
_BME280_REGISTER_CTRL_MEAS = const(0xF4)
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

from micropython import const
from time import sleep_ms
import ustruct

# Display resolution
EPD_WIDTH = const(200)
EPD_HEIGHT = const(200)

# Display commands
DRIVER_OUTPUT_CONTROL = const(0x01)
BOOSTER_SOFT_START_CONTROL = const(0x0C)
#GATE_SCAN_START_POSITION             = const(0x0F)
DEEP_SLEEP_MODE = const(0x10)
DATA_ENTRY_MODE_SETTING = const(0x11)
#SW_RESET                             = const(0x12)
#TEMPERATURE_SENSOR_CONTROL           = const(0x1A)
MASTER_ACTIVATION = const(0x20)
#DISPLAY_UPDATE_CONTROL_1             = const(0x21)
DISPLAY_UPDATE_CONTROL_2 = const(0x22)
WRITE_RAM = const(0x24)
WRITE_VCOM_REGISTER = const(0x2C)
예제 #43
0
"""

import time
try:
    import struct
except ImportError:
    import ustruct as struct

from adafruit_bus_device.i2c_device import I2CDevice
from micropython import const

__version__ = "1.1.2"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_MLX90393.git"

_CMD_SB = const(0b00010000)   # Start burst mode
_CMD_SW = const(0b00100000)   # Start wakeup on change mode
_CMD_SM = const(0b00110000)   # Start single-measurement mode
_CMD_RM = const(0b01000000)   # Read measurement
_CMD_RR = const(0b01010000)   # Read register
_CMD_WR = const(0b01100000)   # Write register
_CMD_EX = const(0b10000000)   # Exit mode
_CMD_HR = const(0b11010000)   # Memory recall
_CMD_HS = const(0b11100000)   # Memory store
_CMD_RT = const(0b11110000)   # Reset
_CMD_NOP = const(0x00)        # NOP

_CMD_AXIS_ALL = const(0xE)    # X+Y+Z axis bits for commands

_CMD_REG_CONF1 = const(0x00)  # Gain
_CMD_REG_CONF2 = const(0x01)  # Burst, comm mode
예제 #44
0
class SPS30:
    # index of list
    # I2C address: 0x69
    SPS_ADDR = const(0x00)
    # float array of values
    SPS_PM1P0 = const(0)
    SPS_PM2P5 = const(1)
    SPS_PM4P0 = const(2)
    SPS_PM10P0 = const(3)
    SPS_PCNT_0P5 = const(4)
    SPS_PCNT_1P0 = const(5)
    SPS_PCNT_2P5 = const(6)
    SPS_PCNT_4P0 = const(7)
    SPS_PCNT_10P0 = const(8)
    SPS_TYP_SIZE = const(9)

    # status PM sensor: STANDBY (fan off) or NORMAL (fan ON, sampling)
    ACTIVE = const(0)  # mode active, has allowed to fan startup
    PASSIVE = const(1)  # mode passive, same as NORMAL
    NORMAL = const(3)  # mode normal, fan is ON, sampling measurements
    STANDBY = const(4)  # mode passive, state standby fan is OFF

    # idle time minimal time to switch fan OFF
    IDLE = const(
        120000)  # msecs, minimal idle time between sample time and interval

    def __init__(self,
                 port=1,
                 debug=False,
                 sample=60,
                 interval=1200,
                 raw=False,
                 calibrate=None,
                 pins=('P3', 'P4'),
                 addr=SPS_ADDR,
                 clean=0,
                 explicit=False):
        # read from port=UART1 V5/Gnd, PMS/Rx - GPIO P3/Tx, PMS/Tx - GPIO P4/Rx
        # or port=/dev/ttyUSB?
        # measure average in sample time, interval freq. of samples in secs
        # explicit True: Plantower way of count (>PMi), False: Sensirion way (PM0.3-PMi) (dflt=False)
        # idle <8 mA, operation 60 mA, max 5.5V, count/mass: 0.3 - size um
        # SPS pin nr:
        #     1=VCC, 2=Rx/SDA, 3=Tx/SCL, 4= sel(Gnd,I2C), 5=Gnd, 5 is corner side
        # clean > 0: secs interval autoclean, 0 (dflt): weekly, None: clean initial
        try:
            if type(port) is str:  # no PyCom case
                import serial
                self.ser = serial.Serial(port,
                                         115200,
                                         bytesize=8,
                                         parity='N',
                                         stopbits=1,
                                         timeout=20,
                                         xonxoff=0,
                                         rtscts=0)
                self.ser.any = self.in_waiting
            elif type(port) is int:  # micro python case
                from machine import UART
                self.ser = UART(port,
                                baudrate=115200,
                                pins=pins,
                                timeout_chars=10)
            else:
                self.ser = port  # fd
        except:
            raise ValueError("SPS serial failed")

        self.debug = debug
        self.addr = addr
        self.mode = self.PASSIVE
        self.started = None

        self.interval = interval * 1000  # if interval == 0 no auto fan switching
        self.sample = sample * 1000
        self.raw = raw
        self.clean = clean  # clean fan after clean secs dflt: None (weekly)
        self.explicit = explicit  # counts are > PM size or < PM size

        # dflts are from sample label. Try later again
        self.name = 'SPS30'
        self.firmware = '117118'
        self.code = 'SEN-15103'
        self.clean = clean

        # list of name, units, index in measurments, calibration factoring
        # eg pm1=[20,1] adds a calibration offset of 20 to measurement
        self.PM_fields = [
            ['pm1', 'ug/m3', self.SPS_PM1P0, [0, 1]],  # 0.3 upto 1
            ['pm25', 'ug/m3', self.SPS_PM2P5, [0, 1]],  # 0.3 upto 2.5
            ['pm4', 'ug/m3', self.SPS_PM4P0, [0, 1]],
            ['pm10', 'ug/m3', self.SPS_PM10P0, [0, 1]],
            # 0.1 liter = 0.00353147 cubic feet, convert -> pcs / 0.01qf
            # std used here pcs/0.1dm3 (Plantower style)
            ['pm05_cnt', 'pcs/0.1dm3', self.SPS_PCNT_0P5, [0, 100]],
            ['pm1_cnt', 'pcs/0.1dm3', self.SPS_PCNT_1P0, [0, 100]],
            ['pm25_cnt', 'pcs/0.1dm3', self.SPS_PCNT_2P5, [0, 100]],
            ['pm4_cnt', 'pcs/0.1dm3', self.SPS_PCNT_4P0, [0, 100]],
            ['pm10_cnt', 'pcs/0.1dm3', self.SPS_PCNT_10P0, [0, 100]],
            ['grain', 'mu', self.SPS_TYP_SIZE, None],
            # grain: average particle size
            ['grain', 'mu', self.SPS_TYP_SIZE, None] if not explicit else
            ['pm03_cnt', 'pcs/0.1dm3', self.SPS_TYP_SIZE, [0, 100]],
        ]
        if type(calibrate) is dict:
            for key in calibrate.keys():
                if calibrate[key] and type(calibrate[key]) != list: continue
                for pm in range(len(self.PM_fields)):
                    if self.PM_fields[pm][0] == key:
                        self.PM_fields[pm][3] = calibrate[key]
                        break

    def isStarted(self, debug=False):
        if self.started: return
        self.started = 0
        # dflts are from sample label
        try:
            self.started = True
            if self.reset(debug=debug):
                RuntimeError("Reset failed with %d" % stat)
            # collect meta info
            tmp = self.device_info('name')
            if tmp: self.name = tmp
            tmp = self.device_info('serial')
            if tmp: self.firmware = tmp
            tmp = self.device_info('code')
            if tmp: self.code = tmp
            if debug:
                print("name: '%s', S/N '%s', article: '%s'" %
                      (self.name, self.firmware, self.device_info('code')))
            if self.clean:
                self.auto_clean(self.clean, debug=debug)
                self.clean = 0
            elif self.clean == None:
                self.fan_clean(debug=debug)
        except Exception as e:
            RuntimeError(e)

    def in_waiting(self):  # for non PyCom python
        try:
            return self.ser.in_waiting
        except:
            raise OSError

    def read_until(self, char=chr(0x7E)):
        try:
            cnt = 0
            while True:
                cnt += 1
                if cnt > 20: return None
                if not self.ser.any():
                    sleep_ms(200)
                    continue
                try:
                    if self.ser.read(1) != char: continue
                except:
                    pass
                return char
        except:
            return None

    # calibrate by length calibration (Taylor) factor array
    def calibrate(self, cal, value):
        if self.raw: return value
        if (not cal) or (type(cal) != list):
            return round(value, 2)
        if type(value) is int: value = float(value)
        if not type(value) is float:
            return None
        rts = 0
        pow = 0
        for a in cal:
            rts += a * (value**pow)
            pow += 1
        return rts

    error = {
        0x0: 'ok',
        0x1: 'data length err',
        0x2: 'fan off',
        0x4: 'illegal cmd param',
        0x28: 'internal fie arg range error',
        0x43: 'cmd not allowed in this state',
    }

    stuff = { # byte stuffing with 0x7D
      0x7E: 0x5E, 0x7D: 0x5D,
      0x11: 0x31, 0x13: 0x33,
    }

    # just before sending, returns byte array
    def stuffing(self, arr):
        rslt = [0x7E]
        for b in arr:
            if b in self.stuff.keys():
                rslt += [0x7D, stuff[b]]
            else:
                rslt.append(b)
        rslt += [0x7E]
        return bytearray(rslt)

    # just after reading, returns int array
    def unstuff(self, data):  # to do unstuffing
        rslt = []
        for i in range(0, len(data)):
            if data[i] == 0x7D:
                try:
                    for val in self.stuff.items():
                        if val[1] == data[i + 1]:
                            rslt.append(val[0])
                            break
                    i += 1
                except:
                    pass
            else:
                rslt.append(data[i])
        return rslt

    # adds addr and append checksum, send stuffed bytearray
    def send(self, cmd, data, debug=False):
        self.isStarted(debug=debug)
        s = [self.addr, cmd, len(data)] + data
        s.append((~(sum(s) & 0xFF)) & 0xFF)
        s = self.stuffing(s)
        if debug: print("Send: ", s)
        return self.ser.write(s)

    # get data from uart, return tuple(status,data[])
    def receive(self, cmd, debug=False):
        strt = True
        buf = bytearray()
        for cnt in range(1, 6):
            if self.ser.any():
                cnt = 0
                break
            if debug: print("SPS wait...")
            sleep_ms(1000)
        if cnt: return (0x2, [])
        while True:
            try:
                char = self.ser.read(1)
            except:
                return (0x2, [])
            if char == b'': raise OSError("No data")
            elif strt:
                if (char == b'\x7E'): strt = False
                continue
            if char == b'\x7E': break
            buf += char
        buf = self.unstuff(buf)
        # to do: add sum chk, cmd check: buf[1] == cmd
        if len(buf[4:-1]) != buf[3]: raise ValueError("length rcv")
        if debug: print("Received: %s" % str(buf))
        if (~sum(buf) & 0xFF): raise ValueError("checksum")
        if buf[1] != cmd: raise ValueError("sensor reply error")
        return (buf[2], buf[4:4 + buf[3]])  # status, data

    # UART / Sensirion SPS30 SHDLC commands
    SPS_START = const(0x00)
    SPS_STOP = const(0x01)
    SPS_READ = const(0x03)
    SPS_FAN_SPEED = const(0x04)
    SPS_AUTO_CLEAN = const(0x80)
    SPS_FAN_CLEAN = const(0x56)
    SPS_INFO = const(0xD0)
    SPS_RESET = const(0xD3)

    def start_measurement(self, debug=False):
        if debug: print("Start SPS")
        # subcmd=0x01, mode=0x03
        self.send(self.SPS_START, [0x01, 0x03], debug=debug)
        return self.receive(self.SPS_START)[0]

    def stop_measurement(self, debug=False):
        # to idle state
        if debug: print("Stop SPS")
        self.send(self.SPS_STOP, [], debug=debug)
        return self.receive(self.SPS_STOP, debug=debug)[0]

    # mass ug/m3: PM1.0, PM2.5, PM4.0, PM10
    # count pcs/cm3: PM0.5, PM1.0, PM2.5, PM4.0, PM10
    # typical pm size
    def read_measurement(self,
                         debug=False
                         ):  # default 1 sec sample, empty if no value yet
        if debug: print("Read SPS values")
        self.send(self.SPS_READ, [])
        (status, data) = self.receive(self.SPS_READ, debug=debug)
        if status:
            try:
                print("SPS error: %d (%s)" % (status, self.error[status]))
            except:
                print("SPS unknown error: %d" % status)
            return []
        rslts = []
        for i in range(0, len(data), 4):
            if (i + 4) > len(data): break
            rslts.append(struct.unpack('>f', bytearray((data[i:i + 4])))[0])
        if debug: print("Read: ", rslts)
        return rslts

    # routine is from Sensirion sample. Gives status 2, no speed
    def fan_speed(self, debug=False):
        if debug: print("Get fan speed")
        self.send(self.SPS_FAN_SPEED, [], debug=debug)
        rslts = self.receive(self.SPS_FAN_SPEED, debug=debug)
        if debug: print(rslts)
        if not rslts[0]: return rslts[1][0]
        else: return self.error[rslts[0]]

    # read/write auto cleaning interval, 10 secs clean air boost
    # interval=0 disable auto clean, dflt 604.800 secs/one week
    # poweroff will reset next clean
    def auto_clean(self, interval=None, debug=False):
        if interval == None:
            if debug: print("Auto clean, no interval")
            self.send(self.SPS_AUTO_CLEAN, [
                0x0,
            ], debug=debug)
        else:
            if debug: print("Auto clean, interval %d" % interval)
            b = bytearray(struct.pack('>L', interval))
            self.send(self.SPS_AUTO_CLEAN, [0x0, b[0], b[1], b[2], b[4]],
                      debug=debug)
        return self.receive(self.SPS_AUTO_CLEAN)[0]

    # forced fan cleaning
    def fan_clean(self, debug=False):
        if debug: print("Clean fan")
        self.send(self.SPS_FAN_CLEAN, [], debug=debug)
        return self.receive(self.SPS_FAN_CLEAN)[0]

    # get information from sensor. Sample gives empty string
    def device_info(self, info='serial', debug=False):
        cmds = {'name': 0x01, 'code': 0x2, 'serial': 0x03}
        try:
            if (not info) or (info == 'all'):
                rslt = []
                for cmd in cmds.keys():
                    rslt.append(cmd + ': ' + self.device_info(cmd))
                return ', '.join(rslt)
            elif info in cmds.keys():
                self.send(self.SPS_INFO, [cmds[info]], debug=debug)
                strg = self.receive(self.SPS_INFO)[1][:-1]
                strg = str(strg[:-1].decode("ascii"))
                if debug: print("Got info \"%s\"" % strg)
                return strg
        except:
            pass
        return ''

    # soft reset similar as power reset
    def reset(self, debug=False):
        if debug: print("SPS reset")
        try:
            self.send(self.SPS_RESET, [], debug=debug)
            stat = self.receive(self.SPS_RESET)[0]
            if not stat: self.mode = self.STANDBY
            if debug: print("reset status: %d" % stat)
        except Exception as e:
            raise RuntimeError(e)
        return stat

        # passive mode, go into standby state / sleep: fan OFF
    def Standby(self, debug=False):
        if debug: print("Go standby from 0X%X" % self.mode)
        if self.mode != self.STANDBY:
            try:
                self.stop_measurement(debug=debug)
            except:
                return False
            self.mode = self.STANDBY
        return True

    # passive mode, go into normal state: fan ON, allow data telegrams reading
    def Normal(self, debug=False):
        if debug: print("Go normal from 0x%X" % self.mode)
        return self.GoPassive(debug=debug)

    # passive mode wait on read request
    def GoPassive(self, debug=False):
        if debug: print("Go Passive from 0X%X" % self.mode)
        if self.mode == self.STANDBY:
            try:
                self.start_measurement(debug=debug)
                sleep_ms(30000)
            except:
                return False
        self.mode = self.PASSIVE
        return True

    # from passive mode go in active mode (same as with power on)
    def GoActive(self, debug=False):
        if debug: print("Go active from 0X%X" % self.mode)
        return self.GoPassive(debug=debug)

    # in passive mode do one data telegram reading
    def PassiveRead(self, debug=False):
        if self.mode == self.STANDBY:
            if not self.GoPassive(debug=debug): return []
        return self.read_measurement(debug=debug)

    def getData(self, debug=False):
        ''' read data telegrams from the serial interface (32 bytes)
      before actual read flush all pending data first
      during the period sample time: active (200-800 ms), passive read cmd 1 sec
      calculate average during sample seconds
      if passive mode fan off: switch fan ON and wait 30 secs.
    '''
        ErrorCnt = 0
        cnt = 0
        PM_sample = {}
        # clear the input buffer first so we get latest reading
        if self.mode == self.STANDBY: self.GoPassive(debug=debug)
        StrtTime = ticks_ms()
        LastTime = StrtTime + self.sample - 1000
        while True:
            buff = []
            try:
                buff = self.PassiveRead(debug=debug)
            except:
                pass
            if len(buff) == self.SPS_TYP_SIZE + 1:  # must be all
                for fld in self.PM_fields:
                    PM_sample[fld[0]] = PM_sample.setdefault(
                        fld[0], 0.0) + buff[fld[2]]
                cnt += 1
            elif not len(PM_sample):
                self.mode = self.STANDBY  # wake it up
                return self.getData(debug=debug)
            if ticks_ms() >= LastTime: break
            sleep_ms(5000)
        # turn fan off?
        if self.interval - (ticks_ms() - StrtTime) > 60 * 1000:
            self.Standby(debug=debug)  # switch fan OFF
        if cnt:  # average count during the sample time
            for fld in self.PM_fields:
                PM_sample[fld[0]] /= cnt
                if self.raw:
                    PM_sample[fld[0]] = round(PM_sample[fld[0]], 2)
                else:
                    PM_sample[fld[0]] = round(
                        self.calibrate(fld[3], PM_sample[fld[0]]), 2)
        if self.explicit:
            PM10 = PM_sample["pm10_cnt"]
            for pmCnt in PM_sample.keys():
                if pmCnt.find('_cnt') < 0: continue
                if pmCnt.find('03_cnt') > 0: PM_sample['pm03_cnt'] = PM10
                else: PM_sample[pmCnt] = PM10 - PM_sample[pmCnt]
        return PM_sample
예제 #45
0
* Author(s): Jerry Needell
"""

# imports

import time
from micropython import const


__version__ = "1.1.1"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_STMPE610.git"



_STMPE_ADDR = const(0x41)
_STMPE_VERSION = const(0x0811)

_STMPE_SYS_CTRL1 = const(0x03)
_STMPE_SYS_CTRL1_RESET = const(0x02)
_STMPE_SYS_CTRL2 = const(0x04)

_STMPE_TSC_CTRL = const(0x40)
_STMPE_TSC_CTRL_EN = const(0x01)
_STMPE_TSC_CTRL_XYZ = const(0x00)
_STMPE_TSC_CTRL_XY = const(0x02)

_STMPE_INT_CTRL = const(0x09)
_STMPE_INT_CTRL_POL_HIGH = const(0x04)
_STMPE_INT_CTRL_POL_LOW = const(0x00)
_STMPE_INT_CTRL_EDGE = const(0x02)
예제 #46
0
#
# The sensor's local value updates every second, and it will notify
# any connected central every 10 seconds.

import bluetooth
import random
import struct
import time
from ble_advertising import advertising_payload
from machine import Pin, ADC
from micropython import const

pot = ADC(Pin(32))
pot.atten(ADC.ATTN_11DB)

_IRQ_CENTRAL_CONNECT = const(1 << 0)
_IRQ_CENTRAL_DISCONNECT = const(1 << 1)

# org.bluetooth.service.environmental_sensing
_ENV_SENSE_UUID = bluetooth.UUID(0x181A)
# org.bluetooth.characteristic.temperature
_TEMP_CHAR = (
    bluetooth.UUID(0x2A6E),
    bluetooth.FLAG_READ | bluetooth.FLAG_NOTIFY,
)
_ENV_SENSE_SERVICE = (
    _ENV_SENSE_UUID,
    (_TEMP_CHAR,),
)

# org.bluetooth.characteristic.gap.appearance.xml
예제 #47
0
* Adafruit CircuitPython firmware for the supported boards:
  https://github.com/adafruit/circuitpython/releases
* Adafruit's Bus Device library: https://github.com/adafruit/Adafruit_CircuitPython_BusDevice
"""

import time
import struct
import adafruit_bus_device.i2c_device as i2c_device
from micropython import const

__version__ = "1.0.1"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_MPL115A2.git"

# pylint: disable=bad-whitespace
_MPL115A2_ADDRESS                   = const(0x60)
_MPL115A2_REGISTER_PRESSURE_MSB     = const(0x00)
_MPL115A2_REGISTER_A0_COEFF_MSB     = const(0x04)
_MPL115A2_REGISTER_STARTCONVERSION  = const(0x12)
# pylint: enable=bad-whitespace

class MPL115A2:
    """Driver for MPL115A2 I2C barometric pressure / temperature sensor."""
    def __init__(self, i2c, address=_MPL115A2_ADDRESS):
        self._i2c = i2c_device.I2CDevice(i2c, address)
        self._buf = bytearray(4)
        self._read_coefficients()

    @property
    def pressure(self):
        """The pressure in hPa."""
예제 #48
0
# * Adafruit's Bus Device library: https://github.com/adafruit/Adafruit_CircuitPython_BusDevice
"""

import time

try:
    import struct
except ImportError:
    import ustruct as struct

from micropython import const

__version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_BMP3XX.git"

_BMP388_CHIP_ID = const(0x50)
_BMP390_CHIP_ID = const(0x60)

# pylint: disable=import-outside-toplevel
_REGISTER_CHIPID = const(0x00)
_REGISTER_STATUS = const(0x03)
_REGISTER_PRESSUREDATA = const(0x04)
_REGISTER_TEMPDATA = const(0x07)
_REGISTER_CONTROL = const(0x1B)
_REGISTER_OSR = const(0x1C)
_REGISTER_ODR = const(0x1D)
_REGISTER_CONFIG = const(0x1F)
_REGISTER_CAL_DATA = const(0x31)
_REGISTER_CMD = const(0x7E)

_OSR_SETTINGS = (1, 2, 4, 8, 16, 32
예제 #49
0
Example usage on ESP8266:

    import machine, sdcard, os
    sd = sdcard.SDCard(machine.SPI(0), machine.Pin(15))
    os.umount()
    os.VfsFat(sd, "")
    os.listdir()

"""

from micropython import const
import time


_CMD_TIMEOUT = const(100)

_R1_IDLE_STATE = const(1 << 0)
#R1_ERASE_RESET = const(1 << 1)
_R1_ILLEGAL_COMMAND = const(1 << 2)
#R1_COM_CRC_ERROR = const(1 << 3)
#R1_ERASE_SEQUENCE_ERROR = const(1 << 4)
#R1_ADDRESS_ERROR = const(1 << 5)
#R1_PARAMETER_ERROR = const(1 << 6)
_TOKEN_CMD25 = const(0xfc)
_TOKEN_STOP_TRAN = const(0xfd)
_TOKEN_DATA = const(0xfe)


class SDCard:
    def __init__(self, spi, cs):
예제 #50
0
            data = data & 0b11001111
            data = data | 0b00110000
        self.write_byte(AXP202_OFF_CTL, data)


# =============================================================================
#
# LCD
#
# this is from: https://github.com/devbis/st7789py_mpy
# (seems to be under MIT license)
#
# =============================================================================

# chip commands
ST77XX_NOP = const(0x00)
ST77XX_SWRESET = const(0x01)
ST77XX_RDDID = const(0x04)
ST77XX_RDDST = const(0x09)

ST77XX_SLPIN = const(0x10)
ST77XX_SLPOUT = const(0x11)
ST77XX_PTLON = const(0x12)
ST77XX_NORON = const(0x13)

ST77XX_INVOFF = const(0x20)
ST77XX_INVON = const(0x21)
ST77XX_DISPOFF = const(0x28)
ST77XX_DISPON = const(0x29)
ST77XX_CASET = const(0x2A)
ST77XX_RASET = const(0x2B)
예제 #51
0
* Adafruit CircuitPython firmware for the ESP8622 and M0-based boards:
  https://github.com/adafruit/circuitpython/releases
* Adafruit's Bus Device library: https://github.com/adafruit/Adafruit_CircuitPython_BusDevice
"""
import math
import time

import adafruit_bus_device.i2c_device as i2c_device
from micropython import const

__version__ = "3.1.4"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_VL53L0X.git"

# Configuration constants:
# pylint: disable=bad-whitespace
_SYSRANGE_START                              = const(0x00)
_SYSTEM_THRESH_HIGH                          = const(0x0C)
_SYSTEM_THRESH_LOW                           = const(0x0E)
_SYSTEM_SEQUENCE_CONFIG                      = const(0x01)
_SYSTEM_RANGE_CONFIG                         = const(0x09)
_SYSTEM_INTERMEASUREMENT_PERIOD              = const(0x04)
_SYSTEM_INTERRUPT_CONFIG_GPIO                = const(0x0A)
_GPIO_HV_MUX_ACTIVE_HIGH                     = const(0x84)
_SYSTEM_INTERRUPT_CLEAR                      = const(0x0B)
_RESULT_INTERRUPT_STATUS                     = const(0x13)
_RESULT_RANGE_STATUS                         = const(0x14)
_RESULT_CORE_AMBIENT_WINDOW_EVENTS_RTN       = const(0xBC)
_RESULT_CORE_RANGING_TOTAL_EVENTS_RTN        = const(0xC0)
_RESULT_CORE_AMBIENT_WINDOW_EVENTS_REF       = const(0xD0)
_RESULT_CORE_RANGING_TOTAL_EVENTS_REF        = const(0xD4)
_RESULT_PEAK_SIGNAL_RATE_REF                 = const(0xB6)
예제 #52
0
  <https://www.adafruit.com/product/3709>`_ (Product ID: 3709)

**Software and Dependencies:**

* MicroPython:
    https://github.com/micropython/micropython

"""
import time
from micropython import const

__version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/alexmrqt/Adafruit_CircuitPython_SGP30.git"

# pylint: disable=bad-whitespace
_SGP30_DEFAULT_I2C_ADDR = const(0x58)
_SGP30_FEATURESET = const(0x0020)

_SGP30_CRC8_POLYNOMIAL = const(0x31)
_SGP30_CRC8_INIT = const(0xFF)
_SGP30_WORD_LEN = const(2)
# pylint: enable=bad-whitespace


class Adafruit_SGP30:
    """
    A driver for the SGP30 gas sensor.

    :param i2c: The `I2C` object to use. This is the only required parameter.
    :param int address: (optional) The I2C address of the device.
    """
예제 #53
0
파일: i2c.py 프로젝트: eiselekd/hw
* Adafruit CircuitPython firmware for the supported boards:
  https://github.com/adafruit/circuitpython/releases

* Adafruit's Bus Device library: https://github.com/adafruit/Adafruit_CircuitPython_BusDevice
"""

import adafruit_bus_device.i2c_device as i2c_device
from micropython import const
from adafruit_cap1188.cap1188 import CAP1188

__version__ = "1.1.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_CAP1188.git"

# pylint: disable=bad-whitespace
_CAP1188_DEFAULT_ADDRESS     = const(0x29)
# pylint: enable=bad-whitespace

class CAP1188_I2C(CAP1188):
    """Driver for the CAP1188 connected over I2C."""
    def __init__(self, i2c, address=_CAP1188_DEFAULT_ADDRESS):
        self._i2c = i2c_device.I2CDevice(i2c, address)
        self._buf = bytearray(2)
        super().__init__()

    def _read_register(self, address):
        """Return 8 bit value of register at address."""
        self._buf[0] = address
        with self._i2c as i2c:
            i2c.write(self._buf, end=1, stop=False)
            i2c.readinto(self._buf, start=1)
`ads1x15`
====================================================

CircuitPython base class driver for ADS1015/1115 ADCs.

* Author(s): Carter Nelson
"""

__version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_ADS1x15.git"

from micropython import const
from adafruit_bus_device.i2c_device import I2CDevice

# pylint: disable=bad-whitespace
_ADS1X15_DEFAULT_ADDRESS = const(0x48)
_ADS1X15_POINTER_CONVERSION = const(0x00)
_ADS1X15_POINTER_CONFIG = const(0x01)
_ADS1X15_CONFIG_OS_SINGLE = const(0x8000)
_ADS1X15_CONFIG_MUX_OFFSET = const(12)
_ADS1X15_CONFIG_COMP_QUE_DISABLE = const(0x0003)
_ADS1X15_CONFIG_GAIN = {
    2 / 3: 0x0000,
    1: 0x0200,
    2: 0x0400,
    4: 0x0600,
    8: 0x0800,
    16: 0x0A00
}
# pylint: enable=bad-whitespace
예제 #55
0
파일: ssd1331.py 프로젝트: eiselekd/hw
`adafruit_rgb_display.ssd1331`
====================================================

A simple driver for the SSD1331-based displays.

* Author(s): Radomir Dopieralski, Michael McWethy
"""

from micropython import const
from adafruit_rgb_display.rgb import DisplaySPI

__version__ = "3.1.1"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RGB_Display.git"


_DRAWLINE = const(0x21)
_DRAWRECT = const(0x22)
_FILL = const(0x26)
_PHASEPERIOD = const(0x12)
_SETCOLUMN = const(0x15)
_SETROW = const(0x75)
_CONTRASTA = const(0x81)
_CONTRASTB = const(0x82)
_CONTRASTC = const(0x83)
_MASTERCURRENT = const(0x87)
_SETREMAP = const(0xA0)
_STARTLINE = const(0xA1)
_DISPLAYOFFSET = const(0xA2)
_NORMALDISPLAY = const(0xA4)
_DISPLAYALLON = const(0xA5)
_DISPLAYALLOFF = const(0xA6)
예제 #56
0
import bluetooth
import uasyncio as asyncio

from .core import (
    ensure_active,
    ble,
    log_info,
    log_error,
    log_warn,
    register_irq_handler,
)
from .device import DeviceConnection, DeviceTimeout

_registered_characteristics = {}

_IRQ_GATTS_WRITE = const(3)
_IRQ_GATTS_READ_REQUEST = const(4)
_IRQ_GATTS_INDICATE_DONE = const(20)

_FLAG_READ = const(0x0002)
_FLAG_WRITE_NO_RESPONSE = const(0x0004)
_FLAG_WRITE = const(0x0008)
_FLAG_NOTIFY = const(0x0010)
_FLAG_INDICATE = const(0x0020)

_FLAG_READ_ENCRYPTED = const(0x0200)
_FLAG_READ_AUTHENTICATED = const(0x0400)
_FLAG_READ_AUTHORIZED = const(0x0800)
_FLAG_WRITE_ENCRYPTED = const(0x1000)
_FLAG_WRITE_AUTHENTICATED = const(0x2000)
_FLAG_WRITE_AUTHORIZED = const(0x4000)
예제 #57
0
"""NRF24L01 driver for MicroPython
"""

from micropython import const
import utime

# nRF24L01+ registers
CONFIG      = const(0x00)
EN_RXADDR   = const(0x02)
SETUP_AW    = const(0x03)
SETUP_RETR  = const(0x04)
RF_CH       = const(0x05)
RF_SETUP    = const(0x06)
STATUS      = const(0x07)
RX_ADDR_P0  = const(0x0a)
TX_ADDR     = const(0x10)
RX_PW_P0    = const(0x11)
FIFO_STATUS = const(0x17)
DYNPD	    = const(0x1c)

# CONFIG register
EN_CRC      = const(0x08) # enable CRC
CRCO        = const(0x04) # CRC encoding scheme; 0=1 byte, 1=2 bytes
PWR_UP      = const(0x02) # 1=power up, 0=power down
PRIM_RX     = const(0x01) # RX/TX control; 0=PTX, 1=PRX

# RF_SETUP register
POWER_0     = const(0x00) # -18 dBm
POWER_1     = const(0x02) # -12 dBm
POWER_2     = const(0x04) # -6 dBm
POWER_3     = const(0x06) # 0 dBm
예제 #58
0
    from collections import namedtuple
except ImportError:
    from ucollections import namedtuple
try:
    import struct
except ImportError:
    import ustruct as struct

from micropython import const

__version__ = "4.3.3"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_LIS3DH.git"

# Register addresses:
# pylint: disable=bad-whitespace
_REG_OUTADC1_L   = const(0x08)
_REG_WHOAMI      = const(0x0F)
_REG_TEMPCFG     = const(0x1F)
_REG_CTRL1       = const(0x20)
_REG_CTRL3       = const(0x22)
_REG_CTRL4       = const(0x23)
_REG_CTRL5       = const(0x24)
_REG_OUT_X_L     = const(0x28)
_REG_INT1SRC     = const(0x31)
_REG_CLICKCFG    = const(0x38)
_REG_CLICKSRC    = const(0x39)
_REG_CLICKTHS    = const(0x3A)
_REG_TIMELIMIT   = const(0x3B)
_REG_TIMELATENCY = const(0x3C)
_REG_TIMEWINDOW  = const(0x3D)
예제 #59
0
* Adafruit `TTL Serial JPEG Camera with NTSC Video
  <https://www.adafruit.com/product/397>`_ (Product ID: 397)

**Software and Dependencies:**

* Adafruit CircuitPython firmware for the ESP8622 and M0-based boards:
  https://github.com/adafruit/circuitpython/releases
"""
from micropython import const

__version__ = "4.0.1"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_VC0706.git"

# pylint: disable=bad-whitespace
_SERIAL               = const(0x00)
_RESET                = const(0x26)
_GEN_VERSION          = const(0x11)
_SET_PORT             = const(0x24)
_READ_FBUF            = const(0x32)
_GET_FBUF_LEN         = const(0x34)
_FBUF_CTRL            = const(0x36)
_DOWNSIZE_CTRL        = const(0x54)
_DOWNSIZE_STATUS      = const(0x55)
_READ_DATA            = const(0x30)
_WRITE_DATA           = const(0x31)
_COMM_MOTION_CTRL     = const(0x37)
_COMM_MOTION_STATUS   = const(0x38)
_COMM_MOTION_DETECTED = const(0x39)
_MOTION_CTRL          = const(0x42)
_MOTION_STATUS        = const(0x43)
====================================================

CircuitPython module for the MCP23008 I2C I/O extenders.

* Author(s): Tony DiCola
"""

from micropython import const
from .mcp230xx import MCP230XX
from .digital_inout import DigitalInOut

__version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_MCP230xx.git"

# pylint: disable=bad-whitespace
_MCP23008_ADDRESS = const(0x20)
_MCP23008_IODIR = const(0x00)
_MCP23008_IPOL = const(0x01)
_MCP23008_GPINTEN = const(0x02)
_MCP23008_DEFVAL = const(0x03)
_MCP23008_INTCON = const(0x04)
_MCP23008_IOCON = const(0x05)
_MCP23008_GPPU = const(0x06)
_MCP23008_INTF = const(0x07)
_MCP23008_INTCAP = const(0x08)
_MCP23008_GPIO = const(0x09)


class MCP23008(MCP230XX):
    """Supports MCP23008 instance on specified I2C bus and optionally
    at the specified I2C address.