Re: SPI Software


Glyn M0XGT
 

On Sun, Feb 14, 2021 at 10:03 PM, G8ZHA wrote: 

I just want some software that will allow me to specify a number of bytes to be sent, then to allow me to load up the bytes and send them.

 An Arduino is probably the easiest for loading up some bytes and transferring them over SPI.

Cut and paste the code below into the Arduino IDE for a quick starting point - check the device datasheet for a sensible SPI bus speed and choose the SPIMode to match the SPI clock polarity and phase. The code transfers the bytes in buffer[] over SPI MOSI/MISO/CLK pins using Arduino pin 10 for SPI chip select and prints the sent and received data.  The screenshot is a capture of the data on the bus.

Glyn M0XGT

//---------------------------snip-------------------------
// Arduino SPI
#include <SPI.h>
#include <stdint.h>
 
// SPIMode CPOL CPHA
// ---------------
//   0      0    0
//   1      0    1
//   2      1    0
//   3      1    1
// ---------------
 
// SPI chip select pin
const int pin_cs = 10;
 
// SPI bus speed [Hz], bit-order, mode
SPISettings spi_settings(1000000, MSBFIRST, SPI_MODE3); 
 
// transfer bytes over SPI
void spi_transfer(uint8_t buffer[], int length, int pin_cs)
{
  digitalWrite(pin_cs, LOW);
  SPI.beginTransaction(spi_settings);
  SPI.transfer(buffer, length);
  SPI.endTransaction();
  digitalWrite(pin_cs, HIGH);
}
 
// print buffer
void print_buffer(String text, uint8_t buffer[], int n)
{
  Serial.print(text);
  Serial.print(":");
  for (int i = 0; i < n; i++) {
    Serial.print(' ');
    Serial.print(buffer[i], HEX);
  }
  Serial.print('\n');
}
 
void setup()
{
  // serial
  Serial.begin(19200);
  while (!Serial) {
    ; // wait for serial
  }
 
  // SPI
  SPI.begin();
  pinMode(pin_cs, OUTPUT);  // chip select pin
}
 
void loop()
{
  // fill a buffer with some bytes
  uint8_t buff[] = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef };
  int n = sizeof(buff) / sizeof(uint8_t);
 
  // print the buffer
  print_buffer("sending", buff, n);
 
  // transfer bytes
  spi_transfer(buff, n, pin_cs);
 
  // print what came back
  print_buffer("received", buff, n);
 
  delay(1000);  // [mS]
}
//---------------------------snip-------------------------

Join UKMicrowaves@groups.io to automatically receive all group messages.