SPI on RP2040 Zero

Hello,
I’ve been looking for a while on how to get the SPI to work on RP2040 so I’m sharing.

#include "Arduino.h"
#include "Wire.h"
#include "SPI.h"
#include "SimpleFOC.h"
#include "SimpleFOCDrivers.h"
#include "encoders/as5048a/MagneticSensorAS5048A.h"

#define CS_ENC 1 // some digital pin that you're using as the nCS pin
MagneticSensorAS5048A sensor1(CS_ENC);

void setup() {
  // https://github.com/earlephilhower/arduino-pico/blob/master/libraries/SPI/src/SPI.cpp
  // https://arduino-pico.readthedocs.io/en/latest/pins.html
  // https://arduino-pico.readthedocs.io/en/latest/spi.html
  SPI.setRX(0); // MISO
  SPI.setTX(3); // MOSI
  SPI.setSCK(2); // SCK
  SPI.setCS(1); // CS Chip Select
  sensor1.init();
}

void loop() {
  // update the sensor (only needed if using the sensor without a motor)
  sensor1.update();
  // get the angle, in radians, including full rotations
  float a1 = sensor1.getAngle();
  Serial.println(a1);
  // get the velocity, in rad/s - note: you have to call getAngle() on a
  // regular basis for it to work
  float v1 = sensor1.getVelocity();
  // get the angle, in radians, no full rotations
  float a2 = sensor1.getCurrentAngle();
  // Serial.println(a2);
  //  get the raw 14 bit value
  uint16_t raw = sensor1.readRawAngle();
  // read the CORDIC magnitude value, a measure of the magnet field strength
  float m1 = sensor1.readMagnitude();
  // check for errors
  if (sensor1.isErrorFlag()) {
    AS5048Error error = sensor1.clearErrorFlag();
    if (error.parityError) { // also error.framingError, error.commandInvalid
      // etc...
    }
  }
}
2 Likes

This might seem trivial, but it is a good idea to break things down to a level this small. This would be good for someone who has to test their sensor using this board.