Project tutorial
Anomaly Detection & Temperature Monitoring Using Bolt IoT

Anomaly Detection & Temperature Monitoring Using Bolt IoT © GPL3+

Use Bolt IoT kit and Arduino Uno to make your own anomaly detection & temperature monitoring device in both modes, i. e online and offline.

  • 1,600 views
  • 1 comment
  • 15 respects

Components and supplies

Apps and online services

About this project

Hello World

I'm Ashish Anand, this is a project specified in my Internshala IoT training program powered by Bolt IoT. This Capstone Project assignment description given as follows the pharmaceutical companies use a cooling chamber which is similar to a refrigerator to keep the tablets and maintain the temperature in the required limits.

For this project I made a prototype using Bolt IoT and Arduino to work in both condition i.e online and offline

Working Principle

1) Online Mode

if the device is connected to the internet then the Bolt module sends the data to Bolt IoT cloud and digital ocean server. if anomaly is detected then send email and sms to owner and supervisor of the pharmaceutical company.

machine learning algorithm for anomaly detection in the chamber.

it check whether enough data has been accumulated to calculate the Z-score, we calculate the Z score (Zn) for the data and use it to calculate the upper and lower threshold bounds required to check if a new data point is normal or anomalous.

  • The next code is used to initialize the Bolt and SMS variables, which we will use to collect data and send SMS alerts. Here we also initialize an empty list with the name 'history_data' which we will use to store older data, so that we can calculate the Z-score.
  • If anomaly detected we will be updated via SMS that ""Someone opened the chamber""
if sensor_value > maximum_limit or sensor_value < minimum_limit:
  response = mailer.send_email("Alert", "The Current temperature is beyond the threshold ")
if sensor_value > bound[0] :
  print ("The temperature increased suddenly. Sending Sms.")  response = sms.send_sms ("Someone opened the chamber")
  print("This is the response ",(response))
elif sensor_value < bound[1]:
  print ("The temperature decreased suddenly. Sending an email.")           
  response = mailer.send_email("Someone opened the chamber")           
  print("This is the response ",response)
history_data.append(sensor_value);  
except Exception as e:      
  print ("Error",e)   
time.sleep(10)

2) Offline Mode

imagine if the internet is not connect to device for some reason. if any anomaly is occur in the chamber of pharmaceutical company that cause loss to that company.thats why I build an offline mode for this project

if the worker or supervisor of that company wants to see temperature inside the chamber in realtime without going inside the chamber we use an lcd display to show the current temperature of the chamber.i aslo use ldr and push button to detect chamber is close or not it will alert the supervisor

the device can be place on door of the chamber and sensor like Lm35, LDR are placed inside the chamber and push button is placed corner of the door.

logic for door open close

we know that when fridge is close the intesity of light is low inside the fridge or chamber.the intensity of light is high when we open the fridge or chamber according to this we use LDR and push button to detect whether door is close or not

if (push button button is press and intensity is low )
    print(door closed)
else
    print(door is open )

Step 1: Hardware Setup

Connect all the component as shown in the circuit diagram given above.

  • connect the bolt to the Arduino using UART communication
  • connect LM 35 at Analog pin of Arduino Uno i.e A0
  • connect LDR to Analog pin of Arduino at A1
  • connect push button at digital pin i.e D2

Step 2: Configure Bolt IoT

There have been quite a few projects developed around the Bolt WiFi module, so I believe the reader has already created an Account on the Bolt Cloud and linked their Bolt WiFi module to the Cloud account.

If that is not the case, you might want to go through this.

1. Create a new product on the Bolt Cloud.

Ensure to select the 'Input Devices' and 'UART' option.

2. Configure the product:

I have shared the code for the software configuration.

Once done save and exit the product configuration view.

3. Link the Bolt device to your new product.

Once the device is linked, remember to click on the Deploy Configurations button

4. View your device.

The Cloud polls the device for data every 5 minutes, so it would be best to leave the system be for about 20 to 25 minutes before you check.

Step 3: Install the Required Libraries

For this project you will require the BoltIoT-Arduino-Helper, the Adafruit_GFX.h and Adafruit_ST7735.h Arduino libraries.

To install the libraries just go to the link above, and click on the clone or download button.

Then click on the Download ZIP button. A zip file containing the library will be downloaded.

Once the library is downloaded, go to the Arduino IDE's tool bar, Sketck>Include Library>Add.ZIP Library...

Select the library file which you dowloaded earlier, and click on choose.

Remember to install ALL 3 LIBRARIES.

Step 4: Upload the Code

1. Open the Arduino IDE.

2. Copy the Arduino Code at the end of the blog, and replace all the code inside the sketch with the copied code.

3. Connect your Arduino Uno to the PC and click on Upload.

CAUTION: For Arduino Uno users, remember to disconnect the Bolt module from the Arduino while uploading the code.

Step 4: Write Program to Fetch Sense Value to Server

Open putty to connect to digital ocean server.

A Python Script (running on a server or your PC, for instance) queries the Bolt Cloud for this temperature value using the Bolt Python Library, which in turn is based on the Bolt open APIs for Serial Read.

open my code in nano editor and change the conf.py and email_conf.py according to your account setup boltiot, twilio, @mailgum

The Python script then checks if the temperature is less than a preset threshold. In case the anomaly is occurred or temperature cross the threshold, an SMS & mail alert is sent out using the Twillio SMS service and @mailgum.

Code

main code for Arduino UnoC/C++
this code for Arduino Uno
#include <Adafruit_GFX.h>  // Include core graphics library
#include <Adafruit_ST7735.h>  // Include Adafruit_ST7735 library to drive the display
#include <BoltIoT-Arduino-Helper.h>//Include boltiot library

// Declare pins for the display:
   #define TFT_CS     10
   #define TFT_RST    8 
   #define TFT_DC     9
// The rest of the pins are pre-selected as the default hardware SPI for Arduino Uno (SCK = 13 and SDA = 11)


// Create display:
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);
//variables
int inPin = 2;  //for push button
int push_button = 0;
int lm35_sensor_value;
int intensity_of_light;
float cel ;


String getAnalogData(String *data){
  String retval;
  retval=cel;
  return retval;
}

void setup()  // Start of setup
{

   Serial.begin(9600);
   boltiot.begin(6,7); 
   boltiot.setCommandString("GetAnalogData",getAnalogData);
  
    // Display setup:
   tft.setTextWrap(false);
    // Use this initializer if you're using a 1.8" TFT
   tft.initR(INITR_BLACKTAB);  // Initialize a ST7735S chip, black tab
   tft.fillScreen(ST7735_BLACK);  // Fill screen with black

   //tft.setRotation(0);  // Set orientation of the display. Values are from 0 to 3. If not declared, orientation would be 0,
                         
 
  // Draw rectangle:
     tft.fillRect(0, 0, 129, 30,ST7735_WHITE);
     tft.fillRect(0,30,129,40,ST7735_MAGENTA);
     tft.fillRect(0,115,129,45,ST7735_CYAN);
    // tft.drawRect(0, 30, 129, 40, ST7735_WHITE);
    
  // Write to the display the text "Hello":
  
    tft.setCursor(0, 5);  // Set position (x,y)
    tft.setTextColor( ST7735_GREEN,ST7735_WHITE); // Set color of text. First is the color of text and after is color of background
    tft.setTextSize(2);  // Set text size. Goes from 0 (the smallest) to 20 (very big)
    tft.println("temperature");  // Print a text or value
    
}  // End of setup





void loop()  // Start of loop
{

 push_button = digitalRead(inPin);
  lm35_sensor_value = analogRead(A0);

  float mv = ( lm35_sensor_value/1024.0)*5000; 
    cel = mv/10;
 // float farh = (cel*9)/5 + 32;  

  
 Serial.print("TEMPRATURE = ");
 Serial.print(cel);
 Serial.print("*C");
 Serial.println();
 //boltiot.processPushDataCommand(cel);
 int  intensity_of_light = analogRead(A1) ;
 
  boltiot.handleCommand();

 

  if (push_button == HIGH && intensity_of_light < 20 ) {   // door closed

       tft.fillRect(0,70,129,45,ST7735_GREEN);
      tft.setCursor(0, 70);  // Set position (x,y)
      tft.setTextColor(ST7735_BLACK, ST7735_GREEN);  // Set color of text. First is the color of text and after is color of background
      tft.setTextSize(3);  // Set text size. Goes from 0 (the smallest) to 20 (very big)
      tft.println("door is"); 
       tft.setCursor(0, 90);  // Set position (x,y)
      tft.setTextColor(ST7735_BLACK, ST7735_GREEN);  // Set color of text. First is the color of text and after is color of background
      tft.setTextSize(3);  // Set text size. Goes from 0 (the smallest) to 20 (very big)
      tft.println("closed");
     
   } else {         // door open
      tft.fillRect(0,70,129,52,ST7735_RED);
      tft.setCursor(19, 70);  // Set position (x,y)
      tft.setTextColor(ST7735_BLACK, ST7735_RED);  // Set color of text. First is the color of text and after is color of background
      tft.setTextSize(3);  // Set text size. Goes from 0 (the smallest) to 20 (very big)
      tft.println("door"); 
       tft.setCursor(0, 90);  // Set position (x,y)
      tft.setTextColor(ST7735_BLACK, ST7735_RED);  // Set color of text. First is the color of text and after is color of background
      tft.setTextSize(3);  // Set text size. Goes from 0 (the smallest) to 20 (very big)
      tft.println("is open");
   } 


  tft.setCursor(0, 133);  // Set position (x,y)
  tft.setTextColor(ST7735_BLACK,  ST7735_CYAN );  // Set color of text. First is the color of text and after is color of background
  tft.setTextSize(3);
  tft.println("LDR ");
  tft.setCursor(68, 133);
  tft.println(intensity_of_light); 
  
  tft.setCursor(45, 38);  // Set position (x,y)
  tft.setTextColor(ST7735_YELLOW,ST7735_MAGENTA);  // Set color of text. First is the color of text and after is color of background
  tft.setTextSize(3);  // Set text size. Goes from 0 (the smallest) to 20 (very big)
  tft.println(cel); 
  
 delay(1000);
  
}  // End of loop
Code for data fetching from boltiot and checking threshold and anomaly detectionPython
Run this code on your server
import conf, email_conf, json, time, math, statistics
from boltiot import Sms, Email, Bolt



def compute_bounds(history_data,frame_size,factor):
    if len(history_data)<frame_size :
        return None

    if len(history_data)>frame_size :
        del history_data[0:len(history_data)-frame_size]
    Mn=statistics.mean(history_data)
    Variance=0
    for data in history_data :
        Variance += math.pow((data-Mn),2)
    Zn = factor * math.sqrt(Variance / frame_size)
    High_bound = history_data[frame_size-1]+Zn
    Low_Bound = history_data[frame_size-1]-Zn
    return [High_bound,Low_Bound]

minimum_limit = 4  
maximum_limit = 7

mybolt = Bolt(email_conf.API_KEY, email_conf.DEVICE_ID)
mailer = Email(email_conf.MAILGUN_API_KEY, email_conf.SANDBOX_URL, email_conf.SENDER_EMAIL, email_conf.RECIPIENT_EMAIL)
sms = Sms(conf.SSID, conf.AUTH_TOKEN, conf.TO_NUMBER, conf.FROM_NUMBER)

history_data=[]

while True:
    response = mybolt.analogRead('A0')
    data = json.loads(response)
    
    if data['success'] != '1':
        print("There was an error while retriving the data.")
        print("This is the error:"+data['value'])
        time.sleep(10)
        continue

    
    print ("The sensor value is "+(data['value']))
    sensor_value=0
    try:
        sensor_value = int(data['value'])
        
    
    except Exception as e:
        print("There was an error while parsing the response: ",e)
        continue

    bound = compute_bounds(history_data,email_conf.FRAME_SIZE,email_conf.MUL_FACTOR)
    if not bound:
        required_data_count=email_conf.FRAME_SIZE-len(history_data)
        print("Not enough data to compute Z-score. Need ",required_data_count," more data points")
        history_data.append(int(data['value']))
        time.sleep(10)
        continue

    try:
        if sensor_value > maximum_limit or sensor_value < minimum_limit:
            response = mailer.send_email("Alert", "The Current temperature is beyond the threshold ")
        if sensor_value > bound[0] :
            print ("The temperature increased suddenly. Sending Sms.")
            response = sms.send_sms("Someone opened the chamber")
            print("This is the response ",(response))
        elif sensor_value < bound[1]:
            print ("The temperature decreased suddenly. Sending an email.")
            response = mailer.send_email("Someone opened the chamber")
            print("This is the response ",response)
        history_data.append(sensor_value);
    except Exception as e:
        print ("Error",e)
    time.sleep(10)
conf.pyPython
include this file (import conf) in main code for sms sending
SSID = 'You can find SSID in your Twilio Dashboard' 
AUTH_TOKEN = 'You can find  on your Twilio Dashboard' 
FROM_NUMBER = 'This is the no. generated by Twilio. You can find this on your Twilio Dashboard'
TO_NUMBER = 'This is your number. Make sure you are adding +91 in beginning'
API_KEY = 'This is your Bolt Cloud account API key'
DEVICE_ID = 'This is the ID of your Bolt device'
FRAME_SIZE = 10
MUL_FACTOR = 6
email_conf.pyPython
MAILGUN_API_KEY = 'This is the private API key which you can find on your Mailgun Dashboard' 
SANDBOX_URL= 'You can find this on your Mailgun Dashboard' 
SENDER_EMAIL = 'This would be test@your SANDBOX_URL'
RECIPIENT_EMAIL = 'Enter your Email ID Here'
API_KEY = 'This is your Bolt Cloud accout API key'
DEVICE_ID = 'This is the ID of your Bolt device'
FRAME_SIZE = 10
MUL_FACTOR = 6

Schematics

circuit diagram
temperature_xPJZbK49as.fzz

Comments

Similar projects you might like

Portable Temperature Station V2: IOT Edition

Project tutorial by Isaac100

  • 2,774 views
  • 0 comments
  • 7 respects

Bolt Controlled Robot Car

Project tutorial by Team Bolt

  • 2,115 views
  • 1 comment
  • 18 respects

Monitoring Health Station

Project tutorial by Diana Khalipina

  • 2,295 views
  • 2 comments
  • 25 respects

Android App-Based Home Automation System Using IOT

Project tutorial by Team Autoshack

  • 28,017 views
  • 18 comments
  • 89 respects
Add projectSign up / Login