I2CSensor.c 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #include "I2CSensor.h"
  2. #include "../sensors/SensorsDriver.h"
  3. static uint8_t sensors_count = 0;
  4. uint8_t readReg(I2CSensor* i2c_sensor, uint8_t reg) {
  5. //Блокировка шины
  6. furi_hal_i2c_acquire(i2c_sensor->i2c);
  7. uint8_t buff[1];
  8. furi_hal_i2c_read_mem(i2c_sensor->i2c, i2c_sensor->currentI2CAdr << 1, reg, buff, 1, 0xFF);
  9. furi_hal_i2c_release(i2c_sensor->i2c);
  10. return buff[0];
  11. }
  12. bool readRegArray(I2CSensor* i2c_sensor, uint8_t startReg, uint8_t len, uint8_t* data) {
  13. furi_hal_i2c_acquire(i2c_sensor->i2c);
  14. bool status = furi_hal_i2c_read_mem(
  15. i2c_sensor->i2c, i2c_sensor->currentI2CAdr << 1, startReg, data, len, 0xFF);
  16. furi_hal_i2c_release(i2c_sensor->i2c);
  17. return status;
  18. }
  19. bool writeReg(I2CSensor* i2c_sensor, uint8_t reg, uint8_t value) {
  20. //Блокировка шины
  21. furi_hal_i2c_acquire(i2c_sensor->i2c);
  22. uint8_t buff[1] = {value};
  23. bool status = furi_hal_i2c_write_mem(
  24. i2c_sensor->i2c, i2c_sensor->currentI2CAdr << 1, reg, buff, 1, 0xFF);
  25. furi_hal_i2c_release(i2c_sensor->i2c);
  26. return status;
  27. }
  28. bool unitemp_I2C_sensor_alloc(Sensor* sensor, uint8_t* anotherValues) {
  29. bool status = false;
  30. I2CSensor* instance = malloc(sizeof(I2CSensor));
  31. if(instance == NULL) {
  32. FURI_LOG_E(APP_NAME, "Sensor %s instance allocation error", sensor->name);
  33. return false;
  34. }
  35. instance->i2c = &furi_hal_i2c_handle_external;
  36. sensor->instance = instance;
  37. //Указание функций инициализации, деинициализации и обновления данных, а так же адреса на шине I2C
  38. status = sensor->type->allocator(sensor, anotherValues);
  39. //Установка адреса шины I2C
  40. if(anotherValues[0] >= instance->minI2CAdr && anotherValues[0] <= instance->maxI2CAdr) {
  41. instance->currentI2CAdr = anotherValues[0];
  42. } else {
  43. instance->currentI2CAdr = instance->minI2CAdr;
  44. }
  45. //Блокировка портов GPIO
  46. sensors_count++;
  47. unitemp_gpio_lock(unitemp_GPIO_getFromInt(15), &I2C);
  48. unitemp_gpio_lock(unitemp_GPIO_getFromInt(16), &I2C);
  49. return status;
  50. }
  51. bool unitemp_I2C_sensor_free(Sensor* sensor) {
  52. bool status = sensor->type->mem_releaser(sensor);
  53. free(sensor->instance);
  54. if(--sensors_count == 0) {
  55. unitemp_gpio_unlock(unitemp_GPIO_getFromInt(15));
  56. unitemp_gpio_unlock(unitemp_GPIO_getFromInt(16));
  57. }
  58. return status;
  59. }
  60. UnitempStatus unitemp_I2C_sensor_update(Sensor* sensor) {
  61. if(sensor->status != UT_OK) {
  62. sensor->type->initializer(sensor);
  63. }
  64. return sensor->type->updater(sensor);
  65. }