SPI - 讀寫資料

材料準備

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

範例說明

SPI是一種快速且强大的通訊協議,並通常在微處理器中被用來檢索傳感器的數據或輸出圖像訊號。

AMB21/AMB22
Unit CLK MISO MOSI CS
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

程式碼

首先,將下面的代碼上傳到 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);
  }
}

然後在Ameba板子上把下面的代碼逐行複制粘貼到REPL中,觀察結果。

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
Please confirm that QQ communication software is installed
請先確認已安裝QQ通訊軟體