SPI — pymcu.hal.spi#
from pymcu.hal.spi import SPI
SPI bus communication in master mode. Available for AVR (ATmega328P).
class SPI#
SPI(cs: str = "PB2")#
Initializes the hardware SPI peripheral in master mode, Mode 0, MSB-first, at fosc/4
(4 MHz at 16 MHz clock). cs is the chip-select pin, auto-asserted on select().
Pinout (ATmega328P / Arduino Uno):
Pin |
Arduino |
Function |
|---|---|---|
|
D13 |
SCK |
|
D12 |
MISO |
|
D11 |
MOSI |
|
D10 |
SS / CS |
Methods#
Method |
Description |
|---|---|
|
Drive SS low (begin transaction) |
|
Drive SS high (end transaction) |
|
Full-duplex byte exchange |
|
Send byte (discard received byte) |
|
Alias for |
|
Alias for |
Examples#
Context manager (recommended)#
from pymcu.hal.spi import SPI
spi = SPI()
with spi:
spi.write(0xAB)
b = spi.transfer(0x00)
with spi: calls select() on enter and deselect() on exit, even if the block returns early.
74HC595 shift register#
from pymcu.hal.spi import SPI
from pymcu.time import delay_ms
from pymcu.types import uint8
def main():
spi = SPI()
data: uint8 = 0x01
while True:
with spi:
spi.write(data)
data = (data << 1) | (data >> 7) # rotate left
delay_ms(100)
SoftSPI (bit-bang)#
Use SoftSPI for arbitrary GPIO pins (no hardware SPI constraint):
from pymcu.hal.spi import SoftSPI
from pymcu.types import uint8
spi = SoftSPI(sck="PD4", mosi="PD5", miso="PD6", cs="PD7")
with spi:
b: uint8 = spi.transfer(0x55)