Using the esp32 with the as5048a magnetic sensor

We have tried both HSPI and VSPI ports on the ESP 32, with it currently being wired to the VSPI ports and are running the demo code on GitHub:

#include <SimpleFOC.h>

// MagneticSensorSPI(MagneticSensorSPIConfig_s config, int cs)
//  config  - SPI config
//  cs      - SPI chip select pin 
// magnetic sensor instance - SPI
MagneticSensorSPI sensor = MagneticSensorSPI(AS5048_SPI, 10);
// alternative constructor (chipselsect, bit_resolution, angle_read_register, )
// MagneticSensorSPI sensor = MagneticSensorSPI(5, 14, 0x3FFF);

void setup() {
  // monitoring port
  Serial.begin(115200);

  // initialise magnetic sensor hardware
  sensor.init();

  Serial.println("Sensor ready");
  _delay(1000);
}

void loop() {
  // iterative function updating the sensor internal variables
  // it is usually called in motor.loopFOC()
  // this function reads the sensor hardware and 
  // has to be called before getAngle nad getVelocity
  sensor.update();
  // display the angle and the angular velocity to the terminal
  Serial.print(sensor.getAngle());
  Serial.print("\t");
  Serial.println(sensor.getVelocity());
}

I set up the Arduino IDE accordingly, installing the Simple FOC library, adding the GitHub link to the additional board manager URL, setting the board to esp32-wroom-da (I assume this is right, the board is esp-wroom-32u).

When I move the gm3506 motor, the serial plotter’s output is crazy, fluctuating constantly between positive and negative values, and then settling on an arbitrary value.

Any ideas on what the issue could be?

Hi @callum , welcome to SimpleFOC!

Perhaps add a small delay to the main loop - esp32 is very fast, it won’t give the sensor much time between updates…

Since you’re writing to the serial port the IO will block anyways, but it might be better to add a delay to this loop: delay(1000); once per second should be enough.

In terms of the SPI, your code looks fine. Of course you have to use the right SPI port and pins on the ESP32. If you need to change the pins, you have to do so in the code before calling sensor.init();

You can pass a SPI object to the sensor: sensor.init(&SPI2); to use a different one from the default.

Thanks for your help!

The delay helped, along with securing the wiring… The magnetic sensor kept detaching despite my best soldering efforts :slight_smile:

1 Like