Python Data Types

Welcome to the next tutorial of our python course. We learned about python numbers in the last tutorial, and in this tutorial, Data types in Python include, dictionaries, sets, and Boolean, among others. We'll give a quick overview of the above data types in this section but later in this course, we'll go over each of them in-depth.

Introduction

In the Python programming language, data types are a necessary concept. Python assigns a data type to each value. Data Types are used to classify data objects or to assign a value to a data category. It aids in comprehending the many operations that can be applied to a value.

Python considers everything to be an object. Classes are represented by data types in Python. Variables are the names given to the objects or instances of these classes. Let's look at the various data types that Python has to offer.

Our variables can be used to store values that are of a specific data type. The type of a variable does not need to be specified when declaring a variable in Python because it is dynamically typed. The interpreter's default behavior is to tie a value to its type.

a = 5

We didn't define the type of the variable a, which has the integer value of five. Variable a will be automatically interpreted as an integer by Python.

Python can be used to determine variable`s type in a program. It is possible to retrieve the type of a variable in Python by using the type() method. Consider the following scenario for defining values for various data kinds and determining their type.

Standard data types

Different kinds of values can be stored in a variable. A name of a person, for example, must be stored as a string, while his or her identity number should be stored as an integer. Python comes with a number of standard data types, each of which has its own storage method. The following is a list of the data types defined in Python.

Numbers

The term "number" refers to a sort of data that contains numerical values. Integer, float, and complex values are all available in the Python Numbers data type. The type() method in Python can be used to determine variable’s data type. isinstance() determines whether an object belongs to a specific class. When a variable is assigned a number, Python produces Number objects.

v = 5

print("type ", type(v))

z = 40.5

print("type", type(z))

t = 1+3j

print("type", type(t))

print(" Is this true or not?:", isinstance(1+3j,complex))

Python can handle three different forms of numeric data.

  • Int - Any integer value, such as 10, 2, 29, -20, -150, can be used. The length of an integer is unrestricted in Python. It is int's value.
  • Float - Float is a type of variable that stores float numbers such as 1.9, 9.902, 15.2, and so on. It has a precision of up to fifteen decimal places.
  • complex – The real and imaginary components of these numbers are represented by m and v in an ordered pair, m + iv. It's 1.9 j, 2.0 j, and so forth.

Sequence Type

List

The list might include a variety of data. A comma (,) is used to divide the elements in the list, which are then enclosed in square brackets []. To access the data of the list, we can use slice [:] operators. The concatenation (+) and repetition (*) operators behave similarly in lists and strings. Consider this scenario.

Output:

[1, 'hello', 'students', 5]

[5]

[1, 'hello']

[1, 'hello', 'students', 5, 1, 'hello', 'students', 5]

[1, 'hello', 'students', 5, 1, 'hello', 'students', 5, 1, 'hello', 'students', 5]

How do we access elements in a list?

The components of a list can be accessed in a variety of ways.

List Index

To get to a specific item in a list, we can use the index operator []. In Python, indices begin at 0 and go up from there. As a result, an index of 0 to 4 will be assigned to a list of five members. If you try to access indexes that aren't listed here, you will recieve an IndexError. An integer must be used as the index. We can't use floats or other kinds because TypeError will occur. Nested indexing is used to access nested listings.

Negative indexing

Python sequences can be indexed using negative numbers. For example, the index -1 represents the last item, and the number -2 represents the second-last item.

Adding item to a list

lists are mutable, meaning their elements can be changed. To update a single item or a set of objects, use the assignment operator (=).

Deleting items from a list

The in-built del function can be used to remove one or more entries from a list. It has the ability to completely remove the list.

Tuple

In many ways, a tuple is comparable to a list. Tuples are built up of items of several data kinds, similar to lists. The tuple components enclosed in parentheses are separated by a comma (,).

Read-only data structures, such as tuples, do not allow changes to its elements' size or value.

Let's look at a simple tuple example.

tuup = ("hello"students", 5)

# Check tuup type

print (type(tuup ))

#Print tuup

print (tuup )

# Tuup slice

print (tuup[1:])

print (tuup[0:1])

# Tuple concat

print (tuup + tuup)

# Tuup repetition by use of *

print (tuup * 4)

# Addition of a value to the tuup. It throws an error.

t[5] = "hi"

Output:

<class 'tuple'>

('hello', 'students', 5)

('students', 5)

('hello',)

('hello', 'students', 5, 'hello', 'students', 5)

('hello', 'students', 5, 'hello', 'students', 5, 'hello', 'students', 5, 'hello', 'students', 5)

How do we access tuple items?

1. Use of index

The index operator [] can be used in a tuple to access items, with the index starting at 0.

As a result, a tuple with six elements will have indices ranging from 0 to 5. If you try to access an index that isn't in the tuple index range, you'll get an IndexError (6,7,... in this example).

We can't use floating or other forms of data because the index must be an integer. Because of this, a TypeError is generated.

Using the nested index feature, tuples that have been nested can be found.

2. Negative Indexing

Python sequences can be indexed using negative numbers. For example, the index -1 represents the last item, and the number -2 represents the second-last item.

How to change a Tuple's Value

Tuples are immutable, unlike lists.

This implies that once a tuple's elements have been assigned, they cannot be changed. It is possible to alter the nested items of an element that is itself a changeable data type, such as a list.

A tuple can also have different values assigned to it (reassignment).

Deleting a Tuple

A tuple's elements cannot be changed, as previously stated. We can't delete or remove entries from a tuple because of this.

The keyword del, on the other hand, can be used to completely delete tuples.

Dictionary

A dictionary is a collection of objects that have a key and a value. It's similar to a hash table or an associative array in that each key stores a single value. A primitive data type can be stored in key, but a Python object can be stored in value.

The curly brackets contain the elements in the dictionary, which are separated by a comma (,).

Consider this scenario.

m = {1:'Jim', 2:'malec', 3:'joy', 4:'mark'}

print (m)

print ("name 1 "+d [2])

print ("name 2 "+ d [3])

print (m.keys())

print (m.values())

Output:

name 1 malec

name 2 joy

{1: 'Jim', 2: 'malec', 3: 'joy', 4: 'mark'}

Accessing elements in a dictionary

A dictionary employs keys instead of indexes to access values. Both square brackets [] and the get() function can be used with keys, if the dictionary does not have a key, KeyError is raised. In contrast, if the key cannot be retrieved, the get() method returns None.

Dictionary Elements: Changing and Adding

Dictionaries are subject to change. Using the assignment operator, new objects can be created, or existing ones' values can be altered. If the key already exists, the existing value will be changed. If the key is missing, the dictionary is updated with a new (key: value) pair. As an example,

# manipulation and addition of Dict items

Removing elements from a dictionary

Using the pop() method, we can eliminate a specific item in a dictionary. After deleting items with any of the supplied keys, this function will return that item.

The popitem() method can be used to delete and return a key or value item pair from dictionaries.

Using the clear() method, all the items can be eliminated at once.

Deleting individual entries or the entire dictionary is likewise possible with the del keyword. Consider the following:

meters = {11: 5, 12: 8, 13: 7, 14: 17, 15: 75}

print(meters.pop(11))

Output:

{12: 8, 13: 7, 14: 17, 15: 75}

Boolean

For the Boolean type, True and False are the default values. These figures are used to tell if the assertion stated is accurate. It's wrapped up in the bool class. True is any non-zero number or the character 'T', while false is any non-zero value or the character 'F'. Consider the following.

Python Booleans as Keywords

Keywords are not built-in names. They're regular variables as far as the Python language is concerned. If you assign to them, the built-in value will be overridden.

True and False, on the other hand, are not built-ins. Keywords are what they are. True and False, unlike many other Python keywords, are Python expressions. They can be used everywhere other expressions, such as 1 + 1, can be used because they're expressions.

It is possible to assign a Boolean value to variables, but not to True or False.

Because False/True is a Python keyword, you can't assign to it. True and False behave similarly to other numeric constants in this way. You can pass 1.5 to functions or assign it to variables, for example. It is, however, hard to put a value on 1.5. The Python expression 1.5 = 5 is incorrect. When processed, both 1.5 = 5 and False = 5 are invalid Python code and will result in a SyntaxError.

Python Booleans as Numbers

Python considers Booleans to be a numerical type. For all intents and purposes, that means they're numbers. To put it another way, Booleans can be used to perform mathematical operations and compared to numbers.

Boolean Operators

Operators With No Inputs

True and False can be thought of as Boolean operators that don't require any inputs. The result of one of these operators is always True, while the other is always False.

Sometimes it's helpful to think of Python's Boolean values as operators. This method, for example, can help you remember that they aren't variables. It is impossible to assign to True or False for the same reason you can't assign to +.

In Python, there are only two possible Boolean values. When there are no inputs to a Boolean operator, the result is always the same. As a result, the only two Boolean operators that do not take inputs are True and False.

Set

Python Set refers to the data type's unordered collection. It's iterable, changeable (meaning you may change it after you've created it), and contains unique items. To construct the set, elements` sequence is given between curly brackets and separated by a comma, or the built-in method set() is used. It can have a variety of different values in it. Consider this scenario.

seta = set()

setb = {'Jane', 2, 3,'class'}

print (setb)

setb.add(10)

print (setb)

setb.remove(2)

print(setb)

Output:

{3, 'class', 'jane', 2}

{'class', 'Jane', 3, 2, 10}

{'class', 'jane', 3, 10}

Conclusion

Congratulations on completing this introduction to data type tutorial. In this tutorial, we covered the in-built data types provided by Python.

So far, all of the examples have just altered and presented constant data. In almost all projects, you'll want to build objects which vary in value as the program runs. In the next topic, we will look at sets in depth.

Update LCD Display with ESP32 Web Server

Hello readers, I hope you all are doing great.

ESP32 is a powerful chip for Internet of Things applications. This tutorial is also based on one of the ESP32 applications in the field of IoT.

Where To Buy?
No.ComponentsDistributorLink To Buy
1ESP32AmazonBuy Now

Project Overview

In this tutorial, we will learn how to update LCD display with new data or input using a web server created with ESP32.

Fig. 1

To achieve the target, we will be using an HTML (Hypertext Markup Language) form to provide web input and then update the text displayed on LCD. The values or input received from the webserver will be further stored inside a variable in the code for further use (to display on LCD).

We have already posted a tutorial on LCD (Liquid Crystal Display) interfacing with ESP32. In that tutorial, we demonstrated how to display the hard-coded data (in the ESP32 module) on LCD.

ESP32 Web Server

A web server is computer software and hardware that accepts requests and responds to those requests using HTTP (Hypertext transfer protocol) or HTTPS (HTTP Secure) (HTTP is a network protocol for delivering online content to client user agents).

The ESP32 standalone web server is mobile-enabled and can be accessed from any device with a browser on the local network. B. Mobile phones, computers, laptops, tablets. However, all the devices must be connected to the same WiFi network to which the ESP32 is connected.

Software and Hardware requirements

  • ESP32 development board
  • 16*2 LCD display
  • 10K trim-pot
  • Breadboard or general-purpose PCB
  • Connecting Wires
  • Arduino IDE
  • h, ESPAsynchWenServer.h header files

Interfacing16*2 LCD with ESP32

There are basically two ways to connect the ESP32 to a 16 * 2 LCD display.

  1. Interface with I2C adapter
  2. Direct connection without using I2C adapter.

Connecting an LCD display without an I2C adapter is cheap, but this method requires more connection cables and is complicated to implement. On the other hand, using an I2C adapter reduces complexity but increases cost. In this tutorial, you will connect the ESP32 directly without using an I2C adapter.

Table: 1

Fig. 2: ESP32 and 16*2 LCD interfacing

For more details on interfacing 16*2 LCD with ESP32, follow our previous tutorial at www.theengineeringprojects.com

Programming ESP32

Installing ESP32 board manager in Arduino IDE:

We are using Arduino IDE to compile and upload code into ESP32 module. You must have ESP32 board manager installed on your Arduino IDE to program ESP32 module. To know more about Arduino IDE and how to use it, follow our previous tutorial i.e., on ESP32 programming series. The link is given below:

https://www.theengineeringprojects.com/2021/11/introduction-to-esp32-programming-series.html

Installing necessary libraries:

ESP32 board manager doesn’t come with inbuilt libraries to create an asynchronous web server. So we need to download the library file from external sources and then add into Arduino IDE.

We need to install two library files:

  1. ESPAsynWebServer: Follow the link https://github.com/me-no-dev/ESPAsyncWebServer to download the respective library.
  1. AsyncTCP: You can download the AsyncTCP library from the following link https://github.com/me-no-dev/AsyncTCP

Once you have successfully downloaded the required libraries, next step it to install or add these libraries in Arduino IDE.

To add the libraries in Arduino IDE, go to Sketch >> Include Library >> Add .zip library and then select the downloaded library files.

Fig. 3: adding necessary libraries

Arduino IDE code

#include < WiFi.h >

#include < AsyncTCP.h >

#include < ESPAsyncWebServer.h >

#include < LiquidCrystal.h > // LCD header file

LiquidCrystal lcd (22, 23, 5, 18, 19, 21 );

AsyncWebServer server ( 80 );

// Enter your netwrok credentials

const char* ssid = "replace this with netwrok SSID";

const char* password = "replace this with Password";

const char* PARAM_INPUT_1 = "data_field1";

const char* PARAM_INPUT_2 = "data_field2";

// HTML web page to handle data input fields

const char index_html[] PROGMEM = R"rawliteral(

<!DOCTYPE HTML> <html> <head>

<title> ESP Input Form </title>

<meta name = " viewport" content="width=device-width, initial-scale=1 ">

<style>

html{ font-family: Times New Roman; display: inline-block; text-align: justify;}

</style>

</head> <body>

<form action="/get">

Data_field1: <input type="text" name="data_field1" >

<input type="submit" value="Post ">

</form> <br>

<form action="/get">

Data_field2: <input type="text" name="data_field2">

<input type="submit" value="Post">

</form><br>

</body></html>)rawliteral";

void notFound(AsyncWebServerRequest *request) {

request->send(404, "text/plain", "Not found");

}

void setup() {

 

Serial.begin(115200);

WiFi.mode(WIFI_STA);

WiFi.begin(ssid, password);

if (WiFi.waitForConnectResult() != WL_CONNECTED) {

Serial.println("WiFi Failed!");

return;

}

Serial.println();

Serial.print("IP Address: ");

Serial.println(WiFi.localIP());

//===set LCD

lcd.begin(16, 2);

lcd.clear();

lcd.setCursor(1,0);

server.onNotFound(notFound);

server.begin();

// Send web page with input fields to client

server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)

{

request->send_P(200, "text/html", index_html);

});

server.on("/get", HTTP_GET, [] (AsyncWebServerRequest *request) {

String inputMessage;

String inputParam;

// GET input1 value

if (request->hasParam(PARAM_INPUT_1))

{

inputMessage = request->getParam(PARAM_INPUT_1)->value();

inputParam = PARAM_INPUT_1;

}

// GET input2 value

else if (request->hasParam(PARAM_INPUT_2))

{

inputMessage = request->getParam(PARAM_INPUT_2)->value();

inputParam = PARAM_INPUT_2;

}

else

{

inputMessage = " No message sent";

inputParam = " none";

}

Serial.println ( inputMessage );

delay( 1000);

lcd.clear();

lcd.print( inputMessage);

request-> send (200, "text/html", " HTTP GET request sent to ESP32("

+ inputParam + "): " + inputMessage +

"<br><a href=\"/\"> Back to Home Page </a>");

});

}

void loop( )

{

}

Code Description

  • The first step is adding the necessary header files.
  • Here we are using two libraries:
    • The first one is WiFi.h, which is used to enable the Wi-Fi module and hence wireless network connectivity.
    • LiquidCrystal.h is used to call the necessary functions required to interface and control LCD with ESP32.
    • ESPAsynchWenServer library file is responsible for creating an asynchronous web server.
    • AsyncTCP is used to enable a multi-connection network for ESP32 (Espressif’s) microcontroller unit.

Fig. 4: Adding header files

  • Define the data and control pins (of 16*2 LCD) to be interfaced with ESP32.

Fig. 5: LCD data and control pins

  • While creating a web server we also need to assign a port and usually port 80 is used for local web server.

Fig. 6: server port

  • Enter the network credentials in place of SSID and PASSWORD.

Fig. 7: Enter Network credentials

  • The next thing is the declaration of variables for input data fields.

Fig. 8

Creating HTML Form

  • !DOCTYPE html><html> is used to describe/indicate that we are transmitting HTML, this command should always be the first thing we send.
  • <title> tag is used to write a title for the web page.
  • The next line in the code is used to make the web page responsive in any web browser.
  • The <style> tag is used to style the webpage, which includes the type of font, alignment, display etc.

Fig. 9: HTML web page

  • Next comes the HTML form for user input. We are going to create two data input fields for user input and each filed is having a Post button to send the new data string to the ESP device and the variable declared to store the input will be updated.
  • <form> tag is used to create the HTML form. Here we are creating an HTML form with two input fields namely the Data_field2 and Data_filed2 and each field is having individual Post buttons to post the input from the web server to the client.
  • The action attribute is used to specify, where to send the data input provided in the input data fields after pressing the post
  • After pressing the post button a new web page will open, indicating the status whether the input string is successfully posted or not.

Fig. 10: HTML form for data input

  • The two attributes, type and value specifies a button and the text on the button respectively.

Fig. 11: Post button.

  • If we make an invalid request, the notFound() function will be called.
 

Setup

  • Initialize the serial monitor at 115200 baud rate for debugging purpose.
    • begin() function is used to initialize the Wi-Fi module with Wi-Fi credentials used as arguments.
    • The While loop will continuously run until the ESP32 is connected to Wi-Fi network.

Fig. 12

  • If the device is connected to local Wi-Fi network then print the details on serial monitor.
  • localIP() function is used to fetch the IP address.
  • Print the IP address on serial monitor using println() function.

Fig. 13: Fetch/obtain the IP adrress

  • Initialize the 16*2 LCD using begin() function.
  • Clear the previous data from the LCD before printing or displaying the new one using clear() function.
  • Set the cursor position at row 1 and column 0 using setCursor() function.

Fig. 14: Set 16*2 LCD

  • begin() function is used to initialize the web server once ESP32 is connected with the Wi-Fi network.

Fig. 15: Initialize the server

Handling HTTP GET requests

  • The next part in the programming includes handling of HTTP GET requests.
  • When we access the route URL, we send the web page to client along with the data input fields.
  • We have defined a variable namely index_html to save the HTML text.

Fig. 16: Send web page to client

  • Next task is handling what happens when device receive a request on the /get routes.
  • To save input values, we have created two variables: inputPram and

Fig. 17

  • Next we need to check if HTTP get request contains the Data_input1 and Data_input1 These fields values are saved on PRAM_INPUT_1 and PRAM_INPUT2.
  • If the HTTP GET request contains inputs, then the inputMessage1 will be set to the value inserted in the data_field1.

Fig. read the input from HTML form

  • Else there will be no input for inputMessage.

Fig. 18

  • Print the input value saved on variable inputMessage using Serial.print command.
  • clear() command is used to clear the previous data printed on LCD.
  • New data or message received from the web server will be printed on the LCD display using print() function.

Fig. 19

  • After pressing the post button a new web page will open, indicating the status whether the input string is successfully posted or not.

Fig. 20

Testing

  • Open your Arduino IDE and paste the above code.
  • Change the network credentials, that is the SSID and PASSWORD as per you network setup.
  • Compile and upload the code into ESP32 development board.
  • Before uploading the code make sure that you have selected the correct development board and COM port.

Fig. 21: Select development board and COM port

  • Once the code is uploaded successfully, open the Serial monitor and select the 1115200 baud rate (as per your code instructions).
  • Make sure Wi-Fi to which your ESP device is supposed to connect is ON.
  • Once your ESP32 is connected to the internet, the IP address of the device will be printed on the Serial monitor.
  • Copy the IP address.
  • Open the browser and paste the IP address and press
  • A web page with HTML form containing two input fields will open as shown below:

Fig. 22: web Page

  • Enter the text in the HTML form you want to be printed on on the LCD display.
  • Press the Post

Fig. 23: Enter the Input to ESP32

  • After pressing the post button a new web page will open, indicating the status whether the input string is successfully posted or not.

Fig. 24: Input Updated

Fig. 25: IP address and Web Input on serial monitor.

Fig. 26: String input received from Web server, printed on LCD

This concludes the tutorial. We hope you found this of some help and also hope to see you soon with a new tutorial on ESP32.

Server-Sent Events with ESP32 and DHT11

Hello readers, I hope you all are doing great. In this tutorial, we will learn how to update a webpage using Server-Sent Events and the ESP32 web server.

Where To Buy?
No.ComponentsDistributorLink To Buy
1ESP32AmazonBuy Now

What is Server-Sent Events (SSE)?

It is a server push technology that enables the client devices to receive automatic updates from a server over HTTP (Hypertext Transfer Protocol) connection. SSE also describes how the server can initiate data transmission towards the client once an initial connection with the client has been established.

We have already posted a tutorial on how to implement Web socket protocol with ESP32 which is also a protocol used to notify events to a web client. Both the Server-Sent Events (SSE) and Web-Socket technologies seem to be quite similar but they are not.

The major difference between the two is that SSE is unidirectional, where the web client can only receive the updates from the ESP32 but it can’t send updates back to ESP32. On the other hand, the Web-socket protocol is bi-directional where both the web client and ESP32 can send and receive updates/events.

Fig. 1 Server-Sent event

How does the Server-Sent Event works?

The Server-Sent Event process initiates with an HTTP request from the web client or web page to the ESP32 web server. After that, the ESP32 is ready to send updates or events to the web client as they happen. But the web client can’t send any response or data to the ESP32 server after the initial handshake takes place.

Server-sent event technology can be used to communicate an event, GPIO states or to send sensor readings to the web client, whenever a new reading is observed.

Project Overview

For demonstration purpose, we are using a DHT11 sensor with the ESP32 module. ESP32 web server will display two things i.e., temperature and humidity observed using the DHT11 sensor. So, whenever a new reading is being observed, the ESP32 sends the reading to the Web Client over Server-sent events. After receiving the latest sensor reading the client updates the web page data.

Software and Hardware requirements

  • ESP32 development board
  • DHT11 sensor
  • Connecting Wires
  • Breadboard
  • Arduino IDE
  • Necessary Libraries

DHT11 (a Temperature and Humidity sensor)

Fig. 2 DHT11 sensor

DHT11 is a humidity and temperature sensor that measures its surrounding environment. It measures the temperature and humidity in a given area. It is made up of an NTC (negative temperature co-efficient) temperature sensor and a resistive humidity sensor. It also has an 8-bit microcontroller. The microcontroller is in charge of ADC (analog to digital conversion) and provides a digital output over the single wire protocol.

The DHT11 sensor can measure humidity from 20% to 90% with +-5 percent accuracy (RH or relative humidity) and temperature from 0 degrees Celsius to 50 degrees Celsius with +-2C accuracy.

DHT11 sensors can also be used to build a wired sensor network with a cable length of up to 20 meters.

Interfacing DHT11 with ESP32 module

Table 1

Note: Connect a 10K resistor between data and power (+5V) pin of DHT11 sensor module.

Fig. 3 ESP32 and DHT11 connections/wiring

Programming with Arduino IDE

We are using Arduino IDE to compile and upload code into the ESP32 module. You must have ESP32 board manager installed on your Arduino IDE to program the ESP32 module. To know more about Arduino IDE and how to use it, follow our previous tutorial i.e., on ESP32 programming series. The link is given below:

https://www.theengineeringprojects.com/2021/11/introduction-to-esp32-programming-series.html

Steps to add the necessary libraries in Arduino IDE:

  • Go to Tools >> Manage Libraries.

Fig. 4 manage libraries

  • Search for the necessary library in Library Manager and click Install.
  • We are attaching an image, where we are installing the DHT11 sensor library.

Fig. 5 Install DHT sensor library

  • Follow the similar procedure for rest of the libraries.
  • After successfully installing all the required libraries close the Library Manager tab.

ESP32 board manager doesn’t come with inbuilt libraries to create an asynchronous web server. So we need to download the library file from external sources and then add into Arduino IDE.

We need to install two library files:

  1. ESPAsynWebServer: Follow the link https://github.com/me-no-dev/ESPAsyncWebServer to download the respective library.
  1. AsyncTCP: You can download the AsyncTCP library from the following link https://github.com/me-no-dev/AsyncTCP

Once you have successfully downloaded the required libraries, next step it to install or add these libraries in Arduino IDE.

To add the libraries in Arduino IDE, go to Sketch >> Include Library >> Add .zip library and then select the downloaded library files.

Fig. 6 adding necessary libraries

Arduino Code

#include <WiFi.h>

#include <AsyncTCP.h>

#include <ESPAsyncWebServer.h>

#include "DHT.h"

#define DHTPIN 4 // Digital pin connected to the DHT sensor

#define DHTTYPE DHT11 // DHT 11

// Initializing the DHT11 sensor.

DHT dht(DHTPIN, DHTTYPE);

// Replace with your network credentials

const char* ssid = "SSID";

const char* password = "password";

// Create AsyncWebServer object on port 80

AsyncWebServer server(80);

// Create an Event Source on /events

AsyncEventSource events("/events");

// Timer variables

unsigned long lastTime = 0;

unsigned long timerDelay = 20000; //20 sec timer delay

//==== Creating web page

const char index_html[] PROGMEM = R"rawliteral(

<!DOCTYPE HTML><html>

<head>

<title>SSE with ESP32 Web Server</title>

<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">

<link rel="icon" href="data:,">

<style>

html {font-family: Times New Roman; display: inline-block; text-align: justify;}

p { font-size: 1.2rem;}

body { margin: 0;}

.topnav { overflow: hidden; background-color: blue; color: white; font-size: 1rem; }

.content { padding: 20px; }

.card { background-color: #ADD8E6; box-shadow: 2px 2px 12px 1px rgba(140,140,140,.5); }

.cards { max-width: 600px; margin: 0 auto; display: grid; grid-gap: 2rem; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); }

.reading { font-size: 1.4rem; }

</style>

</head>

<body>

<div class="topnav">

<h1>Server-Sent Events </h1>

<h2> DHT11 Sensor Data </h2>

</div>

<div class="content">

<div class="cards">

<div class="card">

<p> DHT11 Temperature</p><p><span class="reading"><span id="temp">%TEMPERATURE%</span> &deg;C</span></p>

</div>

<div class="card">

<p> DHT11 Humidity</p><p><span class="reading"><span id="hum">%HUMIDITY%</span> &percnt;</span></p>

</div>

</div>

</div>

<script>

if (!!window.EventSource)

{

var source = new EventSource('/events');

source.addEventListener('open', function(e)

{

console.log("Events Connected");

}, false);

source.addEventListener('error', function(e)

{

if (e.target.readyState != EventSource.OPEN)

{

console.log("Events Disconnected");

}

}, false);

source.addEventListener('message', function(e)

{

console.log("message", e.data);

}, false);

source.addEventListener('temperature', function(e)

{

console.log("temperature", e.data);

document.getElementById("temp").innerHTML = e.data;

}, false);

source.addEventListener('humidity', function(e)

{

console.log("humidity", e.data);

document.getElementById("hum").innerHTML = e.data;

}, false);

}

</script>

</body>

</html>)rawliteral";

 

void setup() {

Serial.begin(115200); //initialize serial monitor

//===set and initialize Wi-Fi

WiFi.mode(WIFI_STA);

WiFi.begin(ssid, password);

Serial.print("Connecting to WiFi ..");

while (WiFi.status() != WL_CONNECTED)

{

Serial.print('.');

delay(1000);

}

Serial.print("IP Address: ");

Serial.println(WiFi.localIP()); // print the IP address

//====Initialize DHT11 sensor

dht.begin();

//====Handle Web Server

server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){

request->send_P(200, "text/html", index_html);

});

// Handle Web Server Events

events.onConnect([](AsyncEventSourceClient *client)

{

if(client->lastId())

{

Serial.printf("Client reconnected! Last message ID that it got is: %u\n",

client->lastId());

}

// send event with message "hello!", id current millis

// and set reconnect delay to 1 second

client->send("hello!", NULL, millis(), 10000);

});

server.addHandler(&events);

server.begin();

}

void loop()

{

delay(2000);

float humidity = dht.readHumidity();

// Read temperature as Celsius (the default)

float temperature = dht.readTemperature();

// Check if any reads failed and exit early (to try again).

if (isnan(humidity) || isnan(temperature))

{

Serial.println(F("Failed to read from DHT sensor!"));

return;

}

if ((millis() - lastTime) > timerDelay)

{

// Send Events to the Web Server with the Sensor Readings

events.send("ping",NULL,millis());

events.send(String(temperature).c_str(),"temperature",millis());

events.send(String(humidity).c_str(),"humidity",millis());

Serial.print(F("Humidity(%): "));

Serial.println(humidity);

Serial.print(F("Temp.: "));

Serial.print(temperature);

Serial.println(F("°C "));

}

}

Code Description

  • Here we are using four libraries:
    • The first one is WiFi.h, which is used to enable the Wi-Fi module and hence wireless network connectivity.
    • DHT.h is used to call the necessary functions required to interface DHT sensor with ESP32.
    • ESPAsynchWenServer library file is responsible for creating an asynchronous web server.
    • AsyncTCP is used to enable multi-connection network for ESP32 (Espressif’s) microcontroller unit.

Fig. 7 Header files

  • Next step is the declaration of variables for DHT11 sensor.
  • We are declaring 2 variables, the first one is the DHTPIN to store the GPIO number receiving input from DHT11 sensor and another variables is to define the type of DHT (i.e., whether DHT11 or DHT22).

Fig. 8 Global declarations

  • Next we are creating a DHT object called dht in the DHT sensor type (defined earlier) and the DHT pin.

Fig. 9

  • Enter the network credentials in place of SSID and PASSWORD.

Fig. 10 Enter Network credentials

  • While creating a web server we also need to assign a port and usually port 80 is used for local web server.

Fig. 11 Server port

  • Next step is creating a new event source(on /events).

Fig. 12 Event source

  • Timer variable declaration: the timerDelay and lastTime variables are declared to add delay using timer, instead of using delay() function. Here we are adding a delay of 20 seconds which means the web browser will be updated with new sensor reading in every 20 sec.

Fig. 13 Timer Variables

Creating the Web Page

  • !DOCTYPE html><html> is used to describe/indicate that we are transmitting HTML, this command should always be the first thing we send.
  • <title> tag is used to write title for the web page.

Fig. 14

  • The <style> tag is used to style the webpage, which includes the type of font, alignment, display, color, dimensions etc. You can make changes in the <style> tag as per your requirements.

Fig. 15

  • The content, which is to be displayed on the Web page is written inside the <body> tag. The <body> tag includes two headings h1 and h2 and sensor readings (temperature and humidity).

Fig. 16

Initializing an Event-Source connection

  • JavaScript is written inside the inside the <script> tag, which is responsible for initializing an event source connection with the web server and also to handle the events received from the web server.
  • An object EventSource is created and along with that the URL of the webpage sending the updates is also specified.
  • addEventListener() function is used to listen to the messages coming from the web server, once the event source is initiated successfully.

Fig. 17

  • Next task is adding an event listener for Whenever a new temperature reading is observed from the DHT11 sensor, ESP32 sends a “temperature” event to the web client.

Fig. 18

  • Similarly, another event is generated for It prints the latest readings on the web browser & puts the received data into the element with respective ID on the webpage.

Fig. 19

Setup

  • Initialize the serial monitor at a 115200 baud rate for debugging purposes.
    • begin() function is used to initialize the Wi-Fi module with Wi-Fi credentials used as arguments.
    • The While loop will continuously run until the ESP32 is connected to the Wi-Fi network.

Fig. 20

  • If the device is connected to a local Wi-Fi network then print the details on the serial monitor.
  • localIP() function is used to fetch the IP address.
  • Print the IP address on the serial monitor using println() function.

Fig. 21 Fetch/obtain the IP address

 

Fig. 22 Initialize DHT sensor

Handling HTTP GET requests

  • The next part in the programming includes handling HTTP GET requests.
  • When we access the route URL, we send the web page to the client along with the data input fields.
  • We have defined a variable namely index_html to save the HTML text.

Fig. 23

Handling Server Event source

  • The next task is setting up the event source on the webserver.

Fig. 24 Handling server events

 

Initializing web server

  • Initialize the webserver using begin() function.

Fig. 24 initializing web server

 

Loop()

  • DHT11 is a very slow sensor. It takes almost 250ms to read temperature and humidity.
  • So it is preferred to wait a few seconds before a new measurement or updated sensor reading.
  • Next, we are defining a float type variable ‘h’ to store humidity measured from the DHT11 sensor.
  • readHumidity() function is used to observe the humidity value.
  • readTemperature() function is used to read the surrounding temperature with the DHT11 sensor.

Fig. 25

 
  • If somehow the sensor fails to read or observer temperature and humidity values, then the respective results will be printed on the serial monitor.

Fig. 26 If error occurs while reading data from DHT11

Sending Events to the server

  • Send the updated events or the latest observation from the DHT11 sensor the web browser over the local network.
  • The sensor readings will be updated in every 20 second as per the code instructions.

Fig. 27 Sending events to the server

  • Print the temperature and humidity readings (observer form the DHT11 sensor) on the Serial monitor.

Fig. 28 Print Sensor data on the Serial monitor

Testing

  • Open your Arduino IDE and paste the above code.
  • Change the network credentials, that is the SSID and PASSWORD as per you network setup.
  • Compile and upload the code into ESP32 development board.
  • Before uploading the code make sure that you have selected the correct development board and COM port.

Fig. 29 Select development board and COM port

  • Once the code is uploaded successfully, open the Serial monitor and select the 1115200 baud rate (as per your code instructions).
  • Make sure Wi-Fi to which your ESP device is supposed to connect is ON.
  • Once your ESP32 is connected to the internet, the IP address of the device will be printed on the Serial monitor.
  • Copy the IP address.
  • Open the browser and paste the IP address and press
  • A web page will appear, as shown below:

Fig. 30

  • The web page will be updated with new data every 20 seconds, as per the code instructions and we do not even need to refresh the web page for latest event updates due to SSE technology.

Fig. 31

This concludes the tutorial. I hope you found this of some help and also hope to see you soon with a new tutorial on ESP32.

Dictionaries in Python

Hello! Welcome to the next lesson in this Python course. In the last session, we learned about python tracebacks and how to deal with them. A dictionary, like a list, is a collection of items, and we'll look at that in this tutorial as well.

What will you learn?

This tutorial introduces you to the fundamentals of dictionaries in Python and teaches you how to work with dictionary data. After reading this article, you should be able to tell when and how to utilize a dictionary as a data type.

Characteristics of Dictionaries and lists

  • Both can be changed (mutability).
  • A dynamic relationship exists between them. When needed, they're able to expand and contract.
  • Both are nestable. Another list can be contained within one. It is possible to have a dictionary inside of a dictionary. A list can be found in a dictionary, and the other way around.

How do dictionaries differ from lists?

  • Using indexing, list elements can be retrieved by their position in the list.
  • Keys are used to access dictionary elements.

Defining a Dictionary

Data structures that use associative arrays, or dictionaries in Python, are known as dictionaries. Dictionaries store key-value pairs. Every pair of key-values has a corresponding value assigned to it.

With curly bracketed lists of value pairs, you can define a dictionary (). Each key and its corresponding value are separated by a colon (:):

The following is a definition of a dictionary that links a place's name to the MLB team that occupies that location:

The built-in dict() function can also be used to create a dictionary. Key-value pairs should be passed to dict() as an argument. In this case, a list of tuples works well:

The following is an alternate definition for MLB team:

Key values can be supplied as keyword arguments if they are simply strings. MLB team can also be defined in another way.

You can display the contents of a dictionary in the same way you do a list once it has been defined. When presented, the following is what each of the three definitions provided above looks like:

An alphabetical list of words and phrases is shown in the dictionary. When it comes to getting them back, however, none of it matters. There is no numerical index for dictionary elements:

How do we query the Dictionary's Data?

Dictionary elements, of course, need to be accessible in some way. What if you can't find them using an index?

To get a value out of a dictionary, use the square bracketed key ([]):

Python throws an error if you try to use a key that doesn't exist in the dictionary:

It's as simple as setting a new key and value to the existing entries in a dictionary:

In order to make a change to an existing record, you can assign different value to the current key.

A record can be deleted by issuing the del command with the key you want to delete specified:

Comparison of List Indices to Dictionary Keys

For some reason, the interpreter throws a Key Error whenever an undefined key or numeric index are used to retrieve a dictionary's keys.

A mistake has been made in both cases. However, [1] does not represent an index in the second instance.

To utilize an immutable object as a dictionary key, you'll discover later on in this lesson that it's possible. It follows that integers are perfectly acceptable:

The integers enclosed in square brackets [] appear to be indexes. It's only that they don't have anything to do with the dictionary's order. They're being treated as dictionary keys by Python. The same values can be obtained by defining the dictionary in the reverse order:

Despite the similarity in syntax, a dictionary cannot be treated as a list:

As a reminder, Python guarantees that the order of entries in a dictionary will be retained even if access to them is not required. Order matters when it comes to displaying items and iterating over the keys; this is how they'll appear when you see them. Items that are added to a dictionary are inserted in its final paragraph. Even after deletion, the remaining items retain their original order.

Adding to a Dictionary Step by Step

When all the other keys and values are known ahead of time, a dictionary can be defined as shown above by use of curly brackets and a value. It's a difficulty if you want to build a vocabulary on the fly.

Empty curly braces specify an empty dictionary, so that's where you want to start. Adding additional keys and values one at a time is possible.

It's the same as using any other dictionary once the dictionary has been constructed in this manner:

A secondary index or key is required to retrieve the values from the sublist or subdictionary:

Another advantage of dictionaries is that they don't require all of their entries to be of the same type. There are some strings, some integers, a list and a dictionary among the values in person.

The keys and values don't have to be the same.

Integers, floats, and Booleans make up three of the four keys. Although it isn't immediately clear how this could be of benefit, you never know.

Python dictionaries can be used in a variety of ways. As a part of the MLB_team, the baseball team's name can be found in a number of places. There is only one entity that can be used to identify an individual: the person.

There are few restrictions on the types of keys and values that can be stored in dictionaries, making them useful for a wide range of tasks. But there are a few exceptions to this rule. Continue reading for more information!

Access to the Keys to the Dictionary

It is possible in Python to utilize almost any value as key in dictionary. You saw how to use integer, float, and Boolean values as keys like:

It's also possible to use pre-existing objects like types and functions in your code:

Dictionary keys, on the other hand, are subject to a few restrictions.

It is important to note that a single key can only be used in a dictionary once. It is not permitted to use two different keys. So, it doesn't make any sense to have more than one entry for the same key in the dictionary.'

You can't create a new key by introducing a new value to the current dictionary key; rather, you can simply replace the existing value.

Second-occurrence key names take precedence over first-occurrence ones in the dictionary-building process.

It's also important that a key in dictionary is of a type that cannot be changed. In the examples you've already seen, several of the types that are immutable, such as integers, floating points, strings, and Bools, have been used as dictionary keys.

Tuples, by virtue of their immutability, can also be used as dictionary keys:

When an immutable type is needed, a tuple is preferable to an array. One of them is this.)

Lists and dictionaries can't be used as a dictionary key because of the mutability of both:

What does "unhashable" mean in this context?

For a dictionary key to work, an object does not necessarily need to be immutable. It must be possible to send an item via a hash function, which means it must be hashable. For database lookup and comparison, data of any size can be hashed using a hash function to produce a fixed-size result known as a hash (or simply hash).

When an object is hashable, the built-in hash() method delivers its hash value; otherwise, it raises an exception.

As you've learned so far, immutable types and containers (lists/dictionaries) that can be hashed are all built-in. For the time being, you can consider the terms "hashable" and "immutable" to be nearly interchangeable.

 

You'll see changeable objects that are also hashable in upcoming lectures.

Limitations on the use of Dictionary Definitions

Dictionary values, on the other hand, are unrestricted. In fact, there is nothing at all. For example, lists and dictionaries can be mutated and user-defined objects can be created in Python.

In a dictionary, there is no limit to the number of times a single value can appear.

Operators in Python and built-in Functions.

A large number of the built-in and available operators and functions for working with texts, lists, or tuples will be known to you at this point. As well as other dictionaries, several of these are useful.

Using the in and not in operators, for example, you can determine whether or not an operand is a dictionary key.

A key that is not in the dictionary can be avoided by using the in operator and short circuit evaluation:

Dictionary key-value pairs are counted using the len() method.

Which are the Dictionary's built-in functions?

Similarly, to strings and lists, dictionaries include built-in methods that can be used. Although lists and dictionaries share names in some circumstances, it is not always the case. Since various kinds might have methods with the same names, this is totally appropriate when discussing object-oriented programming.)

There are a few approaches that can be used for dictionaries:

d.clear()

Clears elements in the dictionary.

The function d.clear() removes all key-value pairs from the dictionary d:

d.get(<key>[, <default>])

Whether or not a key exists in the dictionary is checked, and the value associated with it is returned.

This method can be used to retrieve the value of any key without having to verify that the key exists.

If a value matching the supplied key (<key>) is discovered in dictionary d, Get (<key>) returns it. If it is unable to locate the appropriate key, this procedure returns 0.

We're going to use -1 instead of None in case <key> could not be located and the <default> argument had been provided.

items(“value”)

The key-values` list in a dictionary is returned by this command.

items(‘value’) will return a tuple`s list containing the values in d. Key value tuples consist of two items: the key and the value.

d.keys()

This function will return a list of the dictionary's keys.

A list of all d keys can be found using d.keys()

d.values()

Values of dictionary are returned in response to this method.

The list of all values in d is returned by d.values()

If d contains any duplicate values, all of those values will be returned:

A "view object," which is a collection of objects, keys, and values, is returned by these functions. The keys and values of a dictionary can be seen through a similar window in a dictionary view object, the keys and values of the dictionary are returned as an array by these methods.

pop(key)

A key is removed from the dictionary and its value is returned if it exists.

pop(key) will remove key and return its related key when <key> is in d:

d.popitem()

In a dictionary, this function removes one key-value pair.

d.popitem() will remove and return any last key pair added to d.

d.update(<obj>)

Merges the dictionary and iterable key-value pairs.

A dictionary can be updated with update(<obj>), which merges all of the items from obj>. For each key in obj>:

If the value pairs from obj do not already exist in d, they are added to d.

Changes to the value of the key in d are made by use of values from <obj>.

The following is an example of how two dictionaries can be combined:

Therefore, its value is set to 200 because b is contained in d1, which is derived from d2's entry for that key. D1 does not include the key d, hence the key-value pair is taken from d2.

Key-value pairs can also be utilized to define a dictionary using the dict() function. As an example, a list of tuples, such as obj:

It is also possible to specify the values to merge in the form of a list of keywords:

Conclusion

Throughout this course, you learned how to read and manipulate the data in a Python dictionary.

Lists and dictionaries are two of Python's most commonly used data structures. It is clear from the comparison that they have many commonalities yet are different in how their elements can be found. Index numbers are used to locate items in lists, and keys are used to locate items in dictionaries.

Therefore, lists and dictionaries are appropriate for different circumstances. You should now be able to tell whether one or the other is the best option in a given case.

Python sets are the next topic you'll study. Unlike lists and dictionaries, the set is not a simple collection of elements.

Python Traceback

Welcome to the tenth lesson of our python course. In the previous tutorial, you learned about syntax errors in Python, and in this lesson, we will look at one more error notice that is given by Python when there is an error in your code. So, without further ado, let's get started.

Any time an exception is thrown in your code, Python shows you the stack trace. If you don't know what the traceback output is showing you, it can be a little overwhelming. Python's traceback, on the other hand, provides a goldmine of information that can assist you in figuring out why an exception was triggered in your code and fix it. It's essential to learn how to use Python traceback to become a better coder.

After completing this session, you will be able to do the following:

  • Interpret the next error message you come across.
  • Find out how to identify some of the most typical repercussions
  • Successfully log a traceback while addressing the exception.

Python Traceback: What Is It?

This is a list of all the function calls you made at a certain time in your code. Stack traces, stack tracebacks, backtraces, and maybe other terms refer to tracebacks. Traceback is the term used in Python. Python will report the current traceback if your program throws an exception, so you can figure out what went wrong. The following is an example of how this may play out:

Someone is passed to greet() as an argument. But in greet(), the name of the variable is not used. In the print() call, the word someon was used instead. On startup, you'll get a traceback like this:

All of the details you need to investigate the problem can be found in this traceback output. What sort of exception was thrown and what information about it can be found in the last line of the traceback report? Using the traceback, it is possible to identify the code that caused the exception to be raised. When an exception like the one seen above occurs, it implies that a reference to an undefined name (variable, function, or class) is being used. Somebody is the person being referred to in this instance.

Here, the final line gives you enough information to figure out how to fix the issue. You may find the correct code by searching for the misspelled name "someone" in the source code. However, it is common for your code to be far more complex.

How Do You Read Python Traceback?

When you're attempting to figure out what caused an exception to be thrown in your code, the Python traceback provides a wealth of information. Throughout this part, you'll learn about the many pieces of information that can be found in a traceback.

Overview of Python Tracebacks

It is critical to pay attention to each section of a Python traceback. As shown in the picture below, there are several different components:

Using Python, it's better to start at the bottom and work your way up the traceback

  • The error message appears in the blue box at the end of the traceback. It includes the name of the exception that was thrown.
  • The error message appears in the green box to the right of the exception name. In most cases, this message provides useful information about the cause of the exception.
  • Box in yellow: The function calls that have been made most recently to least recently can be seen farther along with the traceback. Each of these phone calls is represented by a two-line entry. For example, the file name, line number, and module identifiers are all included in each call's initial line.
  • Red underline: This is the actual code that was run on the second line of these calls.

For example, traceback output differs between command-line execution and the REPL's execution of code. The same code from the previous section was run in a REPL and the traceback output is shown below:

You'll see "<stdin>" in place of filenames. This makes it reasonable because you entered the code using normal input. In addition, the traceback does not indicate the executed lines of code. You may notice a big difference in the look of a Python traceback compared to other programming languages' stack traces. Other languages often begin at the top and work their way down the list, going from the most recent calls to the oldest ones, in that order.

A Step-by-Step Guide to Retracing Your Steps

You can get a better idea of what information the traceback will give you by going through some of the traceback output. In the following instances, the traceback information provided by Python is illustrated using the code below:

who to greet receives a value, a person, and either return it or prompts for a value to return instead. Then welcome() takes a name to be greeted, a person and an optional greeting value, and calls print() (). This function is also invoked with the passed-in value of "someone."

Finally, greet many() calls greet after iterating through the list of persons (). If welcome() returns an error, then a simple backup greeting is printed instead of the original greeting. There are no issues in this code that would cause an exception to be thrown if the correct input is provided. You'll see the following traceback if you call greet() at the bottom of greetings.py with a keyword argument that it doesn't expect (for example greet('Chad', greting='Yo’)).

If you're dealing with a Python traceback, you should always start by tracing backward. The traceback shows that the exception was a TypeError at the end of the last line. Everything after the colon in the message after the exception type gives you a wealth of information. It informs you that a keyword argument was passed to greet() that it wasn't expecting. Greting is the name of the unknown argument. The line that caused the exception can be seen as you move up the tree. We inserted the greet() code at the bottom of greetings.py in this example.

There is a second line of information that tells you exactly where the code is, what module it's in, and how you may get to it. module> indicates that this is the file that is being executed in this situation since our code doesn't use any other Python modules. Using a new file and different input, you can see where the traceback is leading you. Remove the faulty greet() function from greetings.py and add this file to your directory: greetings.py

You've created a new Python file, greetings.py, which imports greetings.py and uses greet(). If you now run example.py, you'll see what I mean:

This time, a TypeError is thrown, but the message it contains is less instructive. It was expecting to deal with a string but instead received an integer at some point in the program's code. You may see the code that was performed by moving up a few levels. The code's location and filename are then provided. Greet is the function name instead of module> this time around ().

The incorrect greet() call is now passed to the next line of code to be executed. When an exception is thrown, it may be caught by another piece of code, which will then throw an exception of its own. Even if there are many exception tracebacks, Python will always print the traceback of the most recently raised one first.

Here's an example to help clear things up. The bottom of welcomes should include a call to greet many(). py:

All three people should receive printed greetings as a result of this. To see an example of several tracebacks being output, run this code.

In the output above, look for the highlighted line that begins with the phrase "During handling." This line appears in the middle of every traceback. Its message is crystal clear: another exception was produced while your code was trying to handle the prior exception.

Previously, when you called greet() with an integer, you saw the same problem. We can assume the same outcome because we added a 1 to the list of individuals to greet. The welcome() call is redirected to a try-and-except block in the greet many() method. If greet() throws an exception, greet many() will output a generic welcome.

Greetings.py's pertinent paragraph is reprinted here.

As a result, greet many() attempts to produce a simple greeting when greet() fails due to a TypeError caused by an invalid integer input. In this case, the code results in a similar exception. However, it's still attempting to combine two different types of data. Traceback output can help you identify the root cause of an exception by displaying all of the possible causes. When you view the last exception and its traceback, you may not be able to figure out what went wrong. Moving up to the prior exceptions will usually give you a clearer grasp of the underlying problem in these situations as well.

The Most Common Python Tracebacks

When your program throws an exception, it's helpful to know how to read a Python traceback, but it's also helpful to know some of the most typical tracebacks. Listed here are some of the most typical exceptions you'll encounter, along with the reasons they're raised and what they mean, and how to track them down.

AttributeError

If you attempt to access an attribute on an object that does not have that attribute declared, you will receive an AttributeError exception. When this exception is thrown, according to the Python manual:

AttributeErrors have an error message indicating that a certain object type, in this example an int, does not have the attribute accessed, an attribute. If you see the AttributeError in the error message, it will assist you to identify the attribute you attempted to access and where you need to go to fix the problem.

If you get this exception, it's likely because you're working with an object that isn't what you expected.

ImportError

An ImportError is thrown when an import statement fails. The ModuleNotFoundError exception or a subclass thereof will be thrown if you try to import anything from a module that does not exist in the module you are trying to import it from. When this exception is thrown, according to the Python manual:

The ModuleNotFoundError occurs when an attempt is made to import a module that does not exist, like in the above example. An ImportError is thrown if you try to import something that doesn't exist from a module that does exist. Both asdf and asdf can't be imported because of the error message lines at the bottom of the tracebacks.

NameError

What causes the NameError to be raised is the fact that you've used a name that hasn't been specified in your code. When this exception is thrown, according to the Python manual:

Greet() in the following code accepts a person as a parameter. Persn, on the other hand, is the incorrect spelling of this parameter in the function itself:

Your missing name can be found in the NameError traceback error message. In the example above, a misspelled variable or parameter was passed into the function.

If you misspelled the parameter, you'll get a NameError:

In this situation, it may appear as if you've done nothing wrong at all. A clean traceback can be seen after the last line of code was executed. Look through your code to see where the person variable is used and defined if you find yourself in this circumstance. An error in the parameter name can be easily seen in this example.

How Do You Log a Traceback?

Making a decision after receiving a Python exception and associated traceback can be difficult. It's always a good idea to address your code first, however, in certain cases, the problem is caused by inaccurate or unexpected user input. There are instances when silence or hiding an exception by logging the traceback and doing anything else is more appropriate than providing for those situations in your code.

The following code needs to suppress some Python tracebacks in the real world. The requests library is used in this example.

This code works perfectly. A command-line argument is required to launch this script, which will call the URL and print its HTTP status code and response content. Even if the answer contained an HTTP error status, it still works:

Your script may be unable to obtain a URL because it does not exist or the host server is unavailable. Uncaught ConnectionError exceptions and tracebacks will now be raised and printed in those circumstances.

Many other exceptions may be raised before the ConnectionError is raised by the requests themselves in the Python traceback. Line 5 of urlcaller.py is where the trouble began, as you can see in the final exceptions traceback.

For example, if you put the offending line in a try and except block, you can catch the proper error and continue to work:

Instead of using a try/except block, the above code uses an else clause. To learn more about this feature of Python, see the section on else clauses in Python Exceptions: Introductory remark

You'll now see a -1 for the status code and the text "Connection Error:" written when the script is run with a URL that raises a ConnectionError.

This is fantastic. But in most real-world systems, you want to log the traceback rather than just mute the exception and its traceback. Tracebacks, help you figure out what's going wrong with your programs. It is possible to log the traceback in the script by importing the logging package, creating an exception, and calling.exception() on the logger in the except portion of the try and except block. In the end, your script should look like this:

Conclusion

Using Python traceback is a wonderful way to find out what is wrong with your code. These tracebacks may appear frightening at first, but if you understand what they're trying to tell you, they can be really useful. You may get the most out of tracebacks if you go through a few of them line by line. When you execute your program and get a Python traceback, you have an opportunity to make improvements to your code. Python does its best to assist you in this way.

Knowing how to decipher a Python traceback opens the door to learning about other diagnostic tools and approaches that can help you figure out what's wrong with your code. Tracebacks can be seen and worked with using Python's built-in traceback module. When you want to gain more from the traceback output, the traceback module can be useful. It's also a good idea to brush up on your Python debugging skills. In light of this, we'll take a look at dictionaries in Python in the next tutorial.

Python Syntax Errors Continuation

Welcome to chapter 9 of our python tutorial. In the previous chapter, we looked at frequent examples of invalid Python syntax and learned how to fix them. Up to this point, you are well aware of errors that may occur in your Python program and how you can solve them easily and quickly. Therefore, in this tutorial, we will look at a few more causes of syntax errors and zero-error divisions.

Mistaking Dictionary Syntax

As you learned before, omitting the comma from a dictionary element can result in a syntax error. In Python dictionaries, the equals symbol (=) is used instead of a colon to separate key and value pairs.

This error message is once again useless. In this case, the repeated line and caret come in handy! All signs lead to the main antagonist. In addition, if you mistakenly believe that defining a dictionary is the same as calling dict(), you'll get this error. A colon could be used in place of the equals sign to correct this. It's also possible to use dict() instead:

If the dict() syntax is more useful, you can use it to define the dictionary.

Using the Wrong Indentation

Syntax Error has two subclasses that deal especially with indentation issues:

  • Indentation Error
  • Tab Error

Python employs whitespace instead of curly brackets to represent blocks of code in other computer languages. Python, on the other hand, assumes that your code's whitespace will behave predictably. If a line in a code block has an incorrect number of spaces, an Indentation Error will be thrown:

A quick inspection may not reveal that line 5 is indented by two spaces. It should be four spaces over from the for-loop expression. Fortunately, Python can detect this and instantly inform you of the problem. However, there's some gray area here as well. Do you want the print("done") to appear before, or after the block with a for-loop? if you run the following code, you'll get the following error message;

It appears like a Syntax Error traceback, but it is an Indentation Error. Error messages are also highly helpful. There is a discrepancy in the line's indentation level compared to other indentation levels. Print('done') is an alternative that is indented by two spaces, but Python can't identify any additional lines of code that match this amount of indentation. To resolve the problem quickly, make sure the code is aligned with the anticipated indentation level. Tab Error is another type of Syntax Error, which is the result of indentation using tabs or spaces, while the rest of the file has either spaces or tabs instead. You may not see this until Python does!

All lines may be indented at the same level when the tab width is the same as the number of spaces used in each indentation criterion. For example: Using tabs instead of spaces when indenting a line will cause Python to raise an error message.

Instead of four spaces, a tab denotes indentation on line 5. Depending on your system, this code block may appear correct to you, or it may appear incorrect to you.

Python, on the other hand, will be alerted to the problem right away. As a way to view whatever Python tells us is wrong; it might be beneficial to view an example of what the code looks like under various tab-width settings:

The three examples above show a considerable difference in how they are shown. Even though most of the code utilizes four spaces per level of indentation, Line 5 only uses one tab in all three circumstances. The width of the tab changes when the tab width is set:

The print statement will appear to be outside the for loop if the tab width is set to 4. After the loop, the console will display the word 'done. If the tab width is set to 8, the print statement will appear to be inside the for loop (which is common on many computers). After each number, the console will display the word 'done.' Using the print statement with a tab width of 3 appears strange too. In this case, there is no indentation level associated with line 5.

There is a traceback and error message when you run this code.

Instead of a Syntax Error, there's a Tab Error. A useful error message from Python identifies the problematic line. It's easy to see that the file contains a mix of tabs and spaces for indentation. There is no need to utilize both tabs and spaces in the same Python code file as a workaround. It would be better if we replaced the tab with four spaces, which would output "done" when the for loop completes.

Function Definition and Invocation

When defining or calling functions in Python, you may encounter syntax errors. If at the end of a function definition, you place a semicolon instead of a colon, you'll get a Syntax Error.

With the caret pointing directly at the problematic character, this traceback is helpful. The semicolon can be replaced by a colon in Python to correct this erroneous syntax. As an additional requirement, keyword arguments must be placed in the correct sequence in both function definitions and function calls. Positional arguments are always followed by keyword arguments. A Syntax Error will be thrown if this ordering is not followed:

Again, the error notice makes it quite clear what went wrong with the line in question.

Updating Your Python Software

When upgrading from one version of Python to another, it's not uncommon for previously working code to malfunction. This is the result of standardized grammatical adjustments. Most notable is the print statement, which was a keyword in Python 2 but was converted to a built-in function in Python 3.

The Syntax Error's error message shines in this case! It also informs you exactly how to fix a print call that has missing parenthesis. Additionally, it's possible to come across syntax that is correct in one Python version but is not correct in the one you're working in. The f-string syntax, for example, does not exist in Python before 3.6:

Before Python 3.6, the interpreter had no concept of the f-string syntax and would simply produce an error stating that the syntax was invalid. Python version 2.7 was used in this example, and while the code seemed to be correct, it was running on an older version. Double-check the Python version you're using if you're unsure.

The new Syntax Warning is also included in Python 3.8. This alert will appear if the syntax is correct, but there is something fishy about it. A comma would be needed between two tuples in a list as an illustration of this. Because a tuple cannot be called, this code would trigger a Type Error in earlier versions of Python.

The Python interpreter interprets your attempt to use a tuple as a function, which results in this Type Error.

This code still raises a Type Error in Python 3.8, but now you'll see a Syntax Warning that tells you how to solve it.

New Syntax Warning even includes a clue ("maybe you skipped a comma?") to put you in the right way!

What are ZeroDivisionErrors?

It's possible to get a ZeroDivisionError when you divide by zero. In mathematics, an integer split by zero yields an infinite number. Infinite numbers are physically impossible to write down. A ZeroDivisionError: division by zero "is thrown by Python if the result is infinity. It is possible to divide two numbers by one another. A division procedure is all about dividing an int or float value into equal parts or groups. It's harder to interpret a number when it's broken into zeroes. When a number is divided by zero, the outcome is unclear.

Infinity is the result of dividing a number by zero. Since an infinite number cannot be expressed in a concrete form, Python cannot handle it. A "ZeroDivisionError: division by zero" is thrown in this case by Python. The following is an example of an error that would be thrown if it occurred.

Errors of varying severity

Python's Zero Division Error can be thrown in many different ways. The following is a list of ZeroDivisionError's various forms.

What is the cause of the problem?

Zero-division errors occur when numbers are divided by zero or when they are modulo zero. A non-zero numeric number should be used as the denominator in the division operation. If the denominator is 0, the interpreter throws the exception ZeroDivisionError. It is illogical to divide a number into units of zero. So, you end up with an unrepresentable, infinitely large integer in Python. Python throws an exception because of the "ZeroDivisionError: integer division or modulo by zero" error. An integer, long, float, or complex number can all be affected by this issue.

How can we replicate this problem?

It is necessary to divide an integer by a non-zero number. ZeroDivisionError is thrown by the Python interpreter when a number is divided by zero in a program. A division error will occur if the numerator is set to 0.

The code that follows demonstrates how to get the error to occur again.

x = 8

y = 0

z = x / y

print z

Results:

Solution 1

In Python, zero cannot be divided by anything. The denominator must be nonzero before performing any division or modulo operations. When the denominator is 0, the code below explains how to handle it.

x = 8

y = 0

z = x / y

print z

Results:

Solution 2

Denominator values can be zero in some circumstances when the program is uncertain about the denominator value. Handle the ZeroDivisionError if it occurs in this situation. Using the code below, you can see how to handle a ZeroDivisionError.

try:

x = 8

y = 0

z = x / y

except ZeroDivisionError:

z = 0

print z

Output:

Solution 3

The output of a division operation can be set to zero if the numerator is 0 in the program. This may not be correct in terms of mathematics. Real-time calculations will no longer have this problem if the division is set to zero. Here's how to establish the zero for the division operation using this code.

x = 8

y = 0

if y == 0:

z = 0

else:

z = x /y

print z

Output:

At this point, you might have met or heard the term debug somewhere during your programming journey.

What is debugging?

As a multi-step process in computer programming and engineering, debugging begins with the discovery of an issue before being followed by an attempt to isolate the problem's cause and either resolve it directly or find an alternate solution. Finally, a patch or workaround must be tested to see if it fixes the problem. The debugging process has two stages: the discovery of a bug and the ability to replicate it. It is necessary to include debugging in every stage of software development and testing.

Debugging in hardware development often focuses on finding hardware components that are incorrectly installed or configured. A JTAG connection test, for example, could be used by an engineer to look for bad connections on a computer chip.

Conclusion

You've seen how the Syntax Error traceback provides you with information in this tutorial. Several frequent Python syntax problems have been demonstrated, along with solutions. In addition to speeding up your work, this will make you a better code reviewer because you will be able to do more. It is highly recommended that you use an editor that understands Python syntax and provides feedback as you write code. To make sure you don't write any bad Python code, look at the examples from this course in an IDE before you start writing your own. When studying Python, a syntax error can be frustrating, but now you know how to comprehend traceback warnings and what sort of erroneous Python syntax you may encounter. You'll be more prepared for the next time you encounter a syntax error!

Up Down Counter without Microcontroller

Hello geeks, welcome to our new project. In this project, we are going to make a very interesting project. I think most of us have seen the scoreboards in sports, after looking at that, have you ever wondered about the working of it. Therefore, this time, we will be making something like that only with some extra features. So basically that score board is nothing but a counter which counts the scores. Most of the geeks who have an electronics background or have ever studied digital electronics must have heard about the counter.

Here, in this project, we are going to make an Up-Down counter. A simple counter counts in increasing or decreasing order but the Up-Down counter counts in increasing and decreasing order, both depending upon the input it has given.

But I am having an interesting question about the counter. Let suppose if the counter is counting in increasing order then up to which value, it will count because it can not count to infinite which means it has to reset after some certain value, and I believe that you must be having the same doubt as well. Basically every counter resets itself after a certain value and that value depends upon the bits of a counter.

Let suppose, we have a 8 bit counter which means it will count a maximum of up to 255 after which, it will reset to 0. So the size of the counter depends upon the bits of the counter.

So, in this project, we are going to make a counter which will count from 0 to 9 after which it will again reset to 0.

Software to install

We will make this project in the simulation first, for that we will use a simulation software which is Proteus.

Proteus is a simulation software for electronics based circuits. In this software we can make different types of electronic circuits and we can run the simulation and can monitor the working of that project in real-time only.

And it is a good practice also while making any new project. First of all, we should make a simulation of that project so that we can debug any issues without damaging any real components.

Proteus has a very huge database of all types of electronics components pre-installed.

Components Required

In this project, we will use the following components:

  • 7 Segment LED display
  • Push buttons
  • Resistors
  • 74LS192 (BCD/DECADE UP/DOWN COUNTER)
  • 7447 BCD to 7-Segment Decoders/Drivers

Components details

7 Segment Led display

  • It is an LED display module in which there are seven LEDs arranged in the rectangular form on which we can display single digit numbers from 0-9 and some alphabets as well.
  • It has two types, one is common ground and another is common Vcc.
  • There are 7 different pins for each LEDs and one common pin, this pin can be common ground or common Vcc depending upon type of the display.
  • The pins on the display are noted as a,b,c,d,e,f, and `g.
  • Common ground is also known as Common cathode, and common Vcc is also known as Common anode .
  • In Common cathode type display, the LEDs will glow when LEDs pins are connected to logic HIGH.
  • In Common anode type display, the LEDs will glow when the LEDs pins are connected to logic LOW.
  • As they are simple LED’s so while using them in the circuit, it is mandatory to use some protection resistors with each of them if we are using Common ground type display and single resistor with the Common Vcc pin if we are using the Common Vcc type display.
  • For the counter, we will follow the truth table of display for showing the numbers.

Push buttons

  • Here, we have used a simple momentary push button for setting the counter in UP counting or in DOWN counting.
  • There are two pins in the push button.
  • As we will use the push buttons in active low condition which means one side will be connected to ground and other terminal will be connected to the Arduino.
  • So when we press the push button, it will close the circuit and set the pin.
  • While using any push button, it is mandatory to use a pull-up or pull-down resistor with it, otherwise there will be some glitches in the operation.
  • Because when the button is released, the circuit will be opened and if there is no pull-up or pull-down connected to the other pin of the push button, then that pin will be in floating state and it will give any random voltage, which will create an issue.
  • In this project, we have used the pull-up resistor so that when the push button is released, the pin state will be in logic HIGH state.

BCD/Decade Up-Down counter (74LS192)

  • 74LS192 is an Up/Down BCD decade counter IC. It is developed by Motorola.
  • This is the main IC which is used in this project for counting purposes.
  • It is one the simplest IC for Up/Down counters. It has two different input pins for selecting the Up counter or Down counter mode.
  • It is a 16 pin TTL based IC. Operating voltage of the IC is 5v.
  • And as per the data sheet for selecting the mode of counter there are basically four pins used and those are MR, PL, CPU, CpD.
  • For counting, the MR pin should be logic LOW and the PL pin should be in logic HIGH.
  • To start the counting in increasing order or upward, the down counter input pin(CpD) should be at logic HIGH state and the up-counter input pin (CpU) should send a pulse from logic LOW to logic HIGH after this sequence the IC will count upwards.
  • We have to follow the same sequence for counting in decreasing order or downward, the up counter input should be at logic HIGH state and the down counter input pin (CpD) should send a pulse from logic LOW to logic HIGH after this sequence the IC will count downwards.

Truth Table for Modes

7447 BCD to 7-Segment Decoders/Drivers

  • This IC is used in this project for controlling the 7-segment LED display.
  • This is an active low output IC which means we can use its common anode LED display only.
  • It basically converts the BCD number to decimal numbers on the 7-segment LED display.
  • It has 4 input pins for reading the BCD input and depending upon which it will set the output pins for the 7 segment display.
  • To set input pins depending upon the required output we will follow its truth table.

Project overview

In this project, we will use two push buttons for controlling the counter as an Up counter or Down counter. The outputs from the push buttons will work as input for the BCD/DECADE UP/DOWN COUNTER IC. When we press the push button, there will be a change in the signal pin of the IC and according to the truth table when the signal changes from logic HIGH to LOW and the other input clock pin is at HIGH state then it will change the output count value depending upon the selected pin.

Which means if we push the Up counter push button, it will send a pulse to CpU pin of the IC, afterwards it will process as the increment in the output value, so it will increase the current output value by one. Similarly, for the Down counter push button, when we press the button, it will send a pulse to the CpD pin of the IC, thereafter it will process as the decrement in the output value so it will decrease the current output value by one.

And the outputs of the BCD/DECADE UP/DOWN COUNTER IC will work as the input for the BCD to 7-Segment Decoder. And the output pins of the BCD to 7-Segment Decoder will be connected to the 7 segment LED with some protection resistor to prevent them from damaging.

The 7-Segment Led display will glow the LEDs depending upon the output values on the BCD to 7-Segment Decoder/Driver.

Now we know the workflow of our counter.

So let‘s move to the circuit of the counter.

Circuit diagram and working

For making the project, we will be using the Proteus simulation software.

  • First, start the new project in the Proteus and import all the required components into the workplace.
  • After importing all the components in the workplace, let’s start connecting those.
  • First of all, we will connect the push button with the BCD counter IC.
  • As we know, the push button has to be connected in pull mode so we will connect a resistor with each of the push buttons and another terminal with the BCD counter IC.
  • Another terminal of the Up counter push button will be connected to the ‘UP’ pin of the BCD counter IC and the Down counter push-button terminal will be connected to the ‘DN’ pin of the counter IC and other pins like MR will be connected to the Vcc and PL pin will be connected to the ground.
  • All the connections are made as per the datasheet of the IC.
  • After this, we will connect the output pins of the BCD counter to the input pins of 7 segment LED driver IC. While connecting the pins of the IC, make sure they are connected in the correct sequence otherwise it will not display the correct value on the LED display.
  • Now we will connect the protection resistors and the 7-segment LED display with the output of the 7 segment LED driver IC.
  • After connecting them our circuit will be ready.
  • Before testing it, do not forget to re-verify the connections.

Result and test

Now we have our circuit ready, it is time to test it.

  • Start the simulation by clicking on the play button in the Porteus simulation.
  • First we will check for the Up counter.
  • Press the Up counter push button. When we press the Up counter push button then the value on the 7 segment display will increase and if we continuously press it then the counter will go up to 9, afterwards it will reset to 0.
  • Now check the Down counter. Press the Down counter push button, then the value on the 7 segment display will decrease and if we continuously press it then it will reach to 0 and thereafter it will start from the 9 again and will be decreased to 0.

Conclusion

I hope we have covered all the aspects of this project. And I think it will be a very useful learning project as well. Now if we see any scoreboard, immediately we will be knowing the electronics behind it. I hope you have enjoyed reading this project. Please let us know in the comment section if you have faced any issues while making this project.

Thanks for reading this article. See you in the next project.

Role of Cloud Computing in IoT

Hi Everyone! Glad to have you on board. Thank you for clicking this read. In this post today, I’ll cover the Role of Cloud Computing in IoT.

Digital transformation has gained momentum in the past few years, the reason traditional technologies are becoming obsolete over time. Now organizations are incorporating modern technologies into their business model at an accelerated pace. These technologies produce the influx of data and at times it becomes very difficult to process and handle that data, thanks to cloud computing that has made the handling of data easy and effective. You don’t need traditional data centers anymore to store and process information. Everything will be taken care of remotely in the cloud with data centers.

Not to mention, this is the era of automation. Companies strive to accommodate automation in the activities of their business so they can achieve maximum output without the interference of humans. And this trend complements the arrival of IoT (internet of things). The IoT is nothing but a data source and cloud computing is used to store and process that data. We’ll touch on this further in this article.

Scroll on.

Role of Cloud Computing in IoT

Both cloud computing and IoT are separate terms but can work together for better efficiency and productivity. The former is an architecture that offers on-demand computing resources to the end-users to process, store and handle data over the internet while the latter is a technology that acts as a data source from where data is produced. In simple words, IoT (internet of things) is a network of ‘things’ like physical objects, humans, and machines connected and collect and exchange data in real-time through embedded sensors. For instance, a human with a heart monitoring device and a car with sensors that send an instant alert to the driver for any danger fall under the umbrella of IoT.

According to Statista, “the total Internet of Things (IoT) connected devices worldwide is expected to reach 30.9 billion units by 2025, compared to 13.8 billion units that were expected in 2021.”

This projects that billions of devices connected will produce enormous data which makes cloud computing a major part of the IoT technology. Both IoT and cloud computing are inseparable and make an effective integration. In the following, we’ll stretch on this further.

How Cloud Computing and IoT Work Together

As touched on earlier, IoT devices are connected with each other and can produce a flood of data that needs to be handled and processed somewhere. Cloud computing serves that purpose. If IoT devices are connected with traditional data centers, it takes a capital investment to install, manage, scale and upgrade machines on-premises to handle that data. While with cloud computing, virtual infrastructure is created that allows the developers to access and handle computing resources remotely without having to worry about the management of on-site IT infrastructure.

There are cloud service providers that offer cloud computing services to end-users. The common service providers include AWS (Amazon Web Services), Google Cloud, and Alibaba Cloud. The computing capabilities they offer are virtually endless that can effectively process and store the information produced by IoT devices. These providers commonly offer pay-as-you-go service which means you can scale up or scale down the resources as per the requirement of connected IoT devices.

Advantages of Cloud Computing with IoT

Cloud computing and IoT are not the same but they complement each other. The following are the main advantages of combining IoT data with cloud computing infrastructure.

1: Cloud Computing Secures IoT Data

Security is the top priority for any organization to run its business activities successfully. And when companies use cloud computing to their advantage, it gives them a sense of security because your data is processed and stored in remote data centers managed globally. The cloud service providers have a network of servers located at multiple locations which means your data is not stored at one data center, instead, the system creates files of your data at multiple locations in different data centers. If one server goes down, you can get a copy of data from another server.

Whether you pick private cloud or public cloud is another parameter to guarantee the security of your sensitive data. This is how it works – companies use the public cloud for storing a large amount of data and the private cloud to process sensitive data locally. If you want to keep your IoT safe and secure, you can pick a private cloud for this purpose.

2: Cloud Offers Mobility to IoT Data

Cloud makes IoT data easily accessible which means you can remotely access information produced by IoT devices from anywhere in the world. Quick and on-spot data access is crucial when it comes to monitoring information gained by connected IoT devices. In IoT technology, we often get continuous readings from the attached sensors and that readings need to be stored and monitored quickly to make instant decisions.

To stretch this further, you can even use edge computing (which is the extension of cloud computing) to your advantage for handling IoT data. The difference between edge computing and cloud computing is the time it takes to process the information. In edge computing, data doesn’t go to the cloud, instead, it goes to the edge device installed near the data source which takes less time to process it.

3: Cloud Model is Cost-Effective for IoT technology

IoT-based businesses often pick cloud computing to speed up their business operations. Since on-site IT infrastructure is costly and requires up-front payment for the management of traditional data centers. While cloud models remove the hassle of hardware maintenance and give you the flexibility to pick the pricing package best suitable for your business needs.

Common Questions

The following are the frequently asked questions when it comes to integrating IoT with cloud computing.

Is Cloud Computing Necessary for IoT?

Technically speaking the answer is no and yes. NO, if you want to locally process your data in on-site IT infrastructure. YES, if you want to leverage the cloud since it’s preferable to pick the cloud model when there is a flood of information to be handled and stored.

How does cloud computing work with IoT?

There are four different cloud models named public cloud, private cloud, hybrid cloud, and community cloud. You can pick any model based on your business needs and requirements. It all depends on the type of data you want to manage and store. For sensitive information to manage, you can prefer the private cloud model, and for non-sensitive, you can opt for the public cloud model. A hybrid model is another option that gives you the option to integrate both private and public clouds into your business.

How do I know if the cloud is right for me?

It depends on the requirement of IT infrastructure. Do your current IT requirements constantly change over the year? Do local data centers cost you more? What is the type of data? The number of connected IoT devices? These are the main questions you need to ask if you need a cloud model or not. This cloud architecture is mainly suited for you if want cost-effective and reliable solutions to handle enormous data.

 

Conclusion

Technology is evolving and every business uniquely works to keep up with the pace of this technology.

Billions of devices are expected to be connected through IoT technology, the information produced by these devices is difficult to handle if you apply the traditional approach to handle and process that information.

As the demand to handle and manage a data grows, organizations will integrate cloud computing into their business models.

And on-demand availability with cloud computing is what makes this model more attractive since this way you can monitor and access your information remotely from anywhere in the world. This trend will complement the usage of more IoT devices in the cloud computing model.

It is safe to say that cloud computing is expected to open new and flexible opportunities for IoT-based businesses to handle, store and process a bulk of data.

That’s all for today. Hope you loved reading this article. If you’re unsure or have any questions, you can ask me in the section below. I’d love to help you the best way I can. Feel free to share your experience with the IoT and cloud computing integration. Thank you for reading this article.

How Do You Pick the Best 3D Printing Company?

Product designers nowadays have access to various technologies for creating multiple prototypes. These include traditional methods such as pen-and-paper sketching and cutting foam blocks, as well as more modern technologies such as 3D printing and CNC machining service.

However, today we will focus on the additive manufacturing technique and what you should look for during your search. Numerous businesses embrace the technology by delegating tasks to professional 3D printing services.

In the globally competitive environment, adding a supply partner to the company's value chain is the way to go because the technology is capital-intensive to implement. To help more businesses adopt the technology, we've created a simple guide to help them select the best 3D printing solutions partners.

Available technologies

Working with a 3D printing provider gives you direct exposure to a broad scope of 3D printing technologies. A 3D printing service can handle a wide range of industrial projects thanks to its extensive capabilities. As a result, one of the essential criteria in selecting the best 3D printing service for you is the wide variety of current technologies.

The service provider has significant expert knowledge in all technologies due to their broader technology scope. As a result, they can recommend and help consumers with the technology that will help them get the most out of their initiatives.

Material 

Choosing a 3D printing service isn't complete without considering the materials. Material considerations play an essential role in decision-making. Not all materials can be utilized successfully with all techniques.

Only some technologies can efficiently use solid materials. As a result, consider material availability when selecting a 3D printing service. The 3D printing service you hire should be experienced in printing with the required material.

Knowledge in design

The importance of design in 3D printing is frequently overlooked. While any design can be 3D printed, some can't be done well. Methods for additive manufacturing precepts should be used when designing for 3D printing.

A service agency must be aware of the difference and, as a result, strongly recommend or endorse design changes that are compatible with 3D printing. This compatibility can help customers save time, money, and materials while improving part effectiveness, longevity, and trustworthiness. As a result, choose a 3D printing service that specializes in design.

3D Printing Services for a Specific Market 

While contacting a 3D printing service with a wider variety of technologies is usually a good idea, it is not always the best option. Numerous service providers specialize in a specific area of expertise. This is commonly seen in medical and healthcare settings.

Medical implementations of 3D printing, as well as some aerospace implementations, must meet specific rules and regs. Service bureaus with FDA or ISO-approved amenities, technologies, materials, and procedures should be chosen for particular applications.

Long-Term vs. One-Time 

If you're working on a one-off 3D printing project, the 3D printing service you choose won't have an impact on your long-term work, product, or public image.

However, if you want to integrate 3D printing or outsource long-term work, finding the right 3D printing provider should be a priority.

What Benefits Does 3D Printing Provide?

3D printing is one of the most promising technologies in recent breakthroughs. One of the most inherent benefits of 3D printing is additive innovation; it opens up an entirely new way of creating products and provides numerous benefits over traditional fabrication techniques.

Nowadays, more businesses across many industrial sectors adopt 3D printing as a viable alternative to subtractive manufacturing (acquiring machined parts online) and injection molding. We'll look at the benefits of 3D printing and how you can use this production method to benefit your company. Is it worthwhile to use 3D printing for your project?

Affordability

One of the best aspects of 3d printing is the reduced labor costs. Operating costs heavily influence the quantity of money spent on building a structure. Whenever it comes to traditional manufacturing, production costs are incredibly high, and skilled machine operators are required. In 3D printers, however, all that is needed is for an operator to press a button, and the printer's automated process will take care of the rest. Furthermore, 3D printing is comparable to both small-scale and large-scale manufacturing.

Competitive advantage 

Due to the speed and lower expenses of 3D printing, item life cycles are decreased. Organizations can improve and upgrade an item permitting them to convey better things in a more limited time.

3D printing permits the actual show of another item to clients and financial backers instead of passing it on to their minds, accordingly lessening the gamble of data being misconstrued or lost during communication.

It also enables low-cost test marketing, allowing prospective clients to provide feedback on a physical item without the risk of high upfront prototyping costs.

Quality

Traditional production techniques can lead to shoddy designs and, as a result, shoddy prototypes. Consider baking a cake where all of the ingredients are blended and mixed before being baked. If the ingredients were not extensively combined, the cake would have air bubbles or fail to bake thoroughly. The same thing can happen when using subtractive or injection techniques; quality isn't always guaranteed.

Because of the nature of 3D printing, it is possible to assemble a part or product step by step, resulting in improved design and higher quality parts/products.

Customization and creative design liberty 

Traditional manufacturing techniques are efficient at making dozens and dozens of identical items, but the models are devoid of life and repetitive.

While 3D printing allows designers to create unique models with limitless personalization, it also makes it easy to include unique features that customers demand. Meaning you can get precisely what you want after handing over your 3d printing quote to a form well-versed in this sector.

The majority of additive manufacturing's constraints relate to how to generate a print quickly enough to eliminate the need for support. As a result, developers are free to create intricate geometries and concepts.

Final Words

3D printing is a cutting-edge technology that is preferable, cost-effective, speedier, more viable, adaptable, and environmentally friendly than previous generations. We currently reside in a fast-paced universe where everything needs to be done quickly, and 3D printing technology can help us turn our ideas to life; this is a massive advantage in the printing world.

Syed Zain Nasir

I am Syed Zain Nasir, the founder of <a href=https://www.TheEngineeringProjects.com/>The Engineering Projects</a> (TEP). I am a programmer since 2009 before that I just search things, make small projects and now I am sharing my knowledge through this platform.I also work as a freelancer and did many projects related to programming and electrical circuitry. <a href=https://plus.google.com/+SyedZainNasir/>My Google Profile+</a>

Share
Published by
Syed Zain Nasir