int lis3dh_init(lis3dh_t *dev, spi_t spi, gpio_t cs_pin, gpio_t int1_pin, gpio_t int2_pin, lis3dh_scale_t scale) { uint8_t in; dev->spi = spi; dev->cs = cs_pin; dev->int1 = int1_pin; dev->int2 = int2_pin; dev->scale = 0; /* CS */ gpio_init(dev->cs, GPIO_DIR_OUT, GPIO_NOPULL); gpio_set(dev->cs); if (lis3dh_read_regs(dev, LIS3DH_REG_WHO_AM_I, 1, &in) < 0) { /* Communication error */ return -1; } if (in != LIS3DH_WHO_AM_I_RESPONSE) { /* Chip is not responding correctly */ return -1; } /* Set block data update and little endian mode. */ lis3dh_write_reg(dev, LIS3DH_REG_CTRL_REG4, (LIS3DH_CTRL_REG4_BDU_ENABLE | LIS3DH_CTRL_REG4_BLE_LITTLE_ENDIAN)); lis3dh_set_scale(dev, scale); return 0; }
upm_result_t lis3dh_update(const lis3dh_context dev) { assert(dev != NULL); // Max axes data length, 2 bytes per axis * 3 axes const int bufLen = 6; // Max temperature data length const int temperatureBufLen = 2; // We reuse the same array when reading acceleration and then temperature data uint8_t buf[bufLen]; if (lis3dh_read_regs(dev, LIS3DH_REG_OUT_X_L, buf, bufLen) != bufLen) { printf("%s: lis3dh_read_regs() failed to read %d bytes of axes data\n", __FUNCTION__, bufLen); return UPM_ERROR_OPERATION_FAILED; } // X MSB LSB dev->accX = INT16_TO_FLOAT(buf[1], buf[0]); // Y dev->accY = INT16_TO_FLOAT(buf[3], buf[2]); // Z dev->accZ = INT16_TO_FLOAT(buf[5], buf[4]); // Get the temperature if (lis3dh_read_regs(dev, LIS3DH_REG_OUT_ADC3_L, buf, temperatureBufLen) != temperatureBufLen) { printf("%s: lis3dh_read_regs() failed to read %d bytes of temperature data\n", __FUNCTION__, temperatureBufLen); return UPM_ERROR_OPERATION_FAILED; } dev->temperature = INT16_TO_FLOAT(buf[1], buf[0]); return UPM_SUCCESS; }
/** * @brief Write (both set and clear) bits of an 8-bit register on the LIS3DH. * * @param[in] addr Register address on the LIS3DH. * @param[in] mask Bitmask for the bits to modify. * @param[in] values The values to write to the masked bits. * * @return 0 on success * @return -1 on error */ static inline int lis3dh_write_bits(const lis3dh_t *dev, const lis3dh_reg_t reg, const uint8_t mask, const uint8_t values) { uint8_t tmp; if (lis3dh_read_regs(dev, reg, 1, &tmp) < 0) { /* Communication error */ return -1; } tmp &= ~mask; tmp |= (values & mask); if (lis3dh_write_reg(dev, reg, tmp) < 0) { /* Communication error */ return -1; } return 0; }
int lis3dh_read_aux_adc1(const lis3dh_t *dev, int16_t *out) { return lis3dh_read_regs(dev, LIS3DH_REG_OUT_AUX_ADC1_L, LIS3DH_ADC_DATA_SIZE, (uint8_t *)out); }