Skip to contentSkip to conversation

hw/sensor: Add lsm303dlhc magnetometer device

PATCH Superseded Kevin Townsend 2 participants 6 messages Sep 21, 2021 – Sep 28, 2021 Arm/Amlogic Meson SoC support

v3 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

PATCH v3 1/1 hw/sensor: Add lsm303dlhc magnetometer device

This commit adds emulation of the magnetometer on the LSM303DLHC. It allows the magnetometer's X, Y and Z outputs to be set via the mag-x, mag-y and mag-z properties, as well as the 12-bit temperature output via the temperature property.

---
 hw/sensor/Kconfig          |   4 +
 hw/sensor/lsm303dlhc_mag.c | 754 +++++++++++++++++++++++++++++++++++++
 hw/sensor/meson.build      |   1 +
 3 files changed, 759 insertions(+)
 create mode 100644 hw/sensor/lsm303dlhc_mag.c
hw/sensor/Kconfig +4 -0
index a2b55a4fdb..1684e9bb3d 100644
@@ -17,3 +17,7 @@ config ADM1272
 config MAX34451
     bool
     depends on I2C
+
+config LSM303DLHC_MAG
+    bool
+    depends on I2C
hw/sensor/lsm303dlhc_mag.c new file +754 -0

754 lines not on this page · raw message

hw/sensor/meson.build +1 -0
index 034e3e0207..95406abd24 100644
@@ -3,3 +3,4 @@ softmmu_ss.add(when: 'CONFIG_TMP421', if_true: files('tmp421.c'))
 softmmu_ss.add(when: 'CONFIG_EMC141X', if_true: files('emc141x.c'))
 softmmu_ss.add(when: 'CONFIG_ADM1272', if_true: files('adm1272.c'))
 softmmu_ss.add(when: 'CONFIG_MAX34451', if_true: files('max34451.c'))
+softmmu_ss.add(when: 'CONFIG_LSM303DLHC_MAG', if_true: files('lsm303dlhc_mag.c'))
Signature · 1 line
2.30.1 (Apple Git-130)
#1 lore raw
Quoted 5 lines · Kevin Townsend

This commit adds emulation of the magnetometer on the LSM303DLHC. It allows the magnetometer's X, Y and Z outputs to be set via the mag-x, mag-y and mag-z properties, as well as the 12-bit temperature output via the temperature property.

Thanks; this is generally looking pretty good. I have some review commenst below.

Quoted 38 lines
---
 hw/sensor/Kconfig          |   4 +
 hw/sensor/lsm303dlhc_mag.c | 754 +++++++++++++++++++++++++++++++++++++
 hw/sensor/meson.build      |   1 +
 3 files changed, 759 insertions(+)
 create mode 100644 hw/sensor/lsm303dlhc_mag.c
hw/sensor/lsm303dlhc_mag.c new file +30 -0
+static void lsm303dlhc_mag_get_x(Object *obj, Visitor *v, const char *name,
+                                 void *opaque, Error **errp)
+{
+    LSM303DLHCMagState *s = LSM303DLHC_MAG(obj);
+    int64_t value = s->x;
+
+    /* Convert to uT where 1000 = 1 uT. Conversion factor depends on gain. */
+    value *= 1000000;
+    switch (s->crb >> 5) {
+        case 1:
+            /* 11 lsb per uT. */
+            value /= 11000;
+            break;
+        case 2:
+            /* 8.55 lsb per uT. */
+            value /= 8550;
+            break;
+        case 3:
+            /* 6.70 lsb per uT. */
+            value /= 6700;
+            break;
+        case 4:
+            /* 4.50 lsb per uT. */
+            value /= 4500;
+            break;
+        case 5:
+            /* 4.00 lsb per uT. */
+            value /= 4000;
+            break;
+        case 6:

hw/sensor/lsm303dlhc_mag.c line 111

Quoted 10 lines
hw/sensor/lsm303dlhc_mag.c new file +10 -0
+            /* 3.30 lsb per uT. */
+            value /= 3300;
+            break;
+        case 7:
+            /* 2.30 lsb per uT. */
+            value /= 2300;
+            break;
+        default:
+            break;
+    }

This gain conversion code is quite long-winded and duplicated between the get_x and get_y functions. I think we could reduce it:

/*
* Conversion factor from Gauss to sensor values for each GN gain setting,
* in units "lsb per Gauss" (see data sheet table 3). There is no documented
* behaviour if the GN setting in CRB is incorrectly set to 0b000;
* we arbitrarily make it the same as 0b001.
*/
uint32_t xy_gain[] = { 1100, 1100, 855, 670, 450, 400, 330, 230 }; uint32_t z_gain[] = { 980, 980, 760, 600, 400, 355, 295, 205 };

static void lsm303dlhc_mag_get_x(Object *obj, Visitor *v, const char *name,
void *opaque, Error **errp)

{
    LSM303DLHCMagState *s = LSM303DLHC_MAG(obj);
    int64_t value;
    int gm = extract32(s->crb, 5, 3);

    /* Convert to uT where 1000 = 1 uT. Conversion factor depends on gain. */
    int64_t value = muldiv64(s->x, 100000, xy_gain[gm]);
    visit_type_int(v, name, &value, errp);
}

static void lsm303dlhc_mag_set_x(Object *obj, Visitor *v, const char *name,
void *opaque, Error **errp)

{
    LSM303DLHCMagState *s = LSM303DLHC_MAG(obj);
    int64_t value;
    int64_t reg;
    int gm = extract32(s->crb, 5, 3);

    if (!visit_type_int(v, name, &value, errp)) {
        return;
    }

    reg = muldiv64(value, xy_gain[gm], 100000);

    /* Make sure we are within a 12-bit limit. */
    if (reg > 2047 || reg < -2048) {
        error_setg(errp, "value %lld out of register's range", value);
        return;
    }

    s->x = (int16_t)reg;
}

Similarly for y and z (z uses z_gain[], obviously).

(muldiv64() is in "qemu/host-utils.h"; it avoids potential overflows by calculating a * b / c with a higher-precision intermediate value; we don't need that in the get but we do for the set, and it makes the two functions clearly the inverse of each other to use it both places.)

Quoted 15 lines
hw/sensor/lsm303dlhc_mag.c new file +15 -0
+/*
+ * Callback handler whenever a 'I2C_START_RECV' (read) event is received.
+ */
+static void lsm303dlhc_mag_read(LSM303DLHCMagState *s)
+{
+    s->len = 0;
+
+    /*
+     * The address pointer on the LSM303DLHC auto-increments whenever a byte
+     * is read, without the master device having to request the next address.
+     *
+     * The auto-increment process has the following logic:
+     *
+     *   - if (s->pointer == 8) then s->pointer = 3
+     *   - else: if (s->pointer >= 12) then s->pointer = 0

hw/sensor/lsm303dlhc_mag.c line 451

Quoted 10 lines
hw/sensor/lsm303dlhc_mag.c new file +10 -0
+     *   - else: s->pointer += 1
+     *
+     * Reading an invalid address return 0.
+     *
+     * The auto-increment logic is only taken into account in this driver
+     * for the LSM303DLHC_MAG_REG_OUT_* and LSM303DLHC_MAG_REG_TEMP_OUT_*
+     * registers, which are the two common uses cases for it. Accessing either
+     * of these register sets will also populate the rest of the related
+     * dataset.
+     */

I thought we'd agreed to implement the whole of the auto-increment logic, not just for specific registers ?

Could I ask you to write a test case for this new device? tests/qtest/tmp105-test.c is probably a good model to follow. It doesn't have to be an exhaustive functionality test, but some basic tests like:
* if you set the sensor values via the qom properties and read them back do you get the same value you read?
* if you set the values, change the gain, read back, ditto?
* does reading the sensor values via the i2c registers give the right results?
would help in ensuring this doesn't accidentally regress in future. (Make the test case a patch 2 in the patchset.)

thanks
-- PMM

#2 lore raw

Hi Peter,

Thanks for the updated review.

Quoted 3 lines · Peter Maydell

I thought we'd agreed to implement the whole of the auto-increment logic, not just for specific registers ?

The problem I have here is ... how many bytes are we willing to buffer? There's no
reason I can't request 512 registers, for example. Should we limit the buffer length
to a single 'full' set of register values?

Kevin

#3 lore raw
Quoted 7 lines · Kevin Townsend

Hi Peter,

Thanks for the updated review.

Quoted 1 line · Peter Maydell
Quoted 7 lines
Quoted 2 lines

I thought we'd agreed to implement the whole of the auto-increment logic, not just for specific registers ?

The problem I have here is ... how many bytes are we willing to buffer? There's no reason I can't request 512 registers, for example. Should we limit the buffer length to a single 'full' set of register values?

I think the underlying reason this seems awkward is the way this i2c device has been implemented as "at START_RECV create the whole buffer that we're going to read, and then for every call to the recv callback, read out one byte from that buffer". That's how the other hw/sensor/ i2c devices seem to have been written, and it's kinda OK if the device doesn't support reading more than one register at once, but it's a bit awkward if they can handle multiple-register big reads. (Also, I suspect a lot of those other sensors just copied the code structure from the original tmp105 implementation -- which is now 13 years old -- and maybe even for those devices it's not the best approach.)

Anyway you don't have to write it that way: you can have the action at START_RECV be "capture the sensor readings" (AIUI this is what the h/w does, and it sets the LOCK bit here), and then the action on the recv callback is "return the right byte for the current address-pointer value, which might be a register value or might be the captured sensor data, and auto-increment the address-pointer".

(It's not entirely clear to me from the datasheet when exactly the device captures and locks mag and temperature readings, and when it then lets go of that locked data and lets you read a fresh set, but https://electronics.stackexchange.com/a/265561
is a random person with some info suggesting that the values read are locked for the duration of the read transaction and not re-captured. If that's so then "capture once at START_RECV" would DTRT. The event for "end of transaction" is I2C_FINISH, if we need/want to do something at that point.)

-- PMM

#4 lore raw
In reply to Peter Maydell

Hi Peter,

Quoted 3 lines · Peter Maydell

I thought we'd agreed to implement the whole of the auto-increment logic, not just for specific registers ?

Thanks again for the feedback. Dealing with one register value at a time (versus a buffer of response values) does simplify the code flow.

The following code appears to handle multi-byte reads correctly. I just wanted to confirm this is what you were looking for before moving on to the test code?

/*
* Callback handler whenever a 'I2C_START_RECV' (read) event is received. */
static void lsm303dlhc_mag_read(LSM303DLHCMagState *s)
{
/*
* Set the LOCK bit whenever a new read attempt is made. This will be
* cleared in I2C_FINISH. Note that DRDY is always set to 1 in this
driver.

     */
    s->sr = 0x3;
}

/*
* Callback handler whenever a 'I2C_FINISH' event is received. */
static void lsm303dlhc_mag_finish(LSM303DLHCMagState *s)

{
    /*
     * Clear the LOCK bit when the read attempt terminates.
     * This bit is initially set in the I2C_START_RECV handler.
     */
    s->sr = 0x1;
}

/*
* Low-level slave-to-master transaction handler (read attempts). */
static uint8_t lsm303dlhc_mag_recv(I2CSlave *i2c)

{
    LSM303DLHCMagState *s = LSM303DLHC_MAG(i2c);

    switch (s->pointer) {
    case LSM303DLHC_MAG_REG_CRA:
        s->buf = s->cra;
        break;
    case LSM303DLHC_MAG_REG_CRB:
        s->buf = s->crb;
        break;
    case LSM303DLHC_MAG_REG_MR:
        s->buf = s->mr;
        break;
    case LSM303DLHC_MAG_REG_OUT_X_H:
        s->buf = (uint8_t)(s->x >> 8);
        break;
    case LSM303DLHC_MAG_REG_OUT_X_L:
        s->buf = (uint8_t)(s->x);
        break;
    case LSM303DLHC_MAG_REG_OUT_Z_H:
        s->buf = (uint8_t)(s->z >> 8);
        break;
    case LSM303DLHC_MAG_REG_OUT_Z_L:
        s->buf = (uint8_t)(s->z);
        break;
    case LSM303DLHC_MAG_REG_OUT_Y_H:
        s->buf = (uint8_t)(s->y >> 8);
        break;
    case LSM303DLHC_MAG_REG_OUT_Y_L:
        s->buf = (uint8_t)(s->y);
        break;
    case LSM303DLHC_MAG_REG_SR:
        s->buf = s->sr;
        break;
    case LSM303DLHC_MAG_REG_IRA:
        s->buf = s->ira;
        break;
    case LSM303DLHC_MAG_REG_IRB:
        s->buf = s->irb;
        break;
    case LSM303DLHC_MAG_REG_IRC:
        s->buf = s->irc;
        break;
    case LSM303DLHC_MAG_REG_TEMP_OUT_H:
        /* Check if the temperature sensor is enabled or not (CRA & 0x80).
*/
        if (s->cra & 0x80) {
            s->buf = (uint8_t)(s->temperature >> 8);
        } else {
            s->buf = 0;
        }
        break;
    case LSM303DLHC_MAG_REG_TEMP_OUT_L:
        if (s->cra & 0x80) {
            s->buf = (uint8_t)(s->temperature & 0xf0);
        } else {
            s->buf = 0;
        }
        break;
    default:
        s->buf = 0;
        break;
    }

    /*
     * The address pointer on the LSM303DLHC auto-increments whenever a byte
     * is read, without the master device having to request the next
address.
     *
     * The auto-increment process has the following logic:
     *
     *   - if (s->pointer == 8) then s->pointer = 3
     *   - else: if (s->pointer >= 12) then s->pointer = 0
     *   - else: s->pointer += 1
     *
     * Reading an invalid address return 0.
     */
    if (s->pointer == LSM303DLHC_MAG_REG_OUT_Y_L) {
        s->pointer = LSM303DLHC_MAG_REG_OUT_X_H;
    } else if (s->pointer >= LSM303DLHC_MAG_REG_IRC) {
        s->pointer = LSM303DLHC_MAG_REG_CRA;
    } else {
        s->pointer++;
    }

    return s->buf;
}
#5 lore raw
Quoted 32 lines · Kevin Townsend

Hi Peter,

Quoted 3 lines · Peter Maydell

I thought we'd agreed to implement the whole of the auto-increment logic, not just for specific registers ?

Thanks again for the feedback. Dealing with one register value at a time (versus a buffer of response values) does simplify the code flow.

The following code appears to handle multi-byte reads correctly. I just wanted to confirm this is what you were looking for before moving on to the test code?

/*
* Callback handler whenever a 'I2C_START_RECV' (read) event is received. */
static void lsm303dlhc_mag_read(LSM303DLHCMagState *s)

{
    /*
     * Set the LOCK bit whenever a new read attempt is made. This will be
     * cleared in I2C_FINISH. Note that DRDY is always set to 1 in this driver.
     */
    s->sr = 0x3;
}

/*
* Callback handler whenever a 'I2C_FINISH' event is received. */
static void lsm303dlhc_mag_finish(LSM303DLHCMagState *s)

Quoted 7 lines
{
    /*
     * Clear the LOCK bit when the read attempt terminates.
     * This bit is initially set in the I2C_START_RECV handler.
     */
    s->sr = 0x1;
}

I would just inline these in the event lsm303dlhc_mag_event() function. You might also #define some constants for the register bits.

Quoted 81 lines

/*
* Low-level slave-to-master transaction handler (read attempts). */
static uint8_t lsm303dlhc_mag_recv(I2CSlave *i2c)

{
    LSM303DLHCMagState *s = LSM303DLHC_MAG(i2c);

    switch (s->pointer) {
    case LSM303DLHC_MAG_REG_CRA:
        s->buf = s->cra;
        break;
    case LSM303DLHC_MAG_REG_CRB:
        s->buf = s->crb;
        break;
    case LSM303DLHC_MAG_REG_MR:
        s->buf = s->mr;
        break;
    case LSM303DLHC_MAG_REG_OUT_X_H:
        s->buf = (uint8_t)(s->x >> 8);
        break;
    case LSM303DLHC_MAG_REG_OUT_X_L:
        s->buf = (uint8_t)(s->x);
        break;
    case LSM303DLHC_MAG_REG_OUT_Z_H:
        s->buf = (uint8_t)(s->z >> 8);
        break;
    case LSM303DLHC_MAG_REG_OUT_Z_L:
        s->buf = (uint8_t)(s->z);
        break;
    case LSM303DLHC_MAG_REG_OUT_Y_H:
        s->buf = (uint8_t)(s->y >> 8);
        break;
    case LSM303DLHC_MAG_REG_OUT_Y_L:
        s->buf = (uint8_t)(s->y);
        break;
    case LSM303DLHC_MAG_REG_SR:
        s->buf = s->sr;
        break;
    case LSM303DLHC_MAG_REG_IRA:
        s->buf = s->ira;
        break;
    case LSM303DLHC_MAG_REG_IRB:
        s->buf = s->irb;
        break;
    case LSM303DLHC_MAG_REG_IRC:
        s->buf = s->irc;
        break;
    case LSM303DLHC_MAG_REG_TEMP_OUT_H:
        /* Check if the temperature sensor is enabled or not (CRA & 0x80). */
        if (s->cra & 0x80) {
            s->buf = (uint8_t)(s->temperature >> 8);
        } else {
            s->buf = 0;
        }
        break;
    case LSM303DLHC_MAG_REG_TEMP_OUT_L:
        if (s->cra & 0x80) {
            s->buf = (uint8_t)(s->temperature & 0xf0);
        } else {
            s->buf = 0;
        }
        break;
    default:
        s->buf = 0;
        break;
    }

    /*
     * The address pointer on the LSM303DLHC auto-increments whenever a byte
     * is read, without the master device having to request the next address.
     *
     * The auto-increment process has the following logic:
     *
     *   - if (s->pointer == 8) then s->pointer = 3
     *   - else: if (s->pointer >= 12) then s->pointer = 0
     *   - else: s->pointer += 1
     *
     * Reading an invalid address return 0.
     */
    if (s->pointer == LSM303DLHC_MAG_REG_OUT_Y_L) {
Quoted 8 lines
        s->pointer = LSM303DLHC_MAG_REG_OUT_X_H;
    } else if (s->pointer >= LSM303DLHC_MAG_REG_IRC) {
        s->pointer = LSM303DLHC_MAG_REG_CRA;
    } else {
        s->pointer++;
    }

    return s->buf;

I think you don't need to write the value to s->buf, you can just use a local variable and return that. Nothing should be able to read the value back out of s->buf later. I think you should also implement the actual lock part, to avoid wrong values in the case of
* read starts, reads X_H
* s->x updated via the QOM property setter
* read continues, reads X_L
Basically just capture x,y,z,temp at the point of lock, and then return those values in the recv function.

Quoted 1 line

}

thanks
-- PMM