//Main code libreries//
#include <DHT.h>
#include <LiquidCrystal.h>
#include <WiFi.h>
#include<HTTPClient.h>
//Main code libreries ends//
//Email code libreries//
#include <Arduino.h>
#include <WiFi.h>
#include <ESP_Mail_Client.h>
//Email code libreries ends//
// Main code Defines//
#define SPIN 32
#define HPIN 35
int bpm;
int spo2;
const int DHTPIN = 12;
int PirPin = 33;
int pirState = LOW;
int val = 0;
const int RS=4, E = 15, DB4 = 5, DB5 = 18, DB6 = 21, DB7 = 22;
LiquidCrystal lcd (RS,E,DB4,DB5,DB6,DB7);
int hum;
float temp;
float fahrenheit;
DHT dht (DHTPIN, DHT22);
long lastTime = 0;
long timerDelay = 500;
const char ssid[] = "Wokwi-GUEST";
const char password[] = "";
String serverName = "https://api.thingspeak.com/update?api_key=Q80QPCNPUTFBKLPX";
int motionState;
//Main code defines ends//
//Email code defines start//
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
/** The smtp host name e.g. smtp.gmail.com for GMail or smtp.office365.com for Outlook or smtp.mail.yahoo.com */
#define SMTP_HOST "smtp.gmail.com"
#define SMTP_PORT 465
/* The sign in credentials */
#define AUTHOR_EMAIL "[email protected]"
#define AUTHOR_PASSWORD "aoep ftnw qycd vfve"
/* Recipient's email*/
#define RECIPIENT_EMAIL "[email protected]"
/* Declare the global used SMTPSession object for SMTP transport */
SMTPSession smtp;
/* Callback function to get the Email sending status */
void smtpCallback(SMTP_Status status);
//Email defines ends//
void setup()
{
//Main code void setup starts//
Serial.begin(115200);
lcd.begin(16,2);
lcd.print("Cattle Health Monitoring");
delay(500);
lcd.scrollDisplayLeft();
Serial.println("Hello, ESP32!");
pinMode(PirPin, INPUT);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print ("-");
}
Serial.println("");
Serial.print ("ESP 32 Connected\n");
Serial.println(WiFi.localIP());
//lcd.begin(16,2);
//lcd.print("WELCOME!");
motionState= LOW;
dht.begin();
// Main code void setup ends//
delay(2000);
// Email code void setup starts//
Serial.begin(115200);
Serial.println();
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(300);
}
Serial.println();
Serial.print("Connected with IP: ");
Serial.println(WiFi.localIP());
Serial.println();
/* Set the network reconnection option */
MailClient.networkReconnect(true);
/** Enable the debug via Serial port
* 0 for no debugging
* 1 for basic level debugging
*
* Debug port can be changed via ESP_MAIL_DEFAULT_DEBUG_PORT in ESP_Mail_FS.h
*/
smtp.debug(1);
/* Set the callback function to get the sending results */
smtp.callback(smtpCallback);
/* Declare the Session_Config for user defined session credentials */
Session_Config config;
/* Set the session config */
config.server.host_name = SMTP_HOST;
config.server.port = SMTP_PORT;
config.login.email = AUTHOR_EMAIL;
config.login.password = AUTHOR_PASSWORD;
config.login.user_domain = "";
/*
Set the NTP config time
For times east of the Prime Meridian use 0-12
For times west of the Prime Meridian add 12 to the offset.
Ex. American/Denver GMT would be -6. 6 + 12 = 18
See https://en.wikipedia.org/wiki/Time_zone for a list of the GMT/UTC timezone offsets
*/
config.time.ntp_server = F("pool.ntp.org,time.nist.gov");
config.time.gmt_offset = 3;
config.time.day_light_offset = 0;
/* Declare the message class */
SMTP_Message message;
/* Set the message headers */
message.sender.name = F("SRIRAM PROJECT");
message.sender.email = AUTHOR_EMAIL;
message.subject = F("ESP Test Email");
message.addRecipient(F("SRIRAM,"), RECIPIENT_EMAIL);
message.addRecipient(F("Eswar"), "[email protected]");
/*Send HTML message*/
/*String htmlMsg = "<div style=\"color:#2f4468;\"><h1>Hello World!</h1><p>- Sent from ESP board</p></div>";
message.html.content = htmlMsg.c_str();
message.html.content = htmlMsg.c_str();
message.text.charSet = "us-ascii";
message.html.transfer_encoding = Content_Transfer_Encoding::enc_7bit;*/
//Send raw text message
String textMsg = "Hello World! - Sent from ESP board";
message.text.content = textMsg.c_str();
message.text.charSet = "us-ascii";
message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;
message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;
message.response.notify = esp_mail_smtp_notify_success | esp_mail_smtp_notify_failure | esp_mail_smtp_notify_delay;
/* Connect to the server */
if (!smtp.connect(&config)){
ESP_MAIL_PRINTF("Connection error, Status Code: %d, Error Code: %d, Reason: %s", smtp.statusCode(), smtp.errorCode(), smtp.errorReason().c_str());
return;
}
if (!smtp.isLoggedIn()){
Serial.println("\nNot yet logged in.");
}
else{
if (smtp.isAuthenticated())
Serial.println("\nSuccessfully logged in.");
else
Serial.println("\nConnected with no Auth.");
}
/* Start sending Email and close the session */
if (!MailClient.sendMail(&smtp, &message))
ESP_MAIL_PRINTF("Error, Status Code: %d, Error Code: %d, Reason: %s", smtp.statusCode(), smtp.errorCode(), smtp.errorReason().c_str());
// Email void setup ends//
}
void loop()
{
// Main code void loop starts//
if ((millis() - lastTime) > timerDelay)
{
if (WiFi.status() == WL_CONNECTED)
{
val = digitalRead(PirPin);
hum = dht.readHumidity();
temp = dht.readTemperature();
fahrenheit = (temp*1.8)+32;
lcd.clear();
display (fahrenheit, hum, bpm, spo2);
get_bpm();
get_spo2();
if (val == HIGH)
{
if (pirState == LOW)
{
Serial.println("\nMotion detected!");
//Serial.println(pirState);
motionState = HIGH;
sendData(fahrenheit, hum, bpm, spo2, motionState);
pirState = HIGH;
lcd.setCursor(0,1);
lcd.print ("Motion detected!");
}
}
else
{
if (pirState == HIGH)
{
delay(5000);
Serial.println("\nMotion ended!");
//Serial.println(pirState);
motionState = LOW;
sendData(fahrenheit, hum, bpm, spo2, motionState);
pirState = LOW;
lcd.setCursor(0,1);
lcd.print ("Motion ended! ");
}
}
//Serial.println(pirState);
sendData(fahrenheit, hum, bpm, spo2, motionState);
}
else
{
Serial.println("Wifi Disconnected");
}
lastTime = millis();
}
//Serial.println("-----");
//delay(2000);
//Empty void loop for Email code//
}
// Extra voids of main code starts//
void get_bpm()
{
int signal2 = analogRead(HPIN);
bpm= map(signal2,0,4095,0,200);
}
void get_spo2()
{
int signal3 = analogRead(SPIN);
spo2= map(signal3,0,4095,0,200);
}
void display (float temp, int hum, int bpm, int spo2)
{
Serial.print ("\nHumidity: ");
Serial.print (hum);
Serial.print ("\tTemperature: ");
Serial.print(fahrenheit);
Serial.print ("\nHeartRate: ");
Serial.print (bpm);
Serial.print ("\tSpO2: ");
Serial.print(spo2);
lcd.setCursor(0,0);
lcd.print ("Hum: ");
lcd.print(hum);
lcd.print ("\tTemp: ");
lcd.print(fahrenheit);
lcd.setCursor(0,1);
lcd.print ("BPM: ");
lcd.print(bpm);
lcd.print ("\tSpO2: ");
lcd.print(spo2);
//lcd.setCursor(0,1);
//lcd.print (" ");
}
void sendData ( float fahrenheit, int hum, int bpm, int spo2, int motionState)
{
HTTPClient http;
Serial.print("\nMotion: ");
Serial.println(motionState);
String url = serverName + "&field1=" + fahrenheit + "&field2=" + bpm + "&field3=" + spo2 + "&field4=" + motionState + "&field5=" + hum;
http.begin(url.c_str());
int httpResponseCode = http.GET();
if (httpResponseCode>0)
{
Serial.print ("\nHTTP Response Code: ");
Serial.println(httpResponseCode);
}
else
{
Serial.print ("Error Code");
Serial.println(httpResponseCode);
}
http.end();
//delay(3000);
}
// Extrs voids of main code ends//
// Extrs voids of Email code starts//
/* Callback function to get the Email sending status */
void smtpCallback(SMTP_Status status)
{
/* Print the current status */
Serial.println(status.info());
/* Print the sending result */
if (status.success())
{
// ESP_MAIL_PRINTF used in the examples is for format printing via debug Serial port
// that works for all supported Arduino platform SDKs e.g. AVR, SAMD, ESP32 and ESP8266.
// In ESP8266 and ESP32, you can use Serial.printf directly.
Serial.println("----------------");
ESP_MAIL_PRINTF("Message sent success: %d\n", status.completedCount());
ESP_MAIL_PRINTF("Message sent failed: %d\n", status.failedCount());
Serial.println("----------------\n");
for (size_t i = 0; i < smtp.sendingResult.size(); i++)
{
/* Get the result item */
SMTP_Result result = smtp.sendingResult.getItem(i);
// In case, ESP32, ESP8266 and SAMD device, the timestamp get from result.timestamp should be valid if
// your device time was synched with NTP server.
// Other devices may show invalid timestamp as the device time was not set i.e. it will show Jan 1, 1970.
// You can call smtp.setSystemTime(xxx) to set device time manually. Where xxx is timestamp (seconds since Jan 1, 1970)
ESP_MAIL_PRINTF("Message No: %d\n", i + 1);
ESP_MAIL_PRINTF("Status: %s\n", result.completed ? "success" : "failed");
ESP_MAIL_PRINTF("Date/Time: %s\n", MailClient.Time.getDateTimeString(result.timestamp, "%B %d, %Y %H:%M:%S").c_str());
ESP_MAIL_PRINTF("Recipient: %s\n", result.recipients.c_str());
ESP_MAIL_PRINTF("Subject: %s\n", result.subject.c_str());
}
Serial.println("----------------\n");
// You need to clear sending result as the memory usage will grow up.
smtp.sendingResult.clear();
}
}
// Extra voids of email code ends//