#include <SPI.h> // Include the SPI library for ESP32
// Define the SPI pins for the ESP32
// These should match how you've wired them in Wokwi,
// and conceptually match the pins defined in your custom chip.
// For ESP32, typical VSPI pins:
#define SCK_PIN 18
#define MISO_PIN 19
#define MOSI_PIN 23
#define CS_PIN 5 // You can choose any available GPIO for CS
// Buffer to store received image data
// This should be the same size as BUFFER_LEN in your custom chip
// (which is 120 * 160 = 19200 bytes)
#define IMAGE_BUFFER_SIZE (120 * 160)
byte imageData[IMAGE_BUFFER_SIZE];
void setup() {
Serial.begin(115200);
while (!Serial); // Wait for serial port to connect
Serial.println("ESP32 SPI Camera Master Example");
// Set up the Chip Select pin as an output
pinMode(CS_PIN, OUTPUT);
digitalWrite(CS_PIN, HIGH); // Ensure CS is high (inactive) initially
// Initialize the SPI bus
// The ESP32 has two SPI buses (HSPI and VSPI). VSPI is generally preferred for user applications.
// SPI.begin(SCK, MISO, MOSI, SS) or SPI.begin() for default pins.
// We'll explicitly set the pins here for clarity.
SPI.begin(SCK_PIN, MISO_PIN, MOSI_PIN, -1); // -1 means don't use default SS (we'll manage CS_PIN manually)
SPI.setClockDivider(SPI_CLOCK_DIV8); // Set SPI speed (e.g., F_CPU/8)
SPI.setBitOrder(MSBFIRST); // Most Significant Bit first
SPI.setDataMode(SPI_MODE0); // SPI Mode 0
Serial.println("SPI Initialized.");
}
void loop() {
Serial.println("\nRequesting image data from camera...");
// Select the camera (pull CS low)
digitalWrite(CS_PIN, LOW);
delayMicroseconds(10); // Small delay for chip to react
// Read data from the camera
// The custom chip is configured to send BUFFER_LEN bytes when CS is low.
// We will read that many bytes.
for (int i = 0; i < IMAGE_BUFFER_SIZE; i++) {
// Send a dummy byte (0x00) and receive a byte from the slave
imageData[i] = SPI.transfer(0x00);
// You can print a few bytes to verify data is coming through
// if (i < 20 || i > IMAGE_BUFFER_SIZE - 20) { // Print first/last 20 bytes
// Serial.printf("Byte %d: 0x%02X\n", i, imageData[i]);
// }
}
// Deselect the camera (pull CS high)
digitalWrite(CS_PIN, HIGH);
Serial.printf("Received %d bytes of image data.\n", IMAGE_BUFFER_SIZE);
// At this point, imageData array contains the simulated image data.
// You would typically process this data here (e.g., display on a screen,
// save to SD card, send over network, etc.).
// For now, we'll just confirm receipt.
delay(5000); // Wait 5 seconds before requesting another image
}