AS5048A PWM Angle Read

I have the following code from the simpleFOC website on sensing the angle with a magnetic sensor using PWM

#include <SimpleFOC.h>

// MagneticSensorPWM(uint8_t _pinPWM, int _min, int _max)
// - _pinPWM:         the pin that is reading the pwm from magnetic sensor
// - _min_raw_count:  the minimal length of the pulse (in microseconds)
// - _max_raw_count:  the maximal length of the pulse (in microseconds)
MagneticSensorPWM sensor = MagneticSensorPWM(9, 4, 904);
void doPWM(){sensor.handlePWM();}

void setup() {
  // monitoring port

  // initialise magnetic sensor hardware
  // comment out to use sensor in blocking (non-interrupt) way

  Serial.println("Sensor ready");

void loop() {
  // IMPORTANT - call as frequently as possible
  // update the sensor values 
  // display the angle and the angular velocity to the terminal

When i run the code, the angle that the motor is currently positioned is displayed however that angle doesn’t change when i move the motor. If i move the motor and rerun the code I’ll get the new angle on startup but I cant seem to get a live angle read. how can I sort this out?


Not sure what is going on here… which MCU type is this? Is the pin you’re using interrupt-capable?

I strongly recommend not to use PWM mode of this sensor. It’s less accurate, and it’s slow, meaning it will greatly limit your performance…

1 Like

I also encountered serious issues with analog and also both digital reading methods, unfortunately, though, mostly timing issues. With analog the voltage has to ramp when it wraps around and this causes a glitch where the apparent velocity is very high and the wrong way :(. Always something. I think there is a place for PWM at e.g. 1khz, especially with the smoothing sensor thing, because the rotor has inertia so it can’t change position that much in 1 ms anyway. I rather regret not sticking with PWM, although I am hoping my future is sensorless anyway now…

If you watch the sensor on oscilloscope, are you sure it’s outputting properly? That initial reading could be random noise.