Temperature Monitoring using Python

Temperature Monitoring using Python

Hello guys👋, so this post is going to be super excited and useful for those who are trying to find and implement some basic projects to increase and upscale their technical skills and knowledge.

Here is one of the simple projects, which I did during my college project season and it is super useful and easy to implement, with basic knowledge of python and some of the technical tools you can try out this project and can also list it to your Resume or CV, you can also take this project and show to your project’s coordinator during your project season.

What’s the Project About?

Setup_image.jpg The project is about the Temperature Monitoring where we will monitor the temperature of a closed environment, for example – like a closed room. Since, Environment temperature should be a comfortable one, where the people can work comfortably and can go up to their efficiency and can work comfortably whether it is machinery or manpower. One of important factors that are needed be monitored is the temperature and humidity of the room, because if any one of the two goes mismatching it creates an unpleasing and uncomfortable environment.

Where it can be useful?

This project has so many uses from a real-time perspective, let me list some of the uses-

  • It can be useful in a room where’s temperature needs to be in between certain range.
  • A factory or industry where people cannot present at all the time and there’s temperature need to be fixed between certain range.
  • While transporting some of the goods where they need to be in certain temperature range with limited power supply.
Hence these are some of the useful parts of the project where it can be implemented with full control over the temperature and best results.

🔎Let’s know the Project in Detail

Connection View.png Controlling temperature of a controlled environment is an important aspect of any workspace whether it is a commercial space or a domestic space. If temperature or humidity is either increased or decreased of any area, it becomes very difficult to be there and thus, if possible, should be kept in comfortable conditions at all times. One way to do it is to monitor and control the temperature of the closed surroundings using the concepts of Machine Learning and IoT.

This research’s purpose is the same to find an easy and an inexpensive way to find an alternative to it which is based on microcontroller, a Wi-Fi Module, Buzzer, few Temperature sensors and a Solderless board. The system is designed in such a way that the temperature can be monitored whether it is in the given range of temperature as prescribed by the user.

We are also enabling to predict the temperature which will predict the temperature according to the temperature graph being made as by the input taken by the Temperature Sensors using Polynomial Regression Algorithm. Also, if the temperature of the enclosed area is not in the threshold range as suggested by the user, the System will automatically send a notification to user(s) via SMS, E-Mail or even through a Telegram Channel.

Note : To do this project completely you will need some technical tools and access to some of the software and online services.

Introduction :

The main scope of this project is to measure the temperature of a closed environment let’s say we want to measure the temperature of a room.

Basically, a range is fixed that is, the minimum and maximum temperature values are fixed and if the measured value is not in this range, then the system alarms and sends a notification to the user’s device through SMS, email, telegram etc.

Components required to work the project

  1. Bolt WiFi Module(microcontroller)
  2. LED (generic)
  3. Buzzer-to alarm the area
  4. Jumper wires (generic)
  5. LM35-temperature sensor
  6. Breadboard (generic)

We are using Z-Score analysis which also help in detecting the anomaly of the temperature sensor which means a variable’s value going beyond a certain range of values (upper and lower bound).These bound can be calculated using input values, frame size and multiplication factor, where frame size is minimum number of input values needed for Z-Score analysis and these predictions as well as the old values, all will be plotted on a graph, which the user can easily understand what could be the next game of plan. So, we going to use a formula to find any kind of anomaly that can happen in the proposed system.

Z score analysis.png So in the above listed formula, r = Frame Size C = Multiplication factor. To do so and implement the project, you have to register at a platform called Twilio this will help us to get the notification on the device.

🧾Creating & Setting up an account on Twilio

Twilio is a 3rd party PaaS (Platform as a Software) company that provides cloud communication. It uses web APIs to make calls and send and receive messages to registered mobile numbers. The following gives step-by-step instructions to create a Twilio account.

URL - Go to twilio.com .

Sign up - You will find the welcome page. Here click on the "Sign up for free option" twilio.png

Basic steps include Register –> confirm mobile number –> setup required function to carry-out –> Configure the file with the required private fields

After this follow the steps as asked from verification till the project creation and in the project, section ask to send notification to your device on the Twilio platform.

You can refer this guide if you encounter any problems but make sure to go for only free access option during Signup - Twilio Guide

👨‍💻Codes to implement the Project

Make sure to change the configurations and confidentials with yours before implementing the project.

Config_code.py

#This code is used to config the Twillio with the device
#configurations and credential file

api_key = 'XXXXXX' # Enter your API Key used in Twillio App
device_id = 'BOLTXXXXXXX' # Enter the device id i.e. the Bolt Id
telegram_chat_id = '@XXXXXXX'
telegram_bot_id = 'botXXXXXXXX'
threshold = [206.186, 309.28, 412.38] #Change the threshold values according to your environment
frame_size = 10
mul_factor = 2

Main_code.py

#This code helps in main working and running of the set-up

import conf, json, time, math, statistics, requests
from boltiot import 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-1]
    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]

mybolt = Bolt(conf.api_key, conf.device_id)
history_data = []

def send_telegram_message(message):
    url = "https://api.telegram.org/" + conf.telegram_bot_id + "/sendMessage"
    data = {"chat_id": conf.telegram_chat_id, "text": message}
    try:
        response= requests.request("POST", url, params = data)
        print("This is the Telegram response")
        print(response.text)
        telegram_data = json.loads(response.text)
        return telegram_data["ok"]
    except Exception as e:
        print("An error occurredin sending the alert message via Telegram")
        print(e)
        return False

def buzzer_alert():
    high_response = mybolt.digitalWrite("2", "HIGH")
    print(high_response)
    time.sleep(5)
    low_response = mybolt.digitalWrite("2", "LOW")
    print(low_response)
    time.sleep(5)


def check_temperature(value,checker):
    if value > conf.threshold[2]:
        print("The temperaure value increased the threshold value. Sending an alert notification")
        message = "Temperature increased the threshold value. The current value is: " + str(int(sensor_value*0.097))
        telegram_status = send_telegram_message(message)
        print("This is the Telegram status", telegram_status)
        if not checker:
            return buzzer_alert()
        if checker:
            return 0

    if value < conf.threshold[0]:
        print("The temperature value  decreased below the threshold value. Sending an alert notification")
        message = "Temperature decreased below the threshold value. The current value is: " + str(int(sensor_value*0.097))
        telegram_status = send_telegram_message(message)
        print("This is the Telegram status", telegram_status)
        if not checker:
            return buzzer_alert()
        if checker:
            return 0

    if value > conf.threshold[0] and value < conf.threshold[1]:
        print("The temperature value is between ",str(int(conf.threshold[0]*0.097))," and ",str(int(conf.threshold[1]*0.097)), ". Sending an alert notification")
        message = "Temperature is between " + str(int(conf.threshold[0]*0.097)) + " and " + str(int(conf.threshold[1]*0.097)) + ". Check prediction table. The current value is: " + str(int(sensor_value*0.097))
        telegram_status = send_telegram_message(message)
        print("This is the Telegram status", telegram_status)
        if not checker:
            return buzzer_alert()
        if checker:
            return 0

    if value > conf.threshold[1] and value < conf.threshold[2]:
        if not checker:
            time.sleep(10)
        if checker:
            return 0


while True:
    checker = False
    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("This is the value: " +data['value'])

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

    bound= compute_bounds(history_data, conf.frame_size, conf.mul_factor)
    if not bound:
        required_data_count = 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']))
        check_temperature(sensor_value, checker)
        continue

    try:
        if sensor_value> bound[0]:
            print("The temperature value increased suddenly. Sending an alert notification")
            message = "Temperature increased suddenly. The current value is: " + str(int(sensor_value*0.097))
            telegram_status = send_telegram_message(message)
            print("This is the Telegram status", telegram_status)
            buzzer_alert()
            checker = True
        elif sensor_value< bound[1]:
            print("The temperature value decreased suddenly. Sending an alert notification")
            message = "Temperature decreased suddenly. The current value is: " + str(int(sensor_value*0.097))
            telegram_status = send_telegram_message(message)
            print("This is the Telegram status", telegram_status)
            buzzer_alert()
            checker = True
        check_temperature(sensor_value, checker)
        history_data.append(sensor_value)
    except Exception as e:
        print("error", e)

Pediction_code.py

#This code helps in Predicting future instance values.
#Shows up the different Plots and can able to make comparisions.

setChartLibrary('google-chart');
setChartTitle('Polynomial Regression');
setChartType('predictionGraph');
setAxisName('time_stamp','temp');
mul(0.097);
setAnimation(true);
setCrosshair(true);
plotChart('time_stamp','analog');

Resulted Part of the Project is shown as Images.

  1. Screenshot of Notification received on the connected-device. result_1.jpg

  2. Prediction of the future Instance is shown in below Provided Image. result_3.jpg result_4.jpg

Paper work is available at, visit to read and completely understand the logic and working process of the project - The IJEAT Journal

You can download the paper and view it by 🔗Clicking here🔗

Conclusion of the Project

The project work is mainly to calculate the temperature of a closed environment and sends notification to the connected device through SMS, Mail, Telegram etc. only if the temperature of the region varies i.e., either the temperature increases or the temperature decreases.

The system is also capable of displaying temperature, humidity and predicted temperature in real time through web-based application or through a Telegram Channel. For Alerts the system can send it through SMS, E-Mail or through a Telegram Channel.

Hope that some of you try to implement the project and if done then drop your experience in the comment section.

**This is just the overview of the project to understand it correctly and know more about it visit the Github Repository

Thank you for Reading, would Love ❤ to hear your valuable feedback.

If anything is confusing or incorrect then let me know in the comment section. Thanks, from my side, this is Mayank, keep learning and exploring!!

Let's Connect Twitter | Linkedin