SPI - 读写资料

材料准备

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

范例说明

SPI是一种快速且强大的通讯协议,并通常在微处理器中被用来检索传感器的数据或输出图像讯号。

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

程式码

首先,将下面的代码上传到 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
请先确认已安装QQ通讯软体