wifi_lux_sensor.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. #include <ESP8266WiFi.h>
  2. #include <Wire.h>
  3. #include "config.h"
  4. #include "lux_sensor.h"
  5. // ----------- DEFINES ---------------
  6. #define LUX_ID 0x39 // I2C-Id of the lux-sensor
  7. // ----------- GLOBALS ---------------
  8. tsl2591Gain_t _gain;
  9. tsl2591IntegrationTime_t _integration;
  10. WiFiClient espClient;
  11. void connectWifi() {
  12. WiFi.disconnect(false);
  13. Serial.printf("Wi-Fi mode set to WIFI_STA: %s\n", WiFi.mode(WIFI_STA) ? "Ok" : "Failed!");
  14. WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  15. Serial.print("Connecting to ");Serial.println(WIFI_SSID);
  16. while (WiFi.status() != WL_CONNECTED) {
  17. delay(1000);
  18. Serial.print(WiFi.status());
  19. Serial.print(".\r\n");
  20. //WiFi.printDiag(Serial);
  21. }
  22. Serial.println("");
  23. Serial.print("Connected with IP: "),
  24. Serial.println(WiFi.localIP());
  25. Serial.printf("\n");
  26. }
  27. void write8 (uint8_t reg, uint8_t value)
  28. {
  29. Wire.beginTransmission(LUX_ID);
  30. Wire.write(reg);
  31. Wire.write(value);
  32. Wire.endTransmission();
  33. }
  34. void enable(void)
  35. {
  36. // Enable the device by setting the control bit to 0x01
  37. write8(TSL2591_COMMAND_BIT | TSL2591_REGISTER_ENABLE, TSL2591_ENABLE_POWERON | TSL2591_ENABLE_AEN | TSL2591_ENABLE_AIEN);
  38. }
  39. void disable(void)
  40. {
  41. // Disable the device by setting the control bit to 0x00
  42. write8(TSL2591_COMMAND_BIT | TSL2591_REGISTER_ENABLE, TSL2591_ENABLE_POWEROFF);
  43. }
  44. void setConfiguration(tsl2591Gain_t gain, tsl2591IntegrationTime_t integration)
  45. {
  46. enable();
  47. _gain = gain;
  48. _integration = integration;
  49. write8( TSL2591_COMMAND_BIT | TSL2591_REGISTER_CONTROL, _integration | _gain);
  50. disable();
  51. }
  52. void setup() {
  53. Serial.begin(38400); //Opens USB-Serial connection for terminal
  54. delay(1000);
  55. Serial.println("Init of WiFi-Lux-sensor project");
  56. connectWifi();
  57. Wire.begin(4, 5); // sda on pin D2, scl on pin D1
  58. // Config lux-sensor
  59. _integration = TSL2591_INTEGRATIONTIME_100MS;
  60. _gain = TSL2591_GAIN_MED;
  61. // Set default integration time and gain
  62. setConfiguration(_gain, _integration);
  63. }
  64. void loop() {
  65. // put your main code here, to run repeatedly:
  66. byte error, address;
  67. Serial.print("WiFi heartbeat - ms since boot: ");
  68. Serial.print(millis());
  69. Serial.println();
  70. Wire.beginTransmission(LUX_ID);
  71. error = Wire.endTransmission();
  72. if (error == 0) {
  73. Serial.println("I2C-Lux device found");
  74. }
  75. else if (error==4) {
  76. Serial.println("--Unknown error.");
  77. }
  78. Serial.println("done\n");
  79. delay(1000);
  80. }