Ameba MicroPython: SPI – Read and Write Data

SPI - Read and Write Data

Materials

  • AmebaD [ AMB23 / AMB21 / AMB22 / BW16 / BW16-TypeC ] x 1
  • Arduino UNO x 1

Example

SPI is a fast and robust communication protocol that are commonly found on many microcontrollers and is often used to retrieve sensor data or output image signal to a display.

AMB21/AMB22

Unit CLK MISO MOSI CS
0 PB_20 PB_19 PB_18 PB_21
1 PB_6 PB_5 PB_4 PB_7

AMB23

Unit CLK MISO MOSI CS
1 PA_14 PA_13 PA_12 PA_15

BW16/BW16-TypeC

Unit CLK MISO MOSI CS
1 PA_14 PA_13 PA_12 PA_15

Code

First, upload the code below into Arduino UNO.

#include
volatile boolean received;
volatile byte receivedData;
ISR (SPI_STC_vect)        //Interrupt routine function 
{
  receivedData = SPDR;   // Get the received data from SPDR register
  received = true;       // Sets received as True 
}
void setup()
{
  Serial.begin(115200);
  pinMode(MISO,OUTPUT);   //Sets MISO as OUTPUT
  SPCR |= _BV(SPE);       //Turn on SPI in Slave Mode
  received = false;
  SPI.attachInterrupt();  //Activate SPI Interrupt
}
void loop()
{ 
  if(received) {                        
    SPDR = receivedData;    // send back the received data, this is not necessary, only for demo purpose
    received = false;
    Serial.println(receivedData, HEX);
  }
}

Then on the Ameba board copy and paste the following code line by line into REPL to see their effects.

from machine import SPI
spi = SPI(0) # Only support 2 sets of SPI -- 0 or 1
spi.write(b"123") # Write number 123, and don't care about received data
spi.read(8, 0x42) # Read 8 bytes while writing 0x42 for each byte