def __init__(self, bus, addr=None, gain=GAIN_1X, debug=False): if isinstance(bus, busio.I2C): self._write_read = self._write_read_i2c if addr is None: self.device = I2CDevice(bus, 0xC0) else: self.device = I2CDevice(bus, addr) elif isinstance(bus, busio.SPI): self._write_read = self._write_read_spi if addr is None: import digitalio, board self.device = SPIDevice(bus, digitalio.DigitalInOut(board.CE0)) else: self.device = SPIDevice(bus, addr) else: assert False, "Invalid bus" self._debug = debug self._status_last = 0 self._res_current = _RES_2_15 self._gain_current = gain # Put the device in a known state to start self.reset() # Set gain to the supplied level self.gain = self._gain_current
def create_from_pins(cls, cs, sck=board.SCK, mosi=board.MOSI, spi_cls=busio.SPI): """Helper constructor for creating an instance using just the pins its connected to. Args: cs: The pin connected to the DAC's SYNC input. sck: The pin connected to the DAC's SCLK input. mosi: The pin connected to the DAC's SDIN input. spi_cls: The class used to create the SPI interface, typically either ``busio.SPI`` or ``bitbangio.SPI``. """ cs_io = digitalio.DigitalInOut(cs) cs_io.direction = digitalio.Direction.OUTPUT cs_io.value = True spi = spi_cls(sck, MOSI=mosi) spi_device = SPIDevice(spi, cs_io, polarity=0, phase=1, baudrate=5000000) return cls(spi_device)
def __init__(self, gpioRst=None, gpioCs=None, cardWaitCount=2000): self.cardWaitCount = cardWaitCount if gpioRst is not None: self.rst = DigitalInOut(gpioRst) self.rst.direction = Direction.OUTPUT else: self.rst = None assert (gpioCs is not None, "Needs gpioCs") # TODO fails without cableSelect if gpioCs is not None: self.cs = DigitalInOut(gpioCs) self.cs.direction = Direction.OUTPUT else: self.cs = None # TODO CH rationalise which of these are referenced, which can be identical self.regBuf = bytearray(4) self.blockWriteBuf = bytearray(18) self.authBuf = bytearray(12) self.wregBuf = bytearray(2) self.rregBuf = bytearray(1) self.recvBuf = bytearray(16) self.recvMv = memoryview(self.recvBuf) if self.rst is not None: self.rst.value = 0 if self.cs is not None: self.cs.value = 1 self.spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) self.device = SPIDevice(self.spi, self.cs, baudrate=2500000) if self.rst is not None: self.rst.value = 1 self.init()
def __init__(self, spi, n, *, bpp=3, brightness=1.0, auto_write=True, pixel_order=None): # configure bpp and pixel_order if not pixel_order: pixel_order = GRB if bpp == 3 else GRBW else: bpp = len(pixel_order) if isinstance(pixel_order, tuple): order_list = [RGBW[order] for order in pixel_order] pixel_order = "".join(order_list) # set up SPI related stuff self._spi = SPIDevice(spi, baudrate=self.FREQ) with self._spi as spibus: try: # get actual SPI frequency freq = spibus.frequency except AttributeError: # use nominal freq = self.FREQ self._reset = bytes([0] * round(freq * self.TRST / 8)) self.spibuf = bytearray(8 * n * bpp) # everything else taken care of by base class super().__init__(n, brightness=brightness, byteorder=pixel_order, auto_write=auto_write)
def __init__( self, spi, cs, irq, reset, debug=False ): # pylint: disable=too-many-arguments self._irq = irq self._buf_tx = bytearray(20) self._buf_rx = bytearray(20) self._debug = debug # a cache of data, used for packet parsing self._buffer = [] # Reset reset.direction = Direction.OUTPUT reset.value = False time.sleep(0.01) reset.value = True time.sleep(0.5) # CS is an active low output cs.direction = Direction.OUTPUT cs.value = True # irq line is active high input, so set a pulldown as a precaution self._irq.direction = Direction.INPUT self._irq.pull = Pull.DOWN self._spi_device = SPIDevice(spi, cs, baudrate=4000000, phase=0, polarity=0)
def __init__(self): self.driver = Ax5043( SPIDevice(busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO))) self.mgr = Manager(self.driver) self.last_transmit_time = datetime.today() self.last_telemetry_time = datetime.today()
def __init__(self, spi, n, *, bpp=3, brightness=1.0, auto_write=True, pixel_order=None): from adafruit_bus_device.spi_device import SPIDevice self._spi = SPIDevice(spi, baudrate=self.FREQ) with self._spi as spibus: try: # get actual SPI frequency freq = spibus.frequency except AttributeError: # use nominal freq = self.FREQ self.RESET = bytes([0]*round(freq*self.TRST)) self.n = n if pixel_order is None: self.order = GRBW self.bpp = bpp else: self.order = pixel_order self.bpp = len(self.order) self.buf = bytearray(self.n * self.bpp) self.spibuf = bytearray(8*len(self.buf)) # Set auto_write to False temporarily so brightness setter does _not_ # call show() while in __init__. self.auto_write = False self.brightness = brightness self.auto_write = auto_write
def __init__(self, spi_bus, cs): self._device = SPIDevice(spi_bus, cs, baudrate=200000, polarity=1, phase=1) self.resetIC()
def __init__(self, spi, cs_pin, ready_pin, reset_pin, gpio0_pin=None, *, debug=False): self._debug = debug self.set_psk = False self.set_crt = False self._buffer = bytearray(10) self._pbuf = bytearray(1) # buffer for param read self._sendbuf = bytearray(256) # buffer for command sending self._socknum_ll = [[0]] # pre-made list of list of socket # self._spi_device = SPIDevice(spi, cs_pin, baudrate=8000000) self._cs = cs_pin self._ready = ready_pin self._reset = reset_pin self._gpio0 = gpio0_pin self._cs.direction = Direction.OUTPUT self._ready.direction = Direction.INPUT self._reset.direction = Direction.OUTPUT if self._gpio0: self._gpio0.direction = Direction.INPUT self.reset()
def __init__( self, spi_bus, cs, reset=None, is_dhcp=True, mac=DEFAULT_MAC, hostname=None, dhcp_timeout=3, debug=False ): self._debug = debug self._chip_type = None self._device = SPIDevice(spi_bus, cs, baudrate=8000000, polarity=0, phase=0) # init c.s. self._cs = cs # reset wiznet module prior to initialization if reset: reset.value = True time.sleep(0.1) reset.value = False time.sleep(0.1) # Buffer for reading params from module self._pbuff = bytearray(8) self._rxbuf = bytearray(MAX_PACKET) # attempt to initialize the module self._ch_base_msb = 0 assert self._w5100_init() == 1, "Failed to initialize WIZnet module." # Set MAC address self.mac_address = mac self._src_port = 0 self._dns = 0 # Set DHCP if is_dhcp: ret = self.set_dhcp(hostname, dhcp_timeout) assert ret == 0, "Failed to configure DHCP Server!"
def __init__(self, spi_bus, cs): # TBD: Does SPIDevice return an error if not working?d self._device = SPIDevice(spi_bus, cs, baudrate=200000, polarity=1, phase=1) self.init()
def __init__( self, spi_bus, cs, reset=None, is_dhcp=True, mac=DEFAULT_MAC, hostname=None, dhcp_timeout=30, debug=False, ): self._debug = debug self._chip_type = None self._device = SPIDevice(spi_bus, cs, baudrate=8000000, polarity=0, phase=0) # init c.s. self._cs = cs # reset wiznet module prior to initialization if reset: reset.value = False time.sleep(0.1) reset.value = True time.sleep(0.1) # Buffer for reading params from module self._pbuff = bytearray(8) self._rxbuf = bytearray(MAX_PACKET) # attempt to initialize the module self._ch_base_msb = 0 assert self._w5100_init() == 1, "Failed to initialize WIZnet module." # Set MAC address self.mac_address = mac self.src_port = 0 self._dns = 0 # First, wait link status is on # to avoid the code during DHCP, socket listen, connect ... # assert self.link_status, "Ethernet cable disconnected!" start_time = time.monotonic() while True: if self.link_status or ((time.monotonic() - start_time) > 5): break time.sleep(1) if self._debug: print("My Link is:", self.link_status) self._dhcp_client = None # Set DHCP if is_dhcp: ret = self.set_dhcp(hostname, dhcp_timeout) if ret != 0: self._dhcp_client = None assert ret == 0, "Failed to configure DHCP Server!"
def __init__(self, *args): self.spi = busio.SPI( clock = board.SCK_1, MISO = board.MISO_1, MOSI = board.MOSI_1 ) self.cs = digitalio.DigitalInOut(board.CE0_1) self._spi_device = SPIDevice(self.spi,self.cs) self._out_buf = bytearray(3) self._in_buf = bytearray(3)
def __init__(self, spi, cs, thermocouple_type=ThermocoupleType.K): self._device = SPIDevice(spi, cs, baudrate=500000, polarity=0, phase=1) # assert on any fault self._write_u8(_MAX31856_MASK_REG, 0x0) # configure open circuit faults self._write_u8(_MAX31856_CR0_REG, _MAX31856_CR0_OCFAULT0) # set thermocouple type # get current value of CR1 Reg conf_reg_1 = self._read_register(_MAX31856_CR1_REG, 1)[0] conf_reg_1 &= 0xF0 # mask off bottom 4 bits # add the new value for the TC type conf_reg_1 |= int(thermocouple_type) & 0x0F self._write_u8(_MAX31856_CR1_REG, conf_reg_1)
def __init__(self): self.rst = DigitalInOut(board.GP0) self.rst.direction = Direction.OUTPUT self.cs = DigitalInOut(board.GP1) self.cs.direction = Direction.OUTPUT self.rst.value = 0 self.cs.value = 1 self.spi = busio.SPI(clock=board.GP2, MOSI=board.GP3, MISO=board.GP4) self.device = SPIDevice(self.spi, self.cs) self.rst.value = 1 self.init()
def __init__(self, wave_freq=440, wave_phase=0, wave_type="sine", select="D6", m_clock=25000000, debug=False): import board import busio import digitalio # set up SPI bus interconnect, derive chip select pin (to allow multiple # WaveGenerator class instances), and create SPIDevice instance # Note that the 5Mhz AD9833 clock polarity is inverted from the default self._spi = busio.SPI(board.SCK, MOSI=board.MOSI) # setup SPI bus self._cs = digitalio.DigitalInOut(getattr( board, select)) # derive chip select pin from adafruit_bus_device.spi_device import SPIDevice # initiate SPI device manager self._device = SPIDevice(self._spi, self._cs, baudrate=5000000, polarity=1, phase=0) # input parameters self._wave_freq = wave_freq self._wave_phase = wave_phase self._wave_type = wave_type # initial register addresses self._freq_reg = 0 self._phase_reg = 0 # initial reset state self._reset = True # reset enabled # master clock self._m_clock = m_clock # debug parameters self._debug = debug if self._debug: print("*Init:", self.__class__) print("*Init: ", self.__dict__)
def __init__(self, spi, cs, xdcs, dreq): # Create SPI device for VS1053 self._cs = digitalio.DigitalInOut(cs) self._vs1053_spi = SPIDevice(spi, self._cs, baudrate=_COMMAND_BAUDRATE, polarity=0, phase=0) # Setup control lines. self._xdcs = digitalio.DigitalInOut(xdcs) self._xdcs.switch_to_output(value=True) self._dreq = digitalio.DigitalInOut(dreq) self._dreq.switch_to_input() # Reset chip. self.reset() # Check version is 4 (VS1053 ID). if self.version != 4: raise RuntimeError( 'Expected version 4 (VS1053) but got: {} Check wiring!'. format(self.version))
def __init__(self, spi, csn, ce, spi_frequency=10000000): self._spi = SPIDevice(spi, chip_select=csn, baudrate=spi_frequency) self.ce_pin = ce self.ce_pin.switch_to_output(value=False) self._status = 0 self._reg_write(0, 0x0E) if self._reg_read(0) & 3 != 2: raise RuntimeError("nRF24L01 Hardware not responding") self.power = False self._reg_write(3, 3) self._reg_write(6, 7) self._reg_write(2, 0) self._reg_write(0x1C, 0x3F) self._reg_write(1, 0x3F) self._reg_write(0x1D, 5) self._reg_write(4, 0x53) self._pipe0_read_addr = None self.channel = 76 self.payload_length = 32 self.flush_rx() self.flush_tx() self.clear_status_flags()
def __init__(self, linefreq, pgagain, ugain, igainA, igainB, igainC, cs_pin=None): pin = board.D5 if cs_pin is None else cs_pin # We'll need all the settings for the self._linefreq = linefreq self._pgagain = pgagain self._ugain = ugain self._igainA = igainA self._igainB = igainB self._igainC = igainC spi = busio.SPI(board.SCLK, board.MOSI, board.MISO) cs = digitalio.DigitalInOut(pin) # How to use SPI # https://learn.adafruit.com/circuitpython-basics-i2c-and-spi/spi-devices # https://circuitpython.readthedocs.io/projects/busdevice/en/latest/_modules/adafruit_bus_device/spi_device.html self._device = SPIDevice(spi, cs, baudrate=200000, polarity=1, phase=1) self._init_config()
import communications.groundstation as gs from communications.commands import CommandHandler import board import busio import time from adafruit_bus_device.spi_device import SPIDevice from communications.ax5043_manager.ax5043_driver import Ax5043 from communications.ax5043_manager.ax5043_manager import Manager #Radio setup driver = Ax5043(SPIDevice(busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO))) mgr = Manager(driver) ch = CommandHandler() #Pack command into a bytearray gs.registerCommand(ch,1,2,number1=7, number2=4) command = ch.pack_command(1,2,number1=7, number2=4) #Send the command to the satellite gs.transmitCommand(mgr, command) print('Transmitted') print('Entering Receiving Mode') cycleNumber = 1 #Enter listening mode while True: print('Cycle: ' + str(cycleNumber))
def __init__(self, spi_bus, cs, ref_voltage=3.3): self._spi_device = SPIDevice(spi_bus, cs) self._out_buf = bytearray(3) self._in_buf = bytearray(3) self._ref_voltage = ref_voltage
def __init__(self, spi, cs): self.i2c_device = SPIDevice(spi, cs) super().__init__()
def __init__(self, spi, cs): self.spi_device = SPIDevice(spi, cs) self.data = bytearray(4)
def __init__(self, num_led=8, order='rgb', mosi=10, sclk=11, ce=None, bus_speed_hz=8000000): """Initializes the library :param num_led: Number of LEDs in the strip :param order: Order in which the colours are addressed (this differs from strip to strip) :param mosi: Master Out pin. Use 10 for SPI0, 20 for SPI1, any GPIO pin for bitbang. :param sclk: Clock, use 11 for SPI0, 21 for SPI1, any GPIO pin for bitbang. :param ce: GPIO to use for Chip select. Can be any free GPIO pin. Warning: This will slow down the bus significantly. Note: The hardware CE0 and CE1 are not used :param bus_speed_hz: Speed of the hardware SPI bus. If glitches on the bus are visible, lower the value. """ self.num_led = num_led order = order.lower() # Just in case someone use CAPS here. self.rgb = RGB_MAP.get(order, RGB_MAP['rgb']) self.global_brightness = 4 # This is a 5 bit value, i.e. from 0 to 31. Conservative 1/8th, change if desired. self.use_bitbang = False # Two raw SPI devices exist: Bitbang (software) and hardware SPI. self.use_ce = False # If true, use the BusDevice abstraction layer on top of the raw SPI device self.leds = [self.LED_START, 0, 0, 0] * self.num_led # Pixel buffer if ce is not None: # If a chip enable value is present, use the Adafruit CircuitPython BusDevice abstraction on top # of the raw SPI device (hardware or bitbang) # The next line is just here to prevent an "unused" warning from the IDE digitalio.DigitalInOut(board.D1) # Convert the chip enable pin number into an object (reflection à la Python) ce = eval("digitalio.DigitalInOut(board.D" + str(ce) + ")") self.use_ce = True # Heuristic: Test for the hardware SPI pins. If found, use hardware SPI, otherwise bitbang SPI if mosi == 10: if sclk != 11: raise ValueError("Illegal MOSI / SCLK combination") self.spi = busio.SPI(clock=board.SCLK, MOSI=board.MOSI) elif mosi == 20: if sclk != 21: raise ValueError("Illegal MOSI / SCLK combination") self.spi = busio.SPI(clock=board.SCLK_1, MOSI=board.MOSI_1) else: # Use Adafruit CircuitPython BitBangIO, because the pins do not match one of the hardware SPI devices # Reflection à la Python to get at the digital IO pins self.spi = bitbangio.SPI(clock=eval("board.D" + str(sclk)), MOSI=eval("board.D" + str(mosi))) self.use_bitbang = True # Add the BusDevice on top of the raw SPI if self.use_ce: self.spibus = SPIDevice(spi=self.spi, chip_select=ce, baudrate=bus_speed_hz) else: # If the BusDevice is not used, the bus speed is set here instead while not self.spi.try_lock(): # Busy wait to acquire the lock pass self.spi.configure(baudrate=bus_speed_hz) self.spi.unlock() # Debug if self.use_ce: print("Use software chip enable") if self.use_bitbang: print("Use bitbang SPI") else: print("Use hardware SPI")
# -*- coding: utf-8 -*- import time import board import busio import digitalio from adafruit_bus_device.spi_device import SPIDevice cs = digitalio.DigitalInOut(board.A4) spi = busio.SPI(board.SCK, MOSI=board.MOSI) mdac_device = SPIDevice(spi, cs, baudrate=1000000, polarity=0, phase=0) def write_level(level): if level < 0 or level > 65536: return with mdac_device as device: high_byte, low_byte = divmod(level, 256) device.write(bytearray([3])) device.write(bytearray([high_byte])) device.write(bytearray([low_byte])) print('mdac-attenuator level {0}'.format(level)) time_delay = 1 while True: write_level(10000) time.sleep(time_delay) write_level(20000) time.sleep(time_delay)
def __init__(self, spi, cs): self._buffer = bytearray(6) self._device = SPIDevice(spi, cs, baudrate=500000, polarity=0, phase=1) self._write_register_byte(_REG_POWER_CTL, 0x08) self._write_register_byte(_REG_INT_ENABLE, 0x0) print('init done')
GPIO.setup(in1, GPIO.OUT) GPIO.setup(in2, GPIO.OUT) GPIO.setup(in3, GPIO.OUT) GPIO.setup(in4, GPIO.OUT) GPIO.setup(cali, GPIO.IN) #******!!! DE MOTOR PINNEN LAAGZETTEN !!!*******************************************************// GPIO.output(in1, GPIO.LOW) GPIO.output(in2, GPIO.LOW) GPIO.output(in3, GPIO.LOW) GPIO.output(in4, GPIO.LOW) #******!!! DE SPI CONFIGURATIE !!!**************************************************************// spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) # de spi bus initializeren #******!!! DE MCP 3008 CONFIGURATIE !!!*********************************************************// cs1 = digitalio.DigitalInOut(board.CE1) # chip select voor mcp3008 adc = SPIDevice(spi, cs1, baudrate=1000000) # mcp 3008 configureren voor spi nextActive = 0 # hulpvariabelen om te voorkomen dat pot meter constant waarde stuurt voor next ch prevActive = 0 # hulpvariabelen om te voorkomen dat pot meter constant waarde stuurt voor prev ch #******!!! PYGAME INITIALIZEREN !!!*************************************************************// ##pygame.init() # voor de display te 'drawen' hebben we pygame nodig #******!!! NOKIA 5110 DISPLAY GEBRUIKEN !!!*****************************************************// dc = digitalio.DigitalInOut(board.D23) # data/command op d23 zetten cs0 = digitalio.DigitalInOut( board.CE0) # chip select CE0 for display intitializeren reset = digitalio.DigitalInOut(board.D24) # reset pin op D24 pin zetten display = adafruit_pcd8544.PCD8544( spi, dc, cs0, reset, baudrate=1000000) # display SPI configureren display.bias = 4 # bias voor de display instellen display.contrast = 32 # contrast voor de print op het scherm display.invert = True # True voor gewoon false om display te inverteren #******!!! LETTERTYPEN LADEN VOOR OP SCHERM !!!*************************************************//
def __init__(self, spi_bus, cs, address): self._spi_device = SPIDevice(spi_bus, cs) self._out_buf = bytearray(4) self._in_buf = bytearray(4) self.cmd_write = MCP23SXX_CODE_WRITE | (address << 1) self.cmd_read = MCP23SXX_CODE_READ | (address << 1)
import busio import board import digitalio from adafruit_bus_device.spi_device import SPIDevice DEVICE_ADDRESS = 0x68 # device address of BMP280 board A_DEVICE_REGISTER = 0xD0 # device id register on the BMP280 board # The follow is for SPI communications cs = digitalio.DigitalInOut(board.A2) comm_port = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) device = SPIDevice(comm_port, cs) # pylint: disable-msg=no-member with device as bus_device: bus_device.write(bytes([A_DEVICE_REGISTER])) result = bytearray(1) bus_device.readinto(result) print("".join("{:02x}".format(x) for x in result))
import logging import time import board import busio from adafruit_bus_device.spi_device import SPIDevice from communications.ax5043_manager.ax5043_driver import Ax5043 from communications.ax5043_manager.ax5043_manager import Manager logging.basicConfig(level=logging.DEBUG) driver = Ax5043( SPIDevice(busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO))) mgr = Manager(driver)