Untitled

mail@pastecode.io avatar
unknown
ada
a year ago
18 kB
1
Indexable
Never
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <SoftwareSerial.h>
#include <TinyGPS++.h>
#include <Wire.h>
#include <EEPROM.h>
#include "MAX30100_PulseOximeter.h"
#define REPORTING_PERIOD_MS 1000

#define BLYNK_TEMPLATE_ID "TMPLhRpujk5E"
#define BLYNK_DEVICE_NAME "IOT  Pulse Oximeter"
#define BLYNK_AUTH_TOKEN "FC37yNTnXcdM_UfeRTdb91TzlKzHd1C6"
#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
char auth[] = BLYNK_AUTH_TOKEN;

char ssid[] = "💀 ALPHA 💀";        
char pass[] = "2552425524";

BlynkTimer timer;
BLYNK_WRITE(V0)
{
  int value = param.asInt();
  Blynk.virtualWrite(V1, value);
}
BLYNK_CONNECTED()
{
  Blynk.setProperty(V3, "offImageUrl", "https://static-image.nyc3.cdn.digitaloceanspaces.com/general/fte/congratulations.png");
  Blynk.setProperty(V3, "onImageUrl",  "https://static-image.nyc3.cdn.digitaloceanspaces.com/general/fte/congratulations_pressed.png");
  Blynk.setProperty(V3, "url", "https://docs.blynk.io/en/getting-started/what-do-i-need-to-blynk/how-quickstart-device-was-made");
}
void myTimerEvent()
{
  Blynk.virtualWrite(V2, millis() / 1000);
}


PulseOximeter pox;
float BPM, SpO2;
uint32_t tsLastReport = 0;
const int mood = 16;



String PHONE = "+8801533378721";
const int totalPhoneNo = 5;
const int button = D8;
const int buzzer = D7;
int temp = 0;
String phoneNo[totalPhoneNo] = {"","","","",""};
int offsetPhone[totalPhoneNo] = {0,14,28,42,56};
String tempPhone = "";

#define rxGSM 0
#define txGSM 2
SoftwareSerial sim800(rxGSM,txGSM);

#define rxGPS 14
#define txGPS 12
SoftwareSerial neogps(rxGPS,txGPS);
TinyGPSPlus gps;

String smsStatus;
String senderNumber;
String receivedDate;
String msg;

const int MPU_addr=0x68;  
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;
float ax=0, ay=0, az=0, gx=0, gy=0, gz=0;
boolean fall = false; //stores if a fall has occurred
boolean trigger1=false; //stores if first trigger (lower threshold) has occurred
boolean trigger2=false; //stores if second trigger (upper threshold) has occurred
boolean trigger3=false; //stores if third trigger (orientation change) has occurred
byte trigger1count=0; //stores the counts past since trigger 1 was set true
byte trigger2count=0; //stores the counts past since trigger 2 was set true
byte trigger3count=0; //stores the counts past since trigger 3 was set true
int angleChange=0;

int period = 10000;
unsigned long time_now = 0;
int flagcall = 1;
int moodcall = 1;

void onBeatDetected()
{
  Serial.println("Beat Detected!");
  
}


void setup() {
  Serial.begin(115200);
  Serial.println("NodeMCU USB serial initialize");
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);
  Serial.println("Wrote to IMU");
  
  sim800.begin(9600);
  Serial.println("SIM800L serial initialize");
  delay(100);
  
  neogps.begin(9600);
  Serial.println("NEO6M serial initialize");
  delay(100);
  
  
  
  
  sim800.listen();
  neogps.listen();
  pinMode(button, INPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(mood, INPUT);

  
  EEPROM.begin(512);
  writeToEEPROM(offsetPhone[0],"");
  writeToEEPROM(offsetPhone[1],"");
  writeToEEPROM(offsetPhone[2],"");
  writeToEEPROM(offsetPhone[3],"");
  writeToEEPROM(offsetPhone[4],"");
  phoneNo[0] = "";
  phoneNo[1] = "";
  phoneNo[2] = "";
  phoneNo[3] = "";
  phoneNo[4] = "";
  offsetPhone[0] = 0;
  offsetPhone[1] = 14;
  offsetPhone[2] = 28;
  offsetPhone[3] = 42;
  offsetPhone[4] = 56;
  phoneNo[0] = "+8801533378721";
  writeToEEPROM(offsetPhone[0],PHONE);
  
  Serial.println("List of Registered Phone Numbers");
  for (int i = 0; i < totalPhoneNo; i++){
    phoneNo[i] = readFromEEPROM(offsetPhone[i]);
    if(phoneNo[i].length() != 14)
      {phoneNo[i] = "";Serial.println(String(i+1)+": empty");}
    else
      {Serial.println(String(i+1)+": "+phoneNo[i]);}
  }
  
  senderNumber="";
  msg="";
  
  
  delay(9000);
  sim800.println("AT+CMGF=1"); //SMS text mode
  delay(2000);
  sim800.println("AT+CLIP=1"); //Enable Caller ID
  delay(2000);
  sim800.println("AT+CNMI=1,2,0,0,0"); //Enable Caller ID
  delay(2000);
  
  sim800.listen();
  
  
}


void loop() {
  temp = digitalRead(mood);
  if (temp == HIGH) {
    if(moodcall == 1){
      moodcall = 2;
      
      digitalWrite(buzzer,HIGH);
      delay(500);
      digitalWrite(buzzer,LOW);
      delay(500);
      digitalWrite(buzzer,HIGH);
      delay(500);
      digitalWrite(buzzer,LOW);
      Serial.println("MOOD 2");
      stu();
      }
    else if(moodcall == 2){
      moodcall = 1;
      digitalWrite(buzzer,HIGH);
      delay(1000);
      digitalWrite(buzzer,LOW);
      Serial.println("MOOD 1");
      setup();
      }
  }
  if(moodcall == 1){
  while(sim800.available()){
    Data(sim800.readString());
    //Serial.println(sim800.readString());
    
  }
  
  while(Serial.available()){
    sim800.println(Serial.readString());
  }
 mpu_read();
 ax = (AcX-2050)/16384.00;
 ay = (AcY-77)/16384.00;
 az = (AcZ-1947)/16384.00;
 gx = (GyX+270)/131.07;
 gy = (GyY-351)/131.07;
 gz = (GyZ+136)/131.07;
 // calculating Amplitute vactor for 3 axis
 float Raw_Amp = pow(pow(ax,2)+pow(ay,2)+pow(az,2),0.5);
 int Amp = Raw_Amp * 10;  // Mulitiplied by 10 bcz values are between 0 to 1
 
 if (Amp<=2 && trigger2==false){ //if AM breaks lower threshold (0.4g)
   trigger1=true;
   Serial.println("TRIGGER 1 ACTIVATED");
   }
 if (trigger1==true){
   trigger1count++;
   if (Amp>=12){ //if AM breaks upper threshold (3g)
     trigger2=true;
     Serial.println("TRIGGER 2 ACTIVATED");
     trigger1=false; trigger1count=0;
     }
 }
 if (trigger2==true){
   trigger2count++;
   angleChange = pow(pow(gx,2)+pow(gy,2)+pow(gz,2),0.5); Serial.println(angleChange);
   if (angleChange>=30 && angleChange<=400){ //if orientation changes by between 80-100 degrees
     trigger3=true; trigger2=false; trigger2count=0;
     Serial.println(angleChange);
     Serial.println("TRIGGER 3 ACTIVATED");
       }
   }
 if (trigger3==true){
    trigger3count++;
    if (trigger3count>=10){ 
       angleChange = pow(pow(gx,2)+pow(gy,2)+pow(gz,2),0.5);
       //delay(10);
       Serial.println(angleChange); 
       if ((angleChange>=0) && (angleChange<=10)){ //if orientation changes remains between 0-10 degrees
           fall=true; trigger3=false; trigger3count=0;
           Serial.println(angleChange);
             }
       else{ //user regained normal orientation
          trigger3=false; trigger3count=0;
          Serial.println("TRIGGER 3 DEACTIVATED");
       }
     }
  }
 if (fall==true){ //in event of a fall detection
   Serial.println("FALL DETECTED");
   time_now = millis();
   
    while(millis() < time_now + period){
        //wait approx. [period] ms
        temp = digitalRead(button);
        Serial.println("TRIGGER");
        digitalWrite(buzzer, HIGH);   // turn the LED on (HIGH is the voltage level)
        delay(100);
        if (temp == HIGH) {
          flagcall = 0;
          break;
          delay(1000);
          }
    }
    digitalWrite(buzzer,LOW);
    if(flagcall==1){
      Serial.println("TRIGGER");
      sendLocation1(PHONE);
      }
   
   
   flagcall = 1;
   fall=false;
   }
 if (trigger2count>=6){ //allow 0.5s for orientation change
   trigger2=false; trigger2count=0;
   Serial.println("TRIGGER 2 DECACTIVATED");
   }
 if (trigger1count>=6){ //allow 0.5s for AM to break upper threshold
   trigger1=false; trigger1count=0;
   Serial.println("TRIGGER 1 DECACTIVATED");
   }
  delay(100);
 temp = digitalRead(button);
 if (temp == HIGH) {
    Serial.println("press");
    sendLocation2(PHONE);
    digitalWrite(buzzer,HIGH);
    delay(2000);
    digitalWrite(buzzer,LOW);
  }
  delay(100);
  }
  if(moodcall == 2){
    pox.update();
  Blynk.run();

  BPM = pox.getHeartRate();
  SpO2 = pox.getSpO2();
      if (millis() - tsLastReport > REPORTING_PERIOD_MS)
  {
    Serial.print("Heart rate:");
    Serial.print(BPM);
    Serial.print(" SpO2:");
    Serial.print(SpO2);
    Serial.println(" %");

    Blynk.virtualWrite(V1, BPM);
    Blynk.virtualWrite(V2, SpO2);

    tsLastReport = millis();
  }
    }
  
}


void Data(String buff){
  Serial.println(buff);
  unsigned int len, index;
  index = buff.indexOf("\r");
  buff.remove(0, index+2);
  buff.trim();
  
  if(buff != "OK"){
    Serial.println("2");
    index = buff.indexOf(":");
    String cmd = buff.substring(0, index);
    cmd.trim();
    Serial.println(cmd);
    
    buff.remove(0, index+2);
    if(cmd == "+CMT"){
      Serial.println("3");
      extractSms(buff);
      if(comparePhone(senderNumber)){
        doAction(senderNumber);
      }
    }
  }
  else{
  }
  
}



void doAction(String phoneNumber){
  if(msg == "location"){  
      sendLocation(phoneNumber);
  }
  if(msg == "r2="){  
      Serial.println(offsetPhone[1]);
      writeToEEPROM(offsetPhone[1],tempPhone);
      phoneNo[1] = tempPhone;
      String text = "Phone2 is Registered: ";
      text = text + tempPhone;
      debugPrint(text);
      Reply(text, phoneNumber);
  }
  else if(msg == "r3="){  
      writeToEEPROM(offsetPhone[2],tempPhone);
      phoneNo[2] = tempPhone;
      String text = "Phone3 is Registered: ";
      text = text + tempPhone;
      Reply(text, phoneNumber);
  }
  else if(msg == "r4="){  
      writeToEEPROM(offsetPhone[3],tempPhone);
      phoneNo[3] = tempPhone;
      String text = "Phone4 is Registered: ";
      text = text + tempPhone;
      Reply(text, phoneNumber);
  }
  else if(msg == "r5="){  
      writeToEEPROM(offsetPhone[4],tempPhone);
      phoneNo[4] = tempPhone;
      String text = "Phone5 is Registered: ";
      text = text + tempPhone;
      Reply(text, phoneNumber);
  }
  else if(msg == "list"){  
      String text = "";
      if(phoneNo[0])
        text = text + phoneNo[0]+"\r\n";
      if(phoneNo[1])
        text = text + phoneNo[1]+"\r\n";
      if(phoneNo[2])
        text = text + phoneNo[2]+"\r\n";
      if(phoneNo[3])
        text = text + phoneNo[3]+"\r\n";
      if(phoneNo[4])
        text = text + phoneNo[4]+"\r\n";
        
      debugPrint("List of Registered Phone Numbers: \r\n"+text);
      Reply(text, phoneNumber);
  }
  else if(msg == "del=1"){  
      writeToEEPROM(offsetPhone[0],"");
      phoneNo[0] = "";
      Reply("Phone1 is deleted.", phoneNumber);
  }
  else if(msg == "del=2"){  
      writeToEEPROM(offsetPhone[1],"");
      phoneNo[1] = "";
      debugPrint("Phone2 is deleted.");
      Reply("Phone2 is deleted.", phoneNumber);
  }
  else if(msg == "del=3"){  
      writeToEEPROM(offsetPhone[2],"");
      phoneNo[2] = "";
      debugPrint("Phone3 is deleted.");
      Reply("Phone3 is deleted.", phoneNumber);
  }
  else if(msg == "del=4"){  
      writeToEEPROM(offsetPhone[3],"");
      phoneNo[3] = "";
      debugPrint("Phone4 is deleted.");
      Reply("Phone4 is deleted.", phoneNumber);
  }
  else if(msg == "del=5"){  
      writeToEEPROM(offsetPhone[4],"");
      phoneNo[4] = "";
      debugPrint("Phone5 is deleted.");
      Reply("Phone5 is deleted.", phoneNumber);
  }
  if(msg == "del=all"){  
      writeToEEPROM(offsetPhone[0],"");
      writeToEEPROM(offsetPhone[1],"");
      writeToEEPROM(offsetPhone[2],"");
      writeToEEPROM(offsetPhone[3],"");
      writeToEEPROM(offsetPhone[4],"");
      phoneNo[0] = "";
      phoneNo[1] = "";
      phoneNo[2] = "";
      phoneNo[3] = "";
      phoneNo[4] = "";
      offsetPhone[0] = NULL;
      offsetPhone[1] = NULL;
      offsetPhone[2] = NULL;
      offsetPhone[3] = NULL;
      offsetPhone[4] = NULL;
      debugPrint("All phone numbers are deleted.");
      Reply("All phone numbers are deleted.", phoneNumber);
  }
  senderNumber="";
  msg="";
  tempPhone = "";
}





void extractSms(String buff){
   unsigned int index;
   Serial.println("4");
   
    index = buff.indexOf(",");
    senderNumber = buff.substring(1, index-1); 
    buff.remove(0, index+2);
    buff.remove(0,buff.indexOf("\r"));
    buff.trim();
    
    index =buff.indexOf("\n\r");
    buff = buff.substring(0, index);
    buff.trim();
    msg = buff;
    buff = "";
    msg.toLowerCase();
    Serial.println(msg);
    Serial.println(senderNumber);

    String tempcmd = msg.substring(0, 3);
    if(tempcmd.equals("r1=") || tempcmd.equals("r2=") ||
       tempcmd.equals("r3=") || tempcmd.equals("r4=") ||
       tempcmd.equals("r5=")){
        
        tempPhone = msg.substring(3, 17);
        msg = tempcmd;
    }
       
}


void Reply(String text, String Phone)
{
  //return;
  sim800.print("AT+CMGF=1\r");
  delay(1000);
  sim800.print("AT+CMGS=\""+Phone+"\"\r");
  delay(1000);
  sim800.print(text);
  delay(100);
  sim800.write(0x1A); //ascii code for ctrl-26 //sim800.println((char)26); //ascii code for ctrl-26
  delay(1000);
  Serial.println("SMS Sent Successfully.");
  sim800.print("AT+CMGD=1,4");

  senderNumber="";
  msg="";
  tempPhone = "";  
}



void writeToEEPROM(int addrOffset, const String &strToWrite)
{
  byte len = 14; //strToWrite.length();
  for (int i = 0; i < len; i++)
  {
    EEPROM.write(addrOffset + i, strToWrite[i]);
  }
  EEPROM.commit();

}


String readFromEEPROM(int addrOffset)
{
  int len = 14;
  char data[len + 1];
  for (int i = 0; i < len; i++)
  {
    data[i] = EEPROM.read(addrOffset + i);
  }
  data[len] = '\0';
  return String(data);
}


{
  boolean flag = 0;
  for (int i = 0; i < totalPhoneNo; i++){
    phoneNo[i] = readFromEEPROM(offsetPhone[i]);
    if(phoneNo[i].equals(number)){
      //Serial.println(phoneNo[i]);
      flag = 1;
      break;
    }
  }
  return flag;
}




boolean compareWithoutCountryCode(String number)
{
  boolean flag = 0;
  
  for (int i = 0; i < totalPhoneNo; i++){
    phoneNo[i] = readFromEEPROM(offsetPhone[i]);
    //remove first 3 digits (country code)
    phoneNo[i].remove(0,3);
    //Serial.println("meee1: "+phoneNo[i]);
    if(phoneNo[i].equals(number)){
      //Serial.println(phoneNo[i]);
      flag = 1;
      break;
    }
  }
  return flag;
}



void sendLocation(String phoneNumber)
{
  
  boolean newData = false;
  for (unsigned long start = millis(); millis() - start < 2000;)
  {
    while (neogps.available())
    {
      if (gps.encode(neogps.read()))
        {newData = true;break;}
    }
  }
  if(newData)
  {
    newData = false;
    String latitude = String(gps.location.lat(), 6);
    String longitude = String(gps.location.lng(), 6);
    //String speed = String(gps.speed.kmph());
    
    String text = "Latitude= " + latitude;
    text += "\n\r";
    text += "Longitude= " + longitude;
    text += "\n\r";
    text += "Speed= " + String(gps.speed.kmph()) + " km/h";
    text += "\n\r";
    text += "Altitude= " + String(gps.altitude.meters()) + " meters";;
    text += "\n\r";
    text += "http://maps.google.com/maps?q=loc:" + latitude + "," + longitude;
         
    Reply(text, phoneNumber);
  }
  
}
void sendLocation1(String phoneNumber)
{
  boolean newData = false;
  for (unsigned long start = millis(); millis() - start < 2000;)
  {
    while (neogps.available())
    {
      if (gps.encode(neogps.read()))
        {newData = true;break;}
    }
  }
  if(newData)
  {
    newData = false;
    String latitude = String(gps.location.lat(), 6);
    String longitude = String(gps.location.lng(), 6);
    //String speed = String(gps.speed.kmph());
    
    String text = "Accident Accident";
    text += "\n\r";
    text += "Latitude= " + latitude;
    text += "\n\r";
    text += "Longitude= " + longitude;
    text += "\n\r";
    text += "Speed= " + String(gps.speed.kmph()) + " km/h";
    text += "\n\r";
    text += "Altitude= " + String(gps.altitude.meters()) + " meters";
    text += "\n\r";
    text += "http://maps.google.com/maps?q=loc:" + latitude + "," + longitude;
         
    debugPrint(text);
  }
}
void sendLocation2(String phoneNumber)
{
  boolean newData = false;
  for (unsigned long start = millis(); millis() - start < 2000;)
  {
    while (neogps.available())
    {
      if (gps.encode(neogps.read()))
        {newData = true;break;}
    }
  }
  if(newData)
  {
    newData = false;
    String latitude = String(gps.location.lat(), 6);
    String longitude = String(gps.location.lng(), 6);
    String text = "Calling for Hellp";
    text += "\n\r";
    text += "Latitude= " + latitude;
    text += "\n\r";
    text += "Longitude= " + longitude;
    text += "\n\r";
    text += "Speed= " + String(gps.speed.kmph()) + " km/h";
    text += "\n\r";
    text += "Altitude= " + String(gps.altitude.meters()) + " meters";
    text += "\n\r";
    text += "http://maps.google.com/maps?q=loc:" + latitude + "," + longitude;
         
    debugPrint(text);
    Reply(text, phoneNumber);
  }
  
}
void mpu_read(){
 Wire.beginTransmission(MPU_addr);
 Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
 Wire.endTransmission(false);
 Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers
 AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)    
 AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
 AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
 Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
 GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
 GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
 GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
 }
 void stu(){

  Blynk.begin(auth, ssid, pass);
  
  timer.setInterval(1000L, myTimerEvent);
  Serial.print("Initializing Pulse Oximeter..");

  if (!pox.begin())
  {
    Serial.println("FAILED");
    for (;;);
  }
  else
  {
    Serial.println("SUCCESS");
    pox.setOnBeatDetectedCallback(onBeatDetected);
  }

 }