#!/usr/bin/env python

# SPI loopback speed test script
# Connect MOSI and MISO together
#
# For spidev0.0 on the Raspberry Pi those are 
#   pins GPIO10 and GPIO9 respectively
#   physical pins 19 and 21 respectively
#
# This example code is in the public domain.
#
# Michel Deslierres <https://sigmdel.ca/michel>
#
# May 4, 2020

import spidev
import time

SPI_BUS = 0          # spidev0
SPI_SS  = 0          # spidev0.0, can be 1 also

# setup SPI
spi = spidev.SpiDev(SPI_BUS, SPI_SS)

send = [0, 1, 2, 4, 8, 16, 32, 64, 128, 255]
speed = 250000
ok = True

try:
  while ok:
    spi.max_speed_hz = speed
    print()
    print("spi.max_speed_hz:", spi.max_speed_hz)
    print("TX:", send)
    recvd = spi.xfer( [0, 1, 2, 4, 8, 16, 32, 64, 128, 255] )
    print("RX:", recvd)
    ok = recvd == send

    if ok:
      print("Success")
    else:
      print("Failed")
    speed = 2*speed

finally:
    spi.close()
