/*************************************************** Attachement for Sensors And Devices ***************************************************/ //----------------------------------------------------- // SD card conected to SPI bus as follows: // ** GND - pin UNO GND, MEGA GND // ** MISO - pin UNO 12, MEGA 50 // ** MOSI - pin UNO 11, MEGA 51 // ** CLK/SCK - pin UNO 13, MEGA 52 // ** CS - pin UNO 10, MEGA 53 // ** 5V - pin UNO 5V, MEGA 5V // ** 3.3V - pin UNO N.C, MEGA N.C // ** GND - pin UNO N.C, MEGA N.C //----------------------Stepper----------------------- // Note: You also have to connect GND, 5V/VIO and VM. // A connection diagram can be found in the schematics. #define EN_PIN D4 // 7 //enable (CFG6) #define DIR_PIN D6 // 8 //direction #define STEP_PIN D5// 9 //step //----------------------DHT 22----------------------- #include #include "DHT.h" #define DHTPIN D0 #define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321 DHT dht(DHTPIN, DHTTYPE); byte temperatureC; byte humidity; //----------------------Thermistor----------------------- // Define the analog input pin connected to the thermistor const int th0PIN = A1; // Constants for the Steinhart-Hart equation const float resistanceNominal = 10000.0; // Resistance at nominal temperature (10k thermistor) const float betaCoefficient = 3974.0; // Beta coefficient of the thermistor const float nominalTemperature = 25.0; // Nominal temperature of the thermistor //----------------------Heater FAN ----------------------- // Define const int FAN_PIN = D3; //----------------------PCB Heater ----------------------- // const int HEATER_PIN = D2; // For PWM signal //const int freq = 5000; //const int heaterChannel = 0; //const int resolution = 8; //---------------------- SD_CARD ----------------------- // //#include // SD librairy ////-----------------------SD file---------------------------- //File dataFile; //const int chipSelect = D7; //SD Card ChipSelect CS pin //char filename[] = "00000000.CSV"; //Datalog File initial name and number of letter //----------------------- Time ---------------------------- #include #include #include // network credentials const char* ssid = "Color"; const char* password = "YourPassWord"; // Define NTP Client to get time WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP); // Variables to save date and time String formattedDate; String dayStamp; String timeStamp; double ThValue; // Interfacing Telegram and web Server #include #include #include #include // Create AsyncWebServer object on port 90 AsyncWebServer server(90); // Telegram BOT Token (Get from Botfather) #define BOT_TOKEN "Your_Bot_Token" #define CHAT_ID "Your_Chat_ID" WiFiClientSecure secured_client; UniversalTelegramBot bot(BOT_TOKEN, secured_client); const unsigned long BOT_MTBS = 1000; // mean time between scan messages unsigned long bot_lasttime; // last time messages' scan has been done double TtemperatureC; //float temperatureF; double Thumidity; void setup() { //----------------------Serial monitor for Debuging----------------------- Serial.begin(9600); //----------------------Stepper----------------------- //set Steeper pin modes pinMode(EN_PIN, OUTPUT); digitalWrite(EN_PIN, HIGH); //deactivate driver (LOW active) pinMode(DIR_PIN, OUTPUT); digitalWrite(DIR_PIN, LOW); //LOW or HIGH pinMode(STEP_PIN, OUTPUT); digitalWrite(STEP_PIN, LOW); digitalWrite(EN_PIN, LOW); //activate driver //----------------------DHT 22----------------------- dht.begin(); //----------------------Thermistor----------------------- pinMode(th0PIN, INPUT); //_PULLUP); //----------------------Heater FAN ----------------------- pinMode(FAN_PIN, OUTPUT); //----------------------PCB Heater ----------------------- // pinMode(HEATER_PIN, OUTPUT); ledcSetup(0, 5000, 8); // setup PWM // ledcSetup(heatherChannel, freq, resolution); // setup PWM ledcAttachPin(D2, 0); // attach PWM to the pin //ledcAttachPin(heaterPin, heaterChannel); // attach PWM to the pin // //---------------------- SD_CARD ----------------------- // // // pinMode(HEATER_PIN, OUTPUT); // //-----------------------SD card Initialization Script------------------------------ // Serial.print("Initializing SD card..."); //SD card Initialization // pinMode(chipSelect, OUTPUT); //digitalWrite(chipSelect,HIGH); // if (!SD.begin(chipSelect)) { // see if the card is present and can be initialized: // // Serial.println("Card failed, or not present"); // //lcd.println("Card Error"); // return; // don't do anything more: // } // Serial.println("card initialized."); // //lcd.println("Card OK"); // Wire.begin(); // SD.begin(chipSelect); //----------------------- WiFi ------------------------------ Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); WiFiClientSecure secured_client; while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } // Print local IP address and start web server Serial.println(""); Serial.println("WiFi connected."); Serial.println("IP address: "); Serial.println(WiFi.localIP()); //----------------------- Time ------------------------------ // Initialize a NTPClient to get time timeClient.begin(); // Set offset time in seconds to adjust for your timezone, for example: // GMT +1 = 3600 // GMT +8 = 28800 // GMT -1 = -3600 // GMT 0 = 0 timeClient.setTimeOffset(0); // ------------ Interface --------------------- // Initialize SPIFFS if (!SPIFFS.begin()) { Serial.println("An Error has occurred while mounting SPIFFS"); return; } //Interface Route for root / web page server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) { request->send(SPIFFS, "/index.html"); }); server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest * request) { request->send_P(200, "text/plain", read_T_DHT22().c_str()); }); server.on("/humidity", HTTP_GET, [](AsyncWebServerRequest * request) { request->send_P(200, "text/plain", read_H_DHT22().c_str()); }); // server.on("/pressure", HTTP_GET, [](AsyncWebServerRequest * request) { // request->send_P(200, "text/plain", buttonSateChange().c_str()); // }); // Start server server.begin(); } void loop() { tilter(); //dhtRead(); TtemperatureC = dht.readTemperature(); Thumidity = dht.readHumidity(); // Telegram Bot if (millis() - bot_lasttime > BOT_MTBS) { int numNewMessages = bot.getUpdates(bot.last_message_received + 1); while (numNewMessages) { Serial.println("got response"); handleNewMessages(numNewMessages); numNewMessages = bot.getUpdates(bot.last_message_received + 1); } bot_lasttime = millis(); } th0(); // float pwm_FAN = map(ThValue, 20, 60, 125, 255); // float pwm_Heat = map(temperatureC, 25, 50, 70, 0); float pwm_Heat = map(TtemperatureC, 25, 40, 70, 0); float pwm_FAN = map(ThValue, 20, 45, 125, 255); if (ThValue >= 45 || TtemperatureC >= 37.5 ) // Check if temperature exceeds the maximum limit { ledcWrite(0, 0); // if temperature is above the limit, turn off heater analogWrite (FAN_PIN, 255); } else { ledcWrite(0, pwm_Heat); // would make heater work at half power delay(10); // Delay for a short duration (adjust as needed) } { // Debug lines Serial.println("----------------------"); Serial.print("Th0_Value: "); Serial.println(ThValue); Serial.print("temperature DHT22 °C: "); Serial.println(TtemperatureC); analogWrite (FAN_PIN, pwm_FAN); Serial.print("PWM FAN at :"); Serial.println(pwm_FAN); // analogWrite (HEATER_PIN, pwm_Heat); Serial.print("PWM HEATER at :"); Serial.println(pwm_Heat); delay(500); } //NTP_time(); //FAN_PWM(); //HEATER_PWM(); //delay(1000); } void handleNewMessages(int numNewMessages) { Serial.print("handleNewMessages "); Serial.println(numNewMessages); for (int i = 0; i < numNewMessages; i++) { String chat_id = String(bot.messages[i].chat_id); if (chat_id != CHAT_ID ) { bot.sendMessage(chat_id, "Unauthorized user", ""); } else { String text = bot.messages[i].text; String from_name = bot.messages[i].from_name; if (from_name == "") from_name = "Guest"; if (text == "/tempC") { String msg = "Temperature is "; msg += msg.concat(TtemperatureC); msg += "C"; bot.sendMessage(chat_id, msg, ""); } // if (text == "/tempF") // { // String msg = "Temperature is "; // msg += msg.concat(temperatureF); // msg += "F"; // bot.sendMessage(chat_id, msg, ""); // } if (text == "/humidity") { String msg = "Humidity is "; msg += msg.concat(humidity); msg += "%"; bot.sendMessage(chat_id, msg, ""); } // if (text == "/ButtonState") // { // //String Door = ""; // String msg = "DoorState: "; // if (btn == 1) // { // msg += "Ay Caramba! You didn't close the door"; // } // else if (btn == 0) // { // msg += "From what I can sense the door is closed"; // } // //msg += msg.concat(Door); // //msg += "%"; // bot.sendMessage(chat_id, msg, ""); // } // if (text == "/ON") // { // String msg = "Turning led ON :"; // bot.sendMessage(chat_id, msg, ""); // //digitalWrite(led, HIGH); // } // if (text == "/OFF") // { // String msg = "Turning led OFF :"; // bot.sendMessage(chat_id, msg, ""); // //digitalWrite(led, LOW); // } if (text == "/start" || text == "/help" || text == "/?") { String welcome = "Ousiafb XIO ESP32.\n"; welcome += "/tempC : Temperature in celcius \n"; welcome += "/tempF : Temperature in faranthit\n"; welcome += "/humidity : Humidity\n"; // welcome += "/ButtonState : 0 or 1\n"; // welcome += "/ON or /OFF to turn led OFF\n"; bot.sendMessage(chat_id, welcome, "Markdown"); } } } } void tilter() { digitalWrite(DIR_PIN, LOW); //LOW or HIGH for (int i = 1; i < 400; i++) { stepper(); //delayMicroseconds(700); } delay(1000); digitalWrite(DIR_PIN, HIGH); //LOW or HIGH for (int i = 1; i < 400; i++) { //delayMicroseconds(700); stepper(); } delay(1000); } void stepper() { //make one steps digitalWrite(STEP_PIN, HIGH); delayMicroseconds(700); ; digitalWrite(STEP_PIN, LOW); delayMicroseconds(700); ; } void th0() { // Read the analog value from the thermistor int rawValue = analogRead(th0PIN); //Serial.print(rawValue); //Serial.println(" rRAW"); // Convert the raw value to resistance float resistance = 10000.0 / (4095.0 / rawValue - 1.0); // Using voltage divider formula (Ohm's Law) // Calculate temperature using the Steinhart-Hart equation float steinhart; steinhart = resistance / resistanceNominal; // (R/Ro) steinhart = log(steinhart); // ln(R/Ro) steinhart /= betaCoefficient; // 1/B * ln(R/Ro) steinhart += 1.0 / (nominalTemperature + 273.15); // + (1/To) steinhart = 1.0 / steinhart; // Invert steinhart -= 273.15; // Convert to Celsius ThValue = steinhart; } double Thermistor(int RawADC) { double Temp; Temp = log(10000.0 * ((1024.0 / RawADC - 1))); // =log(10000.0/(1024.0/RawADC-1)) // for pull-up configuration Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp )) * Temp ); Temp = Temp - 273.15; // Convert Kelvin to Celcius return Temp; } void NTP_time() { while (!timeClient.update()) { timeClient.forceUpdate(); } // The formattedDate comes with the following format: // 2018-05-28T16:00:13Z // We need to extract date and time formattedDate = timeClient.getFormattedDate(); Serial.println(formattedDate); // Extract date int splitT = formattedDate.indexOf("T"); dayStamp = formattedDate.substring(0, splitT); Serial.print("DATE: "); Serial.println(dayStamp); // Extract time timeStamp = formattedDate.substring(splitT + 1, formattedDate.length() - 1); Serial.print("HOUR: "); Serial.println(timeStamp); delay(1000); } //This function reads the temperature level from the DHT22 for bot String read_H_DHT22() { humidity = dht.readHumidity(); if (isnan(humidity)) { //Serial.println("Failed to read from DHT22 sensor!"); return "NAN"; } else { return String(humidity); } } String read_T_DHT22() { temperatureC = dht.readTemperature(); if (isnan(temperatureC)) { //Serial.println("Failed to read from DHT22 sensor!"); return "NAN"; } else { return String(temperatureC); } }