import sys
import time
from machine import Pin
# Define SPI pins (Master role)
# GP2: MOSI (Master Out Slave In)
# GP3: MISO (Master In Slave Out)
# GP4: SCLK (Clock)
# GP5: CS (Chip Select, Active-Low)
MOSI = Pin(2, Pin.OUT, value=0)
MISO = Pin(3, Pin.IN, Pin.PULL_DOWN)
SCLK = Pin(4, Pin.OUT, value=0) # CPOL = 0 (Clock idle low)
CS = Pin(5, Pin.OUT, value=1) # CS active-low (Idle high)
# Using CPOL=0, CPHA=0 scheme
def spi_transfer_byte(b):
CS.value(0) # Assert Chip Select (Active Low)
time.sleep_us(10)
received_byte = 0
for i in range(7, -1, -1):
# Set MOSI bit (MSB first)
bit = (b >> i) & 1
MOSI.value(bit)
time.sleep_us(10)
SCLK.value(1) # Rising edge (Sample/Shift)
# Read MISO bit back
miso_bit = MISO.value()
received_byte |= miso_bit << i
time.sleep_us(10)
SCLK.value(0) # Falling edge
CS.value(1) # Deassert Chip Select
time.sleep_us(10)
return received_byte
print("Software SPI Master Ready. Enter text:")
while True:
line = sys.stdin.readline()
if not line:
continue
text = line.strip()
if not text:
continue
print(f"Transmitting via SPI: {text}")
received_chars = []
for char in text:
b = ord(char)
rx_b = spi_transfer_byte(b)
received_chars.append(chr(rx_b))
decoded_str = "".join(received_chars)
print(f"Received back via MISO loopback: {decoded_str}")