Read problem with basic SPI driver

Hi, I’m about to make a driver for a SPI device.

I’m using a pixracer board and as a test I tried to read the device id (whoami) of the mpu9250.
The read_registers() operation goes fine but the value read is wrong.
The value of the whoami register should be 0x71, but i get 0x00.

Can you tell me if there’s something wrong in the following code?
(I write it looking at AP_InertialSensor)

AP_HAL::OwnPtr<AP_HAL::SPIDevice> _dev;
uint8_t *_buffer;
_dev = hal.spi->get_device("mpu9250");
if (!_dev) {
    hal.console->printf("DEV NOT FOUND");
    return;
}

_dev->set_read_flag(0x80);

if (!_dev->get_semaphore()->take(HAL_SEMAPHORE_BLOCK_FOREVER)) {
    hal.console->printf("SEMAPHORE ERROR");
    return;
}

_dev->setup_checked_registers(7, 20);

_dev->set_speed(AP_HAL::Device::SPEED_LOW);

// random value because it reads 0 and wanted to be sure that it was the read to set it to 0
uint8_t id = 42;

// 0x75 = whoami reg addr
if(_dev->read_registers(0x75, _buffer, 1)){
    id = *_buffer;
    hal.console->printf("REGISTER READ");
}
else{
    hal.console->printf("READ ERROR");
    _dev->get_semaphore()->give();
    return;
}

if(id == 0x71){ // 0x71 = default whoami reg value
    hal.console->printf("ID CHECKED \n ID = %02x", id);
}
else{
    hal.console->printf("ID ERROR \n ID = %02x", id);
}
_dev->get_semaphore()->give();
return;

Thank you!

1 Like

Solved.

Instead of using a pointer in _dev->read_registers(0x75, _buffer, 1) it’s instead needed to pass a reference to a uint8_t.

uint8_t buffer = 0;
_dev->read_registers(0x75, &_buffer, 1))