1
0

main.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include <stdio.h>
  2. #include "sdkconfig.h"
  3. #include "freertos/FreeRTOS.h"
  4. #include "freertos/task.h"
  5. #include "esp_system.h"
  6. #include "esp_spi_flash.h"
  7. #include "freertos/queue.h"
  8. #include "driver/ledc.h"
  9. #include "driver/pcnt.h"
  10. #include "esp_attr.h"
  11. #include "esp_log.h"
  12. #include "config.h"
  13. #include "wifi.h"
  14. // Externs
  15. extern void ledc_init(void);
  16. extern void init_pcnt_unit();
  17. extern float getkWh();
  18. extern void mqtt_init();
  19. extern void sendMQTTMessage(const char * topic, const char * data);
  20. // Chip info:
  21. // This is esp32 chip with 2 CPU cores, WiFi/BT/BLE, silicon revision 1, 4MB external flash
  22. /** Electric meter:
  23. * 10000 impulses per kWh
  24. * Some normal max number could be 120 kWh/24h = 5 kWh/hour = 50000 pulses/hour = 833 pulses/min = 14 pulses/sec
  25. *
  26. * Counter is 16 bit signed = Max 32768 pulses = Will NOT work for one hour !!!!!
  27. * So we need some other way of counting higher numbers that will last for one h
  28. * Probably we need to use interrupts !
  29. */
  30. void app_main(void)
  31. {
  32. printf("HomeEnergyMeter ESP32\n");
  33. init_pcnt_unit();
  34. ledc_init();
  35. #ifdef WIFI_ENABLED
  36. initWifi(); // Init WIFI
  37. #endif
  38. vTaskDelay(5000 / portTICK_PERIOD_MS);
  39. mqtt_init();
  40. float kWh;
  41. while( true ) {
  42. char dataStr[100];
  43. kWh = getkWh();
  44. sprintf(dataStr,"%f",kWh);
  45. sendMQTTMessage("/sensors/energy/electricalTotal", dataStr);
  46. printf("%f\n",kWh);
  47. vTaskDelay(1000 / portTICK_PERIOD_MS);
  48. }
  49. esp_restart();
  50. }