safwan092

Untitled

Jan 23rd, 2025
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.45 KB | None | 0 0
  1. #include <Wire.h> //default library
  2. #include <U8g2lib.h> //https://github.com/olikraus/U8g2_Arduino
  3. #include <WiFi.h>
  4. #include <FirebaseESP32.h> //https://github.com/mobizt/Firebase-ESP8266
  5. #include <addons/TokenHelper.h>
  6. #include <addons/RTDBHelper.h>
  7. #include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
  8. #include <NTPClient.h>
  9. #include <WiFiUdp.h>
  10.  
  11. U8G2_SSD1306_128X64_NONAME_F_HW_I2C DISPB(U8G2_R0, U8X8_PIN_NONE);
  12.  
  13. #define buttonPin1 D1
  14. //#define buttonPin2 D3
  15. #define SDA 4
  16. #define SCL 5
  17. #define TDS_SENSOR_PIN A0
  18.  
  19. String WIFI_SSID = "Device [Setup WiFi]";
  20. #define API_KEY "AIzaSyCzMchetkDlrD-9YdZ4KuTiigAfjzPUl14"
  21. #define USER_EMAIL "[email protected]"
  22. #define USER_PASSWORD "Password123456789"
  23. #define DATABASE_URL "ai-glucose-tool-default-rtdb.firebaseio.com"
  24. #define DATABASE_SECRET "rLsxPgTD8YY8NaiOkWVjwjZzhi3kS8F3fDCpbHZX"
  25.  
  26.  
  27. // Define NTP Client to get time
  28. WiFiUDP ntpUDP;
  29. NTPClient timeClient(ntpUDP, "pool.ntp.org");
  30. // Variables to store time and date
  31. String currentTime;
  32. String currentDate;
  33. // Interrupt flags
  34. volatile bool button1Pressed = false;
  35. //volatile bool button2Pressed = false;
  36.  
  37. // Function prototypes
  38. void IRAM_ATTR button1ISR();
  39. //void IRAM_ATTR button2ISR();
  40. void sendDataToFirebase(String button);
  41.  
  42.  
  43. FirebaseData fbdo;
  44. FirebaseAuth auth;
  45. FirebaseConfig config;
  46. unsigned long dataMillis = 0;
  47. int count = 0;
  48.  
  49. int tdsValue = 0;
  50. float tds = 0;
  51.  
  52.  
  53.  
  54.  
  55.  
  56. void setup() {
  57. Serial.begin(115200);
  58. pinMode(buttonPin1, INPUT);
  59. //pinMode(buttonPin2, INPUT);
  60.  
  61. setupDisplay();
  62. connect_To_WiFi();
  63. connectingToFirebaseDatabase();
  64. // Initialize NTP Client
  65. timeClient.begin();
  66. timeClient.setTimeOffset(10800); // Adjust for your timezone
  67. // Attach interrupts to the buttons
  68. attachInterrupt(digitalPinToInterrupt(buttonPin1), button1ISR, CHANGE);
  69. //attachInterrupt(digitalPinToInterrupt(buttonPin2), button2ISR, CHANGE);
  70. }
  71.  
  72. void loop() {
  73. reConnect_To_WiFi();
  74. // Update the NTP client to get the current time
  75. timeClient.update();
  76.  
  77. // Get the current time and date
  78. currentTime = timeClient.getFormattedTime();
  79. currentDate = getFormattedDate(timeClient.getEpochTime());
  80. //int button2Status = analogRead(3);
  81. //Serial.println("-------------------------");
  82. //Serial.println(button2Status);
  83. //Serial.println("-------------------------");
  84. readSensor();
  85. showDataOnSerialMonitor();
  86. showDataOnDisplay();
  87.  
  88.  
  89. //sendingDataToFirebase(5);
  90.  
  91. // Check if button 1 was pressed
  92. if (button1Pressed) {
  93. button1Pressed = false; // Reset the flag
  94. sendDataToFirebase("Button1");
  95. }
  96. /*
  97. // Check if button 2 was pressed
  98. if (button2Pressed) {
  99. button2Pressed = false; // Reset the flag
  100. sendDataToFirebase("Button2");
  101. }
  102. */
  103. delay(1000);
  104. }
  105.  
  106.  
  107. // Interrupt Service Routine for Button 1
  108. void IRAM_ATTR button1ISR() {
  109. button1Pressed = true;
  110. }
  111. /*
  112. // Interrupt Service Routine for Button 2
  113. void IRAM_ATTR button2ISR() {
  114. button2Pressed = true;
  115. }
  116. */
  117. // Function to send data to Firebase
  118. void sendDataToFirebase(String button) {
  119. // Create a JSON object to store the data
  120. FirebaseJson json;
  121. json.set("time", currentTime);
  122. json.set("date", currentDate);
  123. json.set("button", button);
  124. json.set("TDS", tds);
  125.  
  126. String path = "/UsersData/";
  127. //path += auth.token.uid.c_str(); //<- user uid of current user that sign in with Emal/Password
  128. //path += "/";
  129. path += button;
  130. path += "/";
  131. path += currentDate;
  132. // Send data to Firebase
  133. if (Firebase.ready() && Firebase.pushJSON(fbdo, path, json)) {
  134. Serial.println("Data sent to Firebase successfully!");
  135. } else {
  136. Serial.println("Failed to send data to Firebase.");
  137. Serial.println("Reason: " + fbdo.errorReason());
  138. }
  139. }
  140.  
  141.  
  142.  
  143.  
  144.  
  145. void setupDisplay() {
  146. pinMode(SDA, OUTPUT);
  147. pinMode(SCL, OUTPUT);
  148. Wire.setClock(100000);
  149. DISPB.setBusClock(100000);
  150. DISPB.setI2CAddress(0x78);
  151. DISPB.begin();
  152. DISPB.setFont(u8g2_font_logisoso16_tf ); //smaller font to show difference
  153. DISPB.clearBuffer();
  154. }
  155.  
  156. void readSensor() {
  157. tdsValue = analogRead(TDS_SENSOR_PIN);
  158. tds = tdsValue * 0.5;
  159. }
  160.  
  161. void showDataOnSerialMonitor() {
  162. Serial.print("TDS Value: ");
  163. Serial.print(tds);
  164. Serial.println(" ppm");
  165. }
  166.  
  167. void showDataOnDisplay() {
  168. DISPB.clearBuffer();
  169. DISPB.setCursor(0, 31);
  170. DISPB.print("TDS Value:");
  171. DISPB.setCursor(10, 63);
  172. DISPB.print(tds);
  173. DISPB.print(" ml");
  174. DISPB.sendBuffer();
  175. }
  176.  
  177. void connectingToFirebaseDatabase() {
  178. Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION);
  179. config.api_key = API_KEY;
  180. auth.user.email = USER_EMAIL;
  181. auth.user.password = USER_PASSWORD;
  182. config.database_url = DATABASE_URL;
  183. Firebase.reconnectWiFi(true);
  184. fbdo.setResponseSize(4096);
  185. String base_path = "/UsersData/";
  186. config.token_status_callback = tokenStatusCallback; // see addons/TokenHelper.h
  187. config.max_token_generation_retry = 5;
  188. Firebase.begin(&config, &auth);
  189. String var = "$userId";
  190. String val = "($userId === auth.uid && auth.token.premium_account === true && auth.token.admin === true)";
  191. Firebase.setReadWriteRules(fbdo, base_path, var, val, val, DATABASE_SECRET);
  192. }
  193.  
  194.  
  195. void sendingDataToFirebase(unsigned long timeDelay) {
  196. if (millis() - dataMillis > (timeDelay * 1000) && Firebase.ready())
  197. {
  198. dataMillis = millis();
  199. String path = "/UsersData/";
  200. path += auth.token.uid.c_str(); //<- user uid of current user that sign in with Emal/Password
  201. path += "/test/TDS";
  202. Serial.printf("Set TDS... %s\n", Firebase.setFloat(fbdo, path, tds) ? "ok" : fbdo.errorReason().c_str());
  203. }
  204. }
  205.  
  206.  
  207. void reConnect_To_WiFi() {
  208. while (WiFi.status() != WL_CONNECTED) {
  209. //delay(500);
  210. Serial.print(".");
  211. connect_To_WiFi();
  212. }
  213. }
  214.  
  215. void connect_To_WiFi() {
  216. WiFiManager wm;
  217. bool res;
  218. res = wm.autoConnect(WIFI_SSID.c_str()); // password protected ap
  219.  
  220. if (!res) {
  221. Serial.println("Failed to Connect!!");
  222. // ESP.restart();
  223. }
  224. else {
  225. //if you get here you have connected to the WiFi
  226. Serial.println("Connected...");
  227. }
  228. }
  229.  
  230. // Function to convert epoch time to a formatted date string
  231. String getFormattedDate(unsigned long epochTime) {
  232. // Convert epoch time to a tm structure
  233. struct tm *ptm;
  234. ptm = gmtime((time_t *)&epochTime);
  235.  
  236. // Format the date as "YYYY-MM-DD"
  237. char buffer[11];
  238. sprintf(buffer, "%04d-%02d-%02d", ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday);
  239. return String(buffer);
  240. }
Advertisement
Add Comment
Please, Sign In to add comment