Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <Wire.h> //default library
- #include <U8g2lib.h> //https://github.com/olikraus/U8g2_Arduino
- #include <WiFi.h>
- #include <FirebaseESP32.h> //https://github.com/mobizt/Firebase-ESP8266
- #include <addons/TokenHelper.h>
- #include <addons/RTDBHelper.h>
- #include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
- #include <NTPClient.h>
- #include <WiFiUdp.h>
- U8G2_SSD1306_128X64_NONAME_F_HW_I2C DISPB(U8G2_R0, U8X8_PIN_NONE);
- #define buttonPin1 D1
- //#define buttonPin2 D3
- #define SDA 4
- #define SCL 5
- #define TDS_SENSOR_PIN A0
- String WIFI_SSID = "Device [Setup WiFi]";
- #define API_KEY "AIzaSyCzMchetkDlrD-9YdZ4KuTiigAfjzPUl14"
- #define USER_EMAIL "[email protected]"
- #define USER_PASSWORD "Password123456789"
- #define DATABASE_URL "ai-glucose-tool-default-rtdb.firebaseio.com"
- #define DATABASE_SECRET "rLsxPgTD8YY8NaiOkWVjwjZzhi3kS8F3fDCpbHZX"
- // Define NTP Client to get time
- WiFiUDP ntpUDP;
- NTPClient timeClient(ntpUDP, "pool.ntp.org");
- // Variables to store time and date
- String currentTime;
- String currentDate;
- // Interrupt flags
- volatile bool button1Pressed = false;
- //volatile bool button2Pressed = false;
- // Function prototypes
- void IRAM_ATTR button1ISR();
- //void IRAM_ATTR button2ISR();
- void sendDataToFirebase(String button);
- FirebaseData fbdo;
- FirebaseAuth auth;
- FirebaseConfig config;
- unsigned long dataMillis = 0;
- int count = 0;
- int tdsValue = 0;
- float tds = 0;
- void setup() {
- Serial.begin(115200);
- pinMode(buttonPin1, INPUT);
- //pinMode(buttonPin2, INPUT);
- setupDisplay();
- connect_To_WiFi();
- connectingToFirebaseDatabase();
- // Initialize NTP Client
- timeClient.begin();
- timeClient.setTimeOffset(10800); // Adjust for your timezone
- // Attach interrupts to the buttons
- attachInterrupt(digitalPinToInterrupt(buttonPin1), button1ISR, CHANGE);
- //attachInterrupt(digitalPinToInterrupt(buttonPin2), button2ISR, CHANGE);
- }
- void loop() {
- reConnect_To_WiFi();
- // Update the NTP client to get the current time
- timeClient.update();
- // Get the current time and date
- currentTime = timeClient.getFormattedTime();
- currentDate = getFormattedDate(timeClient.getEpochTime());
- //int button2Status = analogRead(3);
- //Serial.println("-------------------------");
- //Serial.println(button2Status);
- //Serial.println("-------------------------");
- readSensor();
- showDataOnSerialMonitor();
- showDataOnDisplay();
- //sendingDataToFirebase(5);
- // Check if button 1 was pressed
- if (button1Pressed) {
- button1Pressed = false; // Reset the flag
- sendDataToFirebase("Button1");
- }
- /*
- // Check if button 2 was pressed
- if (button2Pressed) {
- button2Pressed = false; // Reset the flag
- sendDataToFirebase("Button2");
- }
- */
- delay(1000);
- }
- // Interrupt Service Routine for Button 1
- void IRAM_ATTR button1ISR() {
- button1Pressed = true;
- }
- /*
- // Interrupt Service Routine for Button 2
- void IRAM_ATTR button2ISR() {
- button2Pressed = true;
- }
- */
- // Function to send data to Firebase
- void sendDataToFirebase(String button) {
- // Create a JSON object to store the data
- FirebaseJson json;
- json.set("time", currentTime);
- json.set("date", currentDate);
- json.set("button", button);
- json.set("TDS", tds);
- String path = "/UsersData/";
- //path += auth.token.uid.c_str(); //<- user uid of current user that sign in with Emal/Password
- //path += "/";
- path += button;
- path += "/";
- path += currentDate;
- // Send data to Firebase
- if (Firebase.ready() && Firebase.pushJSON(fbdo, path, json)) {
- Serial.println("Data sent to Firebase successfully!");
- } else {
- Serial.println("Failed to send data to Firebase.");
- Serial.println("Reason: " + fbdo.errorReason());
- }
- }
- void setupDisplay() {
- pinMode(SDA, OUTPUT);
- pinMode(SCL, OUTPUT);
- Wire.setClock(100000);
- DISPB.setBusClock(100000);
- DISPB.setI2CAddress(0x78);
- DISPB.begin();
- DISPB.setFont(u8g2_font_logisoso16_tf ); //smaller font to show difference
- DISPB.clearBuffer();
- }
- void readSensor() {
- tdsValue = analogRead(TDS_SENSOR_PIN);
- tds = tdsValue * 0.5;
- }
- void showDataOnSerialMonitor() {
- Serial.print("TDS Value: ");
- Serial.print(tds);
- Serial.println(" ppm");
- }
- void showDataOnDisplay() {
- DISPB.clearBuffer();
- DISPB.setCursor(0, 31);
- DISPB.print("TDS Value:");
- DISPB.setCursor(10, 63);
- DISPB.print(tds);
- DISPB.print(" ml");
- DISPB.sendBuffer();
- }
- void connectingToFirebaseDatabase() {
- Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION);
- config.api_key = API_KEY;
- auth.user.email = USER_EMAIL;
- auth.user.password = USER_PASSWORD;
- config.database_url = DATABASE_URL;
- Firebase.reconnectWiFi(true);
- fbdo.setResponseSize(4096);
- String base_path = "/UsersData/";
- config.token_status_callback = tokenStatusCallback; // see addons/TokenHelper.h
- config.max_token_generation_retry = 5;
- Firebase.begin(&config, &auth);
- String var = "$userId";
- String val = "($userId === auth.uid && auth.token.premium_account === true && auth.token.admin === true)";
- Firebase.setReadWriteRules(fbdo, base_path, var, val, val, DATABASE_SECRET);
- }
- void sendingDataToFirebase(unsigned long timeDelay) {
- if (millis() - dataMillis > (timeDelay * 1000) && Firebase.ready())
- {
- dataMillis = millis();
- String path = "/UsersData/";
- path += auth.token.uid.c_str(); //<- user uid of current user that sign in with Emal/Password
- path += "/test/TDS";
- Serial.printf("Set TDS... %s\n", Firebase.setFloat(fbdo, path, tds) ? "ok" : fbdo.errorReason().c_str());
- }
- }
- void reConnect_To_WiFi() {
- while (WiFi.status() != WL_CONNECTED) {
- //delay(500);
- Serial.print(".");
- connect_To_WiFi();
- }
- }
- void connect_To_WiFi() {
- WiFiManager wm;
- bool res;
- res = wm.autoConnect(WIFI_SSID.c_str()); // password protected ap
- if (!res) {
- Serial.println("Failed to Connect!!");
- // ESP.restart();
- }
- else {
- //if you get here you have connected to the WiFi
- Serial.println("Connected...");
- }
- }
- // Function to convert epoch time to a formatted date string
- String getFormattedDate(unsigned long epochTime) {
- // Convert epoch time to a tm structure
- struct tm *ptm;
- ptm = gmtime((time_t *)&epochTime);
- // Format the date as "YYYY-MM-DD"
- char buffer[11];
- sprintf(buffer, "%04d-%02d-%02d", ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday);
- return String(buffer);
- }
Advertisement
Add Comment
Please, Sign In to add comment