def _eeprom_spi_write_byte( spi: busio.SPI, csel: digitalio.DigitalInOut, address: int, data: int, timeout: float = 1.0, ) -> bool: # Make sure address is only one byte: if address > 255: return False # Make sure data is only one byte: if data > 255: return False # Wait for WIP to be low if not _eeprom_spi_wait(spi, csel, timeout): return False # Enable writing csel.value = False spi.write(bytearray([EEPROM_SPI_WREN])) csel.value = True # Write to address csel.value = False spi.write(bytearray([EEPROM_SPI_WRITE, address, data])) csel.value = True return True
def __init__(self, freq, sc, mo, mi): self._spi = SPI(sc, mo, mi) if not self._spi.try_lock(): print("ERROR: busio.SPIBus: no lock for configure()") else: try: self._spi.configure(baudrate=freq) finally: self._spi.unlock()
def read_adc(spi: busio.SPI, channel: int) -> int: """ Read a single ADC channel of the MCP3008 """ # TODO: This is still kinda slow, investigate Python's 'spidev' # library or https://iosoft.blog/2020/06/11/fast-data-capture-raspberry-pi/ rx_buf = bytearray(3) tx_buf = bytearray((0x01, 0x80 | (channel << 4), 0x00)) with open(f'/sys/class/gpio/gpio{CS_PIN}/value', 'w') as cs_file: cs_file.write('0') spi.write_readinto(tx_buf, rx_buf) with open(f'/sys/class/gpio/gpio{CS_PIN}/value', 'w') as cs_file: cs_file.write('1') raw_val = ((rx_buf[1] & 0x3) << 8) | rx_buf[2] return raw_val
def __init__(self): self.connection = self.CONFIG['connection'] self.pin = self.CONFIG['downlink_pin'] spi_nr = self.ARG if spi_nr == 0: spi = SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI) else: spi = SPI(clock=board.SCK_1, MISO=board.MISO_1, MOSI=board.MOSI_1) pin_dig = getattr(board, f"D{ self.connection}") cs = DigitalInOut(pin_dig) self.mcp = mcp3008.MCP3008(spi_bus=spi, cs=cs) self.data = self._get_data()
def pid_loop(state): i = 0 pidhist = config.pid_hist_len * [0.] temphist = config.temp_hist_len * [0.] temperr = config.temp_hist_len * [0] temp = 25. lastsettemp = state['brewtemp'] lasttime = time() sensor = MAX31855(SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO), DigitalInOut(board.D5)) pid = PID(Kp=config.pidc_kp, Ki=config.pidc_ki, Kd=config.pidc_kd, setpoint=state['brewtemp'], sample_time=config.time_sample, proportional_on_measurement=False, output_limits=(-config.boundary, config.boundary)) while True: try: temp = sensor.temperature del temperr[0] temperr.append(0) del temphist[0] temphist.append(temp) except RuntimeError: del temperr[0] temperr.append(1) if sum(temperr) >= 5 * config.temp_hist_len: print("Temperature sensor error!") call(["killall", "python3"]) avgtemp = sum(temphist) / config.temp_hist_len if avgtemp <= 0.9 * state['brewtemp']: pid.tunings = (config.pidc_kp, config.pidc_ki, config.pidc_kd) else: pid.tunings = (config.pidw_kp, config.pidw_ki, config.pidw_kd) if state['brewtemp'] != lastsettemp: pid.setpoint = state['brewtemp'] lastsettemp = state['brewtemp'] pidout = pid(avgtemp) pidhist.append(pidout) del pidhist[0] avgpid = sum(pidhist) / config.pid_hist_len state['i'] = i state['temp'] = temp state['pterm'], state['iterm'], state['dterm'] = pid.components state['avgtemp'] = round(avgtemp, 2) state['pidval'] = round(pidout, 2) state['avgpid'] = round(avgpid, 2) sleeptime = lasttime + config.time_sample - time() sleep(max(sleeptime, 0.)) i += 1 lasttime = time()
def __init__(self): self.is_on = False self.temp_f = 0 self.temp_f_target = 212 self.control_p = 2 self.control_i = 0.1 self.control_d = 2 self.temp_history = [] self.shed_on_time = None self.sched_off_time = None self.last_on_time = time.time() self.last_off_time = None self.pid_freq = 1 self.read_freq = 10 self.post_freq = 10 self.stop_funcs = [] self.mqtt_client = MQTTClient() self.pid = PID(self.control_p, self.control_i, self.control_d, setpoint=self.temp_f_target) self.pid.output_limits = (0, 100) spi = SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI) cs = DigitalInOut(board.D5) self.sensor = MAX31855(spi, cs) he_pin = 26 # GPIO26 GPIO.setmode(GPIO.BCM) GPIO.setup(he_pin, GPIO.OUT) self.he_pwm = GPIO.PWM(he_pin, self.pid_freq * 3) self.he_pwm.start(0)
def test(): """Scrolling Marquee""" try: # Implementation dependant pin and SPI configuration if implementation.name == 'circuitpython': import board from busio import SPI from digitalio import DigitalInOut cs_pin = DigitalInOut(board.P0_15) dc_pin = DigitalInOut(board.P0_17) rst_pin = DigitalInOut(board.P0_20) spi = SPI(clock=board.P0_24, MOSI=board.P0_22) else: from machine import Pin, SPI cs_pin = Pin(5) dc_pin = Pin(17) rst_pin = Pin(16) spi = SPI(2, baudrate=14500000, sck=Pin(18), mosi=Pin(23)) # Create the SSD1351 display: display = Display(spi, dc=dc_pin, cs=cs_pin, rst=rst_pin) display.clear() # Draw non-moving circles display.fill_circle(63, 63, 63, color565(27, 72, 156)) display.fill_circle(63, 63, 53, color565(0, 0, 0)) display.fill_circle(63, 63, 43, color565(189, 0, 36)) display.fill_circle(63, 63, 33, color565(0, 0, 0)) # Load Marquee image display.draw_image('images\Rototron128x26.raw', 0, 50, 128, 26) # Set up scrolling display.set_scroll(horiz_offset=1, vert_start_row=50, vert_row_count=26, vert_offset=0, speed=1) display.scroll(True) while True: # Do nothing, scrolling handled by hardware sleep(1) except KeyboardInterrupt: display.cleanup()
def __init__(self, logger): self._logger = logger self._logger.log_info("Initializing display") spi = SPI(clock=SCK, MOSI=MOSI, MISO=MISO) self._driver = ILI9341(spi, cs=DigitalInOut(D8), dc=DigitalInOut(D24), rst=DigitalInOut(D25)) self._driver.fill(0)
def test(): """Scrolling Marquee.""" try: # Implementation dependant pin and SPI configuration if implementation.name == 'circuitpython': import board from busio import SPI from digitalio import DigitalInOut cs_pin = DigitalInOut(board.P0_15) dc_pin = DigitalInOut(board.P0_17) rst_pin = DigitalInOut(board.P0_20) spi = SPI(clock=board.P0_24, MOSI=board.P0_22) else: from machine import Pin, SPI cs_pin = Pin(16) dc_pin = Pin(4) rst_pin = Pin(17) # Baud rate of 40000000 seems about the max spi = SPI(1, baudrate=40000000, sck=Pin(14), mosi=Pin(13)) # Create the ILI9341 display: display = Display(spi, dc=dc_pin, cs=cs_pin, rst=rst_pin) display.clear() # Draw non-moving circles display.fill_rectangle(0, 0, 239, 99, color565(27, 72, 156)) display.fill_rectangle(0, 168, 239, 151, color565(220, 27, 72)) # Load Marquee image display.draw_image('images/Rototron128x26.raw', 56, 120, 128, 26) # Set up scrolling display.set_scroll(top=152, bottom=100) spectrum = list(range(152, 221)) + list(reversed(range(152, 220))) while True: for y in spectrum: display.scroll(y) sleep(.1) except KeyboardInterrupt: display.cleanup()
def _eeprom_spi_read_byte( spi: busio.SPI, csel: digitalio.DigitalInOut, address: int, timeout: float = 1.0 ) -> Tuple[bool, bytearray]: # Make sure address is only one byte: if address > 255: return False, bytearray() # Wait for WIP to be low if not _eeprom_spi_wait(spi, csel, timeout): return False, bytearray() # Read byte from address csel.value = False result = bytearray(1) spi.write(bytearray([EEPROM_SPI_READ, address])) spi.readinto(result) csel.value = True return True, result
def _eeprom_spi_wait( spi: busio.SPI, csel: digitalio.DigitalInOut, timeout: float = 1.0 ) -> bool: # Continually read from STATUS register timestamp = time.monotonic() while time.monotonic() < timestamp + timeout: # Perfrom RDSR operation csel.value = False result = bytearray(1) spi.write(bytearray([EEPROM_SPI_RDSR])) spi.readinto(result) csel.value = True # Mask out and compare WIP bit if (result[0] & (1 << EEPROM_SPI_WIP_BIT)) == 0: return True return False
class SPIBus(object): """SPI bus access.""" def __init__(self, freq, sc, mo, mi): self._spi = SPI(sc, mo, mi) if not self._spi.try_lock(): print("ERROR: busio.SPIBus: no lock for configure()") else: try: self._spi.configure(baudrate=freq) finally: self._spi.unlock() @property def bus(self): return self._spi def write_readinto(self, wbuf, rbuf): if self._spi.try_lock(): try: self._spi.write_readinto(wbuf, rbuf) finally: self._spi.unlock()
async def init(self, e=None): self.e = e spi = SPI(clock=SCK, MOSI=MOSI, MISO=MISO) self.disp = ST7789(spi, rotation=270, width=128, height=160, x_offset=0, y_offset=0, baudrate=24000000, cs=DigitalInOut(self.CS_PIN), dc=DigitalInOut(self.DC_PIN), rst=DigitalInOut(self.RESET_PIN)) if self.disp.rotation % 180 == 90: self.height = self.disp.width self.width = self.disp.height else: self.width = self.disp.width self.height = self.disp.height self.backlight = PWMOut(D22, frequency=2000, duty_cycle=0) self.clear() await self.setBacklight(await self.e.config.get('backlight')) self.fonts = { 'timer': ImageFont.truetype('./fonts/SF-Compact-Display-Medium.ttf', 36), 'subtitle': ImageFont.truetype('./fonts/SF-Pro-Display-Regular.ttf', 16), 'alert': ImageFont.truetype('./fonts/SF-Pro-Display-Semibold.ttf', 28), 'prompt': ImageFont.truetype('./fonts/SF-Pro-Display-Semibold.ttf', 20), 'mini': ImageFont.truetype('./fonts/SF-Pro-Display-Semibold.ttf', 13), } self.colors = { 'preheat': '#ff7300', 'cook': '#ffd600', 'notify': '#634dd3', 'checkpoint': '#3f91ff', 'poweroff': '#e93838', 'cool': '#f3fbff', }
def test(): """CircuitPython Text, Shape & Sprite""" if implementation.name != 'circuitpython': print() print('This demo is for CircuitPython only!') exit() try: # Configuratoin for CS and DC pins: cs_pin = DigitalInOut(board.P0_15) dc_pin = DigitalInOut(board.P0_17) rst_pin = DigitalInOut(board.P0_20) # Setup SPI bus using hardware SPI: spi = SPI(clock=board.P0_24, MOSI=board.P0_22) # Create the ILI9341 display: display = Display(spi, dc=dc_pin, cs=cs_pin, rst=rst_pin) display.clear() # Load Fixed Font fixed = XglcdFont('fonts/FixedFont5x8.c', 5, 8, letter_count=96) # Title WIDTH = 128 text = 'CircuitPython Demo' # Measure text and center length = fixed.measure_text(text) x = int((WIDTH / 2) - (length / 2)) display.draw_text(x, 6, text, fixed, color565(255, 255, 0)) # Draw title outline display.draw_rectangle(0, 0, 127, 20, color565(0, 255, 0)) # Load sprite logo = BouncingSprite('images/blinka45x48.raw', 45, 48, 239, 319, 1, display) while True: timer = monotonic() logo.update_pos() logo.draw() # Attempt to set framerate to 30 FPS timer_dif = .033333333 - (monotonic() - timer) if timer_dif > 0: sleep(timer_dif) except KeyboardInterrupt: display.cleanup()
def mountspi(): import board,os,storage from busio import SPI from digitalio import DigitalInOut spi = SPI(board.A5,board.A7,board.A6) cs = DigitalInOut(board.A0) flash = SPIFlash(spi,cs) bdev = SPIFlashBlockDevice(flash,nblocks=2048,debug=False) try: vfs = storage.VfsFat(bdev) vfs.ilistdir('/') except OSError: print("Formatting device") storage.VfsFat.mkfs(bdev) vfs = storage.VfsFat(bdev) storage.mount(vfs,"/spi")
from board import APA102_SCK, APA102_MOSI from busio import SPI from time import sleep # Istantiate DotStar LED dotstar = SPI(APA102_SCK, APA102_MOSI) def setPixel(red, green, blue): if not dotstar.try_lock(): return data = bytearray([ 0x00, 0x00, 0x00, 0x00, 0xff, blue, green, red, 0xff, 0xff, 0xff, 0xff ]) dotstar.write(data) dotstar.unlock() sleep(0.01)
# Image and Temp Block Location temp_location = {'x':200, 'y':12} #---------------------------------------------------------------- # Display Initialization #---------------------------------------------------------------- import displayio # Replease any display connections (just in case) displayio.release_displays() # Initialize SPI Display from busio import SPI spi = SPI(SCK, MOSI) display_bus = displayio.FourWire( spi, command=EPD_DC, chip_select=EPD_CS, baudrate=1000000 ) #from time import sleep #sleep(1) # Not sure why this was in original Adafruit example script from adafruit_il0373 import IL0373 display = IL0373( display_bus, width=DISPLAY_WIDTH, height=DISPLAY_HEIGHT, rotation=270, black_bits_inverted=False, color_bits_inverted=False,
import requests import board import digitalio import busio from busio import SPI import adafruit_max31855 import time from datetime import datetime, timedelta app = Flask(__name__) cors = CORS(app) #app.config['CORS_HEADERS'] = 'Content-Type' #api = Api(app) spi_a = SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI) spi_b = SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI) cs_a = digitalio.DigitalInOut(board.D5) cs_b = digitalio.DigitalInOut(board.D6) sensorA = adafruit_max31855.MAX31855( spi_a, cs_a, ) sensorB = adafruit_max31855.MAX31855(spi_b, cs_b) @app.route('/', methods=['GET']) def index(): data = {
# Bipolar stepper -- the two coils are A0-A1 and B0-B1. pin_a0 = DigitalInOut(board.D8) pin_a0.direction = Direction.OUTPUT pin_a1 = DigitalInOut(board.D7) pin_a1.direction = Direction.OUTPUT pin_b0 = DigitalInOut(board.D5) pin_b0.direction = Direction.OUTPUT pin_b1 = DigitalInOut(board.D6) pin_b1.direction = Direction.OUTPUT # The h-bridge takes a PWM input, one for each of A and B. pin_pwm_a = PWMOut(board.D9, frequency=200000, duty_cycle=0) pin_pwm_b = PWMOut(board.D4, frequency=200000, duty_cycle=0) # SPI bus connected to the encoder. spi = SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) spi.try_lock() spi.configure(baudrate=10000000, polarity=0, phase=1) spi.unlock() spi_cs = DigitalInOut(board.A2) spi_cs.direction = Direction.OUTPUT def read_encoder(): """ Returns averaged encoder value in the range (0,_MICROSTEPS_PER_REV). """ reading = 0 for _ in range(_ENCODER_SAMPLES): # Send SPI signal to read the raw value from the magnetic encoder. spi_cs.value = False
https://github.com/micropython/micropython/blob/master/drivers/nrf24l01/nrf24l01test.py ''' import time, struct import board import digitalio as dio from busio import SPI from adafruit_circuitpython_nrf24l01 import NRF24L01 pipes = (b'\x01\x02\x03\x04\x00', b'\x01\x02\x03\x04\x01') ce = dio.DigitalInOut(board.D5) cs = dio.DigitalInOut(board.D7) spi = SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) nrf = NRF24L01(spi, cs, ce) TX_DELAY = 1 RX_POLL_DELAY = 0.5 def master(): nrf.open_tx_pipe(pipes[0]) nrf.open_rx_pipe(1, pipes[1]) nrf.stop_listening() i = 0 while True: try:
import board from busio import I2C, SPI I2C_BUS = I2C(board.SDA, board.SCL) SPI_BUS = SPI(board.MISO, board.MOSI, board.SCK) class Serial_Manager: def __init__(self, ser_objects=None): self._mgr = [] if ser_objects is not None: for ser in ser_objects: self.insert(ser) @property def get_ports(self): result = [] for obj in self._mgr: result.insert(obj.port) return result def insert(self, obj, index=None): self._mgr.insert(len(self._mgr) - 1 if index is None else index, obj) def remove(self, port): for i, obj in enumerate(self._mgr): if obj.port == port: self._mgr.remove(i) def get_obj(self, port): for obj in self._mgr:
def stopbutton( channel ): # see: https://raspberrypihq.com/use-a-push-button-with-raspberry-pi-gpio/ connect gpioButtonPin to 3.3V, preferably through a resistor STOP_EVENT.set() GPIO.setmode(GPIO.BCM) GPIO.setup(gpioOvenPin, GPIO.OUT) GPIO.setup( gpioButtonPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN ) # Set pin to be an input pin and set initial value to be pulled low (off) GPIO.add_event_detect(gpioButtonPin, GPIO.RISING, callback=stopbutton) #stuff needed for reading the temperature spi = SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI) cs = DigitalInOut(board.D5) sensor = adafruit_max31855.MAX31855(spi, cs) #Create a fake sensor: TODO #sensor = types.SimpleNamespace() #sensor.temperature=110 ProgramRunning = False CurrentProgramName = '' CurrentStep = 0 thermocouplebroken = False app = Flask(__name__)
from busio import SPI from digitalio import DigitalInOut from ssd1351 import Display from adafruit_ble.uart import UARTServer from adafruit_bluefruit_connect.packet import Packet from adafruit_bluefruit_connect.button_packet import ButtonPacket from random import randint, seed from time import monotonic, sleep # Configuration for CS, DC and Reset pins (Feather nRF52840 Express): cs_pin = DigitalInOut(board.D11) dc_pin = DigitalInOut(board.D10) rst_pin = DigitalInOut(board.D9) # Setup SPI bus using hardware SPI: spi = SPI(clock=board.SCK, MOSI=board.MOSI) # Create the SSD1351 display: display = Display(spi, dc=dc_pin, cs=cs_pin, rst=rst_pin) display.clear() display.contrast(5) NORTH = const(0) EAST = const(1) SOUTH = const(2) WEST = const(3) UP = ButtonPacket.UP DOWN = ButtonPacket.DOWN LEFT = ButtonPacket.LEFT RIGHT = ButtonPacket.RIGHT BORDER_WIDTH = const(2)
# Create a servo object, my_servo. my_servo = servo.ContinuousServo(pwm) # Connect the I2C i2c = I2C(SCL, SDA) # Connect to the magnetometer # Following is for MLX90393 sensor # Possible addresses (depending on A0/A1 setting) are # 0x0C, 0x0D, 0x0E and 0x0F magsensor = MLX90393(i2c, address=0x0C, gain=GAIN_1X) # Connect to the rtc #rtc = PCF8523(i2c) # Set up SPI for talking to SD card spi = SPI(SCK, MOSI=MOSI, MISO=MISO) cs = DigitalInOut(D10) # Time variables # Comment: all is done in nanoseconds b/c time.monotonic # looses accuracy after a few hours readcount = 0 # Just to keep track read_nextime = monotonic_ns() fileout_nextime = read_nextime print_nextime = read_nextime # Statistics variable: The system detects when the short filter value (fltval) # rises above the long filter value (medval). It then uses the time between # subsequent such events to determine the rotation frequency. The last 5 # measurements are averaged to determine the speed correction. magval = 0.0 # input value
xtb1_cs = DigitalInOut(board.D35) xtb1_DRDY = DigitalInOut(board.D36) led.direction = Direction.OUTPUT sd_cs.direction = Direction.OUTPUT xtb1_cs.direction = Direction.OUTPUT xtb1_DRDY.direction = Direction.INPUT led.value = 0 sd_cs.value = 1 xtb1_cs.value = 1 sdcard = False filename = 'temporary' spi = SPI(board.SCK, board.MOSI, board.MISO) try: neopix = DigitalInOut(board.NEOPIXEL) neopix.direction = Direction.OUTPUT except Exception as e: print(e) try: sdcard = adafruit_sdcard.SDCard(spi, sd_cs) vfs = VfsFat(sdcard) mount(vfs, "/sd") path.append("/sd") sdcard = True name = 'XTB-40_000' files = [] for i in range(0, 100):