from machine import Pin, SPI
import utime
# SPI setup for master (RP2040 supports SPI0 and SPI1)
spi_master = SPI(0, sck=Pin(2), miso=Pin(4), mosi=Pin(3), polarity=0, phase=0)
cs = Pin(5, Pin.OUT) # Chip Select pin
def receive_bits_from_slave():
cs.value(0) # Activate slave (CS low)
utime.sleep_us(10) # Allow slave to prepare
received_bits = "" # Store received 16-bit binary string
# Send dummy bytes to generate clock and read MISO
for _ in range(16):
# Send a dummy byte (0x00) to trigger the clock and receive data
received_byte = spi_master.read(1)
# Convert the received byte to a bit
received_bit = (received_byte[0] & 1) # Extract LSB
print("Received bit:", received_bit)
# Collect bits in a string
received_bits += str(received_bit)
cs.value(1) # Deactivate slave (CS high)
# Convert the 16-bit binary string to a temperature value
temperature = int(received_bits, 2) / 100.0
# Print the full binary and temperature value
print(f"Complete 16-bit Binary: {received_bits}")
print(f"Temperature: {temperature:.2f} °C")
while True:
receive_bits_from_slave()
utime.sleep(5) # Wait 5 seconds before the next request
from machine import Pin, SPI, ADC
import utime
# SPI setup for slave (RP2040 supports SPI0 and SPI1)
spi_slave = SPI(1, sck=Pin(18), miso=Pin(16), mosi=Pin(19), polarity=0, phase=0)
cs = Pin(17, Pin.IN, Pin.PULL_UP) # Chip Select pin
# Internal temperature sensor setup
sensor_temp = ADC(4) # Use ADC(4) for internal temperature sensor
conversion_factor = 3.3 / 65535
samples = 7
# Median filter to reduce noise
def median_filter_adc():
readings = [sensor_temp.read_u16() for _ in range(samples)]
readings.sort()
return readings[samples // 2]
# Convert temperature to 16-bit binary
def get_temperature_binary():
median_reading = median_filter_adc()
voltage = median_reading * conversion_factor
temperature_c = 27 - (voltage - 0.706) / 0.001721
# Scale temperature to a 16-bit integer
temp_16bit = int(temperature_c * 100)
print(f"Temperature: {temperature_c:.2f} °C")
return temp_16bit.to_bytes(2, 'big') # Convert to 2 bytes (big-endian format)
while True:
# Wait until CS goes low (start of communication)
while cs.value(0):
pass
# Get the 16-bit temperature value
temp_binary = get_temperature_binary()
# Send the 16-bit temperature as 2 bytes
spi_slave.write(temp_binary)