I2CSensor.c 2.6 KB

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