Untitled

 avatar
unknown
plain_text
a month ago
2.5 kB
11
Indexable
import spidev
import time

# Initialize SPI
spi = spidev.SpiDev()
spi.open(0, 0)  # Use SPI bus 0, device 0 (CE0)
spi.max_speed_hz = 1000000  # Set SPI clock speed (1 MHz)
spi.mode = 0b00  # SPI mode 0 (Clock Polarity 0, Clock Phase 0)

def send_data(data):
    """
    Sends data to the SPI slave and receives a response.
    Args:
        data (list): List of bytes to send (e.g., [0x01, 0x02, 0x03]).
    Returns:
        list: Response received from the SPI slave.
    """
    try:
        response = spi.xfer2(data)  # Send data and receive response
        print(f"Sent: {data}, Received: {response}")
        return response
    except Exception as e:
        print(f"SPI communication error: {e}")
        return []

try:
    while True:
        # Data to send (3 bytes)
        test_data = [0x01, 0x02, 0x03]

        # Send data and get response
        response = send_data(test_data)

        # Add a delay for readability and pacing
        time.sleep(1)

except KeyboardInterrupt:
    # Cleanup SPI interface
    spi.close()
    print("SPI communication ended.")




=========================================

#include <SPI.h>

// SPI Pin Definitions
#define SCK_PIN 18   // SPI Clock pin
#define MISO_PIN 19  // Master In Slave Out pin
#define MOSI_PIN 23  // Master Out Slave In pin
#define SS_PIN 5     // Slave Select pin

void setup() {
  // Initialize SPI as Slave
  SPI.begin(SCK_PIN, MISO_PIN, MOSI_PIN, SS_PIN);

  // Enable internal pull-up resistor on SS_PIN
  pinMode(SS_PIN, INPUT_PULLUP);

  // Start Serial for debugging
  Serial.begin(115200);
  Serial.println("SPI Slave Initialized");
}

void loop() {
  // Buffer to store multiple received bytes
  uint8_t receivedData[3]; // Buffer for 3 bytes
  uint8_t dummyData = 0x00; // Dummy data to send back

  // Check if Slave Select (SS_PIN) is LOW
  if (digitalRead(SS_PIN) == LOW) {
    // Read 3 bytes of data from the master
    for (int i = 0; i < 3; i++) {
      receivedData[i] = SPI.transfer(dummyData); // Receive bytes and send dummy data
    }

    // Print the received data for debugging
    Serial.print("Received: ");
    for (int i = 0; i < 3; i++) {
      Serial.print("0x");
      Serial.print(receivedData[i], HEX);
      Serial.print(" ");
    }
    Serial.println();
  } else {
    Serial.println("Waiting for SS_PIN to go LOW...");
  }

  delay(100); // Small delay for readability
}

Leave a Comment