simplefoc / Arduino-FOC

Arduino FOC for BLDC and Stepper motors - Arduino Based Field Oriented Control Algorithm Library
https://docs.simplefoc.com
MIT License
1.95k stars 511 forks source link

SPI Magnetic sensor reads value correctly only once, after spi begin #307

Closed RaphZufferey closed 10 months ago

RaphZufferey commented 10 months ago

Hi! Thank you for the fantastic library, it is proving to be of great help! I am running into an issue trying to read an SPI sensor. Sensor gets declared as instructed:

  MagneticSensorSPI sensor = MagneticSensorSPI(PA15, 14, 0x3FFF);
  SPIClass SPI_3(PB5, PB4, PB3); //(mosi, miso, sclk)

Then initialized (sensor.init(&SPI_3);) in the setup loop. I am reading the sensor in the main loop just like in the example: Serial.print((float)sensor.getSensorAngle()); Serial.print("\t");

The issue: the sensor returns the correct value only once. On subsequent calls, it returns the same value as before. I managed to circumvent this issue by adding spi->begin(); in the library, which gets then called every time:

// function reading the raw counter of the magnetic sensor
int MagneticSensorSPI::getRawCount(){
    spi->begin();
    return (int)MagneticSensorSPI::read(angle_register);
}

This is obviously not the correct way of solving this issue, and I was hoping someone could look into this?

runger1101001 commented 10 months ago

Are you calling sensor.update() during your test? This is called automatically by motor.loopFOC() but if you’re just testing the sensor stand-alone you have to call it yourself.

RaphZufferey commented 10 months ago

Solved, thank you very much!