
This guide explains how to perform SPI communication using MicroPython on an STM32F4 microcontroller. It covers initializing the SPI interface, controlling a chip select pin, and exchanging data with an SPI device such as the MPU9250 sensor.
Previous guide about SPI transmit can be found here.
In this guide, we shall cover the following:
- Firmware Development.
- MPU9250 Connection.
- Results.
1. Firmware Development:
The MPU9250 has been covered in details in this guide.
Here, we are interested in performing communication using SPI.
We start by importing the following libraries:
import machine import time
Initialize the SPI as follows:
# SPI1: SCK=PA5, MISO=PA6, MOSI=PA7 spi = machine.SPI(1, baudrate=1_000_000, polarity=0, phase=0, bits=8, firstbit=machine.SPI.MSB)
Set PA0 as CS pin:
# Chip Select on PA0 cs = machine.Pin('PA0', machine.Pin.OUT) cs.value(1) # Deselect by default
Next, we shall read who I am register of MPU9250 which is 0x78:
WHO_AM_I = 0x75 # Register address for identity check
The function to read the register:
def read_who_am_i(): tx = bytearray([WHO_AM_I | 0x80, 0x00]) # Set MSB for read rx = bytearray(2) cs.value(0) spi.write_readinto(tx, rx) cs.value(1) return rx[1]
- tx holds the address to be read along with dummy byte of 0x00.
- rx holds the bytes to be read.
Next, set CS to low, followed by spi.write_readinto(tx,rx)
This function will read and write data over SPI bus. The size of received data is determined by the tx array.
Finally, set CS pin to high.
Next, loop the reading on who I am register every 1 second:
# --- Loop: Read WHO_AM_I every second --- while True: who_am_i = read_who_am_i() print("WHO_AM_I:", hex(who_am_i)) time.sleep(1)
Hence, the entire code as follows:
import machine import time # SPI1: SCK=PA5, MISO=PA6, MOSI=PA7 spi = machine.SPI(1, baudrate=1_000_000, polarity=0, phase=0, bits=8, firstbit=machine.SPI.MSB) # Chip Select on PA0 cs = machine.Pin('PA0', machine.Pin.OUT) cs.value(1) # Deselect by default WHO_AM_I = 0x75 # Register address for identity check def read_who_am_i(): tx = bytearray([WHO_AM_I | 0x80, 0x00]) # Set MSB for read rx = bytearray(2) cs.value(0) spi.write_readinto(tx, rx) cs.value(1) return rx[1] # --- Loop: Read WHO_AM_I every second --- while True: who_am_i = read_who_am_i() print("WHO_AM_I:", hex(who_am_i)) time.sleep(1)
Click on run as following:

2. Connection:
The connection as following:
Since STM32F411 Nucleo64 has arduino pinout, we shall use the D13, D12 and D11 for SPI communication, to find which pins they are, we can refer to Nucleo-64 user manual, we can find the following:


Hence, the connection as following:
STM32F411 Nucleo-64 | MPU9250 Module |
5V | Vcc |
GND | GND |
PA0 | nCS |
PA5 (SCK) | SCL |
PA7 (MOSI) | SDA |
PA6 (MISO) | AD0 |
3. Results:
You should able to get 0x73 as shown below:

Happy coding 😉
Add Comment