Internet of Things is a system of multiple inter-related computing devices. The factor ‘thing’ in IoT is designated to an entity capable of communicating data over a network (IOT), which can be a digital machine, sensor, human being, animals etc. Each component that is included in IoT network is assigned with an unique identity called UID and the ability to communicate data over IoT network without any external human or computer intervention.
Hello readers, I hope you all are doing great. In our previous tutorial, we discussed how to upload data to Firebase Real-time Database using ESP32. In this tutorial, we will learn how to read the data stored on the Firebase Database with ESP32.
We can access the data stored in Firebase database from anywhere in the world, which makes this preferable in IoT applications.
Where To Buy? | ||||
---|---|---|---|---|
No. | Components | Distributor | Link To Buy | |
1 | ESP32 | Amazon | Buy Now |
In our previous tutorial, we learnt how to upload an integer value (for demonstration) to Firebase real-time database. So, in this tutorial we will learn how to fetch or receive those integer values from Firebase database.
To access real-time data, we are using two ESP boards where one is used to upload/store the real-time data to the Firebase database and another to read the data stored on the firebase.
Although, it is not required to use two ESP boards, we can also access the previously saved data on the Firebase database with only a single ESP32/ESP8266 board.
We can use the same code for both ESP32 and ESP8266 but we need to make some changes like some of the libraries will be different for ESP8266 and the selection of ESP8266 development board while uploading the code with Arduino IDE.
Fig. 1 Reading data from firebase
Google's Firebase real-time database is a development platform that includes a number of services for managing and authenticating data.
Firebase is a mobile and web app development platform (that also works well with Android APIs) that includes features such as Firebase Cloud, real-time data, and Firebase authentication, among others.
According to Firebase's official documentation (https://firebase.google.com/docs/database), when a user creates a cross-platform application using JavaScript SDKs for Android or Apple, all clients share a single database.
Fig. 1 Firebase Real-time database and ESP32
The following are the main features of the Firebase Real-time database:
The Internet of Things, also known as IoT, is the interconnection of physical objects or devices with sensors and software accessing capabilities in order to communicate data or information over the internet.
We need an interface medium that can fetch, control, and communicate data between sender and receiver electronics devices or servers in order to build an IoT network.
The Firebase real-time database gives you a place to store data from sensors on your level device. With Android APIs, Firebase performs admirably.
Firebase is especially useful for storing data from sensors and syncing it between users in real-time in data-intensive Internet of things (IoT) applications. For the sake of simplicity and clarity, we can say that it is a Google cloud service for real-time collaborative apps.
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
Fig. 2 manage libraries
Fig. 3 Install Firebase ESP Client Library
We have already posted a tutorial on our website on getting started with Firebase real-time database and how to post or upload data to Firebase database from ESP32. Where we discussed, how to create a project on Firebase real-time database, authentication, how to access the API key and project URL etc.
So now we do not need to create a new project, we are using the same project and hence same API key and project URL to read or download the data from Firebase real-time database.
Fig. 4 Project Setting
Fig. 5 Project API key
Fig. 6 Project URL
//--add necessary header files
#include <WiFi.h>
#include <Firebase_ESP_Client.h>
#include "addons/TokenHelper.h" //Provide the token generation process info.
#include "addons/RTDBHelper.h" //Provide the real-time database payload printing info and other helper functions.
// Insert your network credentials
#define WIFI_SSID "ssid"
#define WIFI_PASSWORD "password"
// Insert Firebase project API Key
#define API_KEY "replace this with your project API key"
// ----Insert real-time database URL
#define DATABASE_URL "replace this with your project URL"
//Define Firebase Data object
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;
unsigned long sendDataPrevMillis = 0;
int read_data;
bool signupSuccess = false;
void setup() {
Serial.begin(115200);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(200);
}
Serial.println();
Serial.print("Connected to... ");
Serial.println(WiFi.localIP());
Serial.println();
// Assigning the project API key
config.api_key = API_KEY;
//Assign the project URL
config.database_url = DATABASE_URL;
/// check signup statue
if (Firebase.signUp(&config, &auth, "", "")) {
Serial.println("ok");
signupSuccess = true;
}
else {
Serial.printf("%s\n", config.signer.signupError.message.c_str());
}
// Assign the callback function for token generation task
config.token_status_callback = tokenStatusCallback;
Firebase.begin(&config, &auth);
Firebase.reconnectWiFi(true);
}
void loop()
{
if (Firebase.ready() && signupSuccess && (millis() -
sendDataPrevMillis > 8000 || sendDataPrevMillis == 0))
{
sendDataPrevMillis = millis();
if (Firebase.RTDB.getInt(&fbdo, "/test/int"))
{
if (fbdo.dataType() == "int")
{
read_data = fbdo.intData();
Serial.print("Data received: ");
Serial.println(read_data); //print the data received from the Firebase database
}
}
else
{
Serial.println(fbdo.errorReason()); //print he error (if any)
}
}
}
Fig. 7 Header files
Fig. 8 Helper libraries
Fig. 9 Insert API key
Fig. 10 RTDB URL
Fig. 11 Firebase Data Objects
Fig. 12 Enter Network credentials
Fig. 13 Initialize wifi module
Fig. 14 Fetch/obtain the IP address
Fig. 15 configuring API key
Fig. 16 configuring database URL
Fig. 17 sign up status
Fig. 18
Fig. 19 Fetch data from Firebase RTDB
Fig. 20
Fig. 21 Select development board and COM port
Fig. 22 Data sent Vs Data Received
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.
Welcome to the fifteenth chapter of this python course. Python lists and tuples were studied extensively in the last session, and we learned how to manipulate the data contained in these types of structures. You've only experienced sequential execution up to this point, where each statement is performed sequentially in the order they appear in the code.
However, the real world is frequently more nuanced. Sometimes, a program must skip over certain statements, run a set of statements repetitively, or pick between other sets of statements to execute. This is called "conditional branching."
That's when control structures come into play, which controls the sequence in which statements in a program are executed.
The if statement is the first control structure you'll encounter in Python.
Real-world situations frequently need us to examine the information around us and then make a decision based on what we've observed. As an illustration;
Unless it's raining, I'll be mowing the yard. It's correct to say that if it's pouring or snowing, I won't be mowing the lawn.
This type of decision-making is performed in Python programs using the if statement. If an expression has a certain value, and that value is known, a statement or set of statements can be executed.
Let`s get started.
We'll begin with the simplest form of an if statement. This is how it appears in its most basic form:
As you can see:
Execution of the statement occurs when the expression evaluates to a "truthy" value. No action takes place if expr is false. You must include a colon (:) after expr. Python does not require the parentheses around expr, as some other programming languages do.
This type of if statement is used in a variety of ways:
There is no effect on pressing Enter key after you have typed the print('yes') expression when using these examples interactively in a REPL session. There are multiple lines in this command. You must press Enter a second time to complete it. Executing a script file doesn't necessitate the use of an extra newline.
Suppose, on the other hand, that you wish to assess a condition and then take many actions if it is true:
There is only one 'statement' in each of the cases above, as demonstrated. It's necessary to be able to express "Do this if [expr] is true."
Syntactic devices, which bring together several statements into a single compound statement or block, are the most common technique employed by most programming languages. Syntactically, a block is considered to be a single entity. Explanation: All statements in the block are performed when it is an "if" target and "expr" is true. None of them are true if expr is false.
It is possible to define blocks in virtually all programming languages, however, this is not always possible. Let's have a look at Python's approach.
You may have heard the offside rule in football, right? Well, in programming, the off-side rule is a tenet of the Python programming language. Indentation is used by rule-abiding languages to define blocks. Off-side rule adherent Python is one of few languages.
Indentation has a specific meaning in a Python program, as you learned in the last tutorial on the structure of Python programs. The reason for this is that indentation is used to denote blocks of related statements. A block in a Python program consists of a series of statements that are all indented the same way. Thus, a Python compound if statement looks like this:
Lines 2 to 5 are considered to be part of the same block because they all have the same indentation level. If expr is true, the entire block executes, while if expr is false, the block is skipped. Following the following statement> (line 6) execution continues.
Tokens are not used to indicate the end of a block. There are two ways to tell when a block has come to a close.
Take foo.py as an example:
This is what happens when you run foo.py:
Lines 2-5 have the same indentation and print () commands. As a result, they form the code that would be executed if the underlying assumption was correct. Because it is untrue, the entire block is ignored. It doesn't matter whether or not lines 2 to 5 are executed, the first statement with a lower indentation level, the print () statement on line 6, is executed.
There is no limit on how deep blocks can be nested. Each new block is defined by a new indent, and each previous block is ended by an outdent. In the end, the structure is simple to follow, consistent, and easy to understand.
This script, called blocks.py, is a bit more complicated.
The following is an example of what you'll see after running this script:
When entering multiline expressions into a REPL session, you must include an extra newline because of the off-side constraint. Otherwise, the translator would have no means of knowing the if block's final statement had been entered.
Perhaps you'd like to know what other options are out there. It's unclear how blocks are declared in languages that don't follow the off-side rule
To denote the beginning and end of a block in most programming languages, special tokens are used as a strategy. Curly braces () are used to define blocks in Perl, for example:
Other programming languages, such as C/C++ and Java, also make use of curly brackets in this fashion.
Algol and Pascal, on the other hand, employ the keywords begin and end to denote the beginning and finish of a block.
It's all about how you look at it. They tend to have a strong opinion about how they do things in general. The off-side rule can generate a lot of controversies when it comes up for discussion.
The off-side rule is an issue you'll have to deal with if you are writing Python code. Python's control structures all rely on it, and you'll see this in several upcoming lectures. Many programmers initially resisted Python's approach to defining blocks, but they've since learned to enjoy it and even prefer it over more traditional methods.
If a certain condition is met, you may wish to conduct a certain course of action, but if it isn't, you may want to specify another course of action. The else clause is used to accomplish this:
If expr> is true, the first suite is run and the second is skipped. Second Suite Execution Is Skipped If 'Expr' Is False Execution resumes after the second suite is completed. Indentation is used to distinguish between the two suites, as indicated in the preceding paragraph. For example, lines 4 to 5 are run, and lines 7 to 8 are omitted because x is less than 50:
Because x exceeds 50 in this case, the first suite is omitted in favor of the second, which is run.
It's also possible to branch execution based on a variety of possible outcomes. One or more elif clauses can be used to do this. Each expr is evaluated in turn by Python, which then executes the set of instructions associated with the first one that is found to be true.
You can provide as many elif clauses as you like. The else clause is not required. One must be provided at the end if it is present:
An if statement with elif clauses, like the ‘and’ and ‘or’ operators, uses short-circuit evaluation. The remaining expressions are not tested when one of the tests returns true and its block is run. This can be seen in the following example:
There is a zero division in the second equation, and an undefined variable var is referred to in the third. As long as the first criterion is met, neither option will be assessed.
The following is a standard way to write if (expr) indented on a separate line from the statement (statement):
However, an entire if statement can be written on a single line. The following is essentially the same as the previous example. Semicolons are used to separate multiple statements on the same line.
One exception to this rule is when an entire if statement is written in one line. Functionally, this is just like the example above. Separated by semicolons, you can have multiple statements on a single line.
Unlike the other if statement forms, this one does not control the flow of program execution, unlike the ones listed above. It's more like an expression-defining operator. Conditional expr> is first evaluated in the above example. The expression evaluates to expr1 if it is true. It returns a value of expr2 if it is false.
It's important to note that the evaluation of the middle expression comes before the evaluation of the two ends, and as a result, only one of the two ends is returned. Here are a few real-world examples to illustrate my point:
Selective assignment of variables is a popular application of the conditional statement. Let's say you're trying to figure out which of two numbers is greater. You could, of course, use the built-in method max() to accomplish the same thing. But what if you want to start from scratch and develop your code?
The term "code stub" refers to a placeholder for a section of code that hasn't yet been implemented, such as when writing a test case.
Token delimiters, such as the curly brackets in C or Perl, can be used to define a code stub in these languages. Perl or C code like the following is acceptable:
The curly braces here denote an empty area. Even if the expression x is true, Perl or C will do nothing after evaluating it.
Specifying an empty block is impossible because Python utilizes indentation rather than delimiters. A follow-up statement, either indented or on the same line, is required after an if statement that begins with if expr. Consider foo.py as an example:
Foo.py doesn't work if it is attempted to be run.
This issue can be solved with the Python pass command. It does not affect the program's behavior. With this placeholder, the interpreter is kept happy in situations where a statement is required syntactically but no action is desired:
Foo.py is now error-free:
Congratulations! You have completed this tutorial on conditional statements in Python. We've explored the if-else statement in Python code and learned how to organize statements into blocks and understand the control structure concept in Python. Developing more complicated Python programs relies heavily on understanding these ideas. The while statement and the for statement are two new control structures that will be introduced in the next tutorial.
Welcome to the fourteenth chapter of our python tutorial course. In the last lesson, we looked at sets and operations done to sets, including union and intersection. In this tutorial, we'll take a closer look at lists and tuples to see how they're used. Python's most versatile and useful data types are lists and tuples. A non-trivial Python application will nearly always have these.
Lists and tuples have a number of significant features that you'll learn about. In this course, you'll understand the definitions and applications of these terms. By the time you're done, you'll know when and how to employ different Python object kinds.
In other words, Lists are similar to arrays in many other programming languages because they allow you to store any number of arbitrary elements within them. For a list to exist in Python, an object sequence must be enclosed in square brackets ([]) as seen in the example below:
In other words, a list is more than a collection of things. Collections of things are organized in this way. Lists are defined by the order in which their elements are listed, and this order is maintained throughout the life of the list itself. For more information on Python data types, check the dictionaries tutorial (coming soon).
A comparison of two lists that contain the same contents but are organized differently is impossible:
A list can be made up of any number of items. A list can have all of its elements of the same type:
Different kinds of elements can be used.
Complex objects such as functions, classes, and modules can also reside in lists, as you'll see in forthcoming tutorials:
From 0 to the limit of your computer's RAM, a list can contain any number of items.
Uniqueness isn't required for list objects. There is no limit to the number of times an object can be listed:
This is a question you could ask yourself whenever you need to access items in a list, and the answer is yes: an index in square brackets can be used to access items in a list. In other words, it's the same as looking up individual characters in a string. As with strings, the indexing of lists is zero-based. The following is a sample list:
Here are the indices for the items in a:
Slicing is another option. For lists, the formula a[m:n] retrieves only the part of a that is between m and but not containing n in the list a.
As you learned before, an item in a list can be of any type. Another list is included in that. You can have as many sublists as you want within a single list.
As an illustration, consider the following (obviously fabricated) scenario:
x refers to an item structure depicted in the image below:
These three strings below, are all one character in length:
Example of sublists are shown below:
Simply add an additional index to have access to the items in a sublist:
To the degree that your computer's RAM allows, there is no limit to the depth or complexity of nested lists in this manner.
A lot of your experience so far has been with atomic data types. Primitive units, such as integers and floats, are those that cannot be decomposed further. Once they've been allocated, these types aren't able to be modified. Changing the value of an integer doesn't make sense at all. If you prefer a different integer, simply change the one you've assigned.
The string type, on the other hand, is a complex type. Strings can be broken down into their constituent characters. Think of a string of characters and how they might be rearranged. However, this is not possible. Strings are also immutable in Python.
This is the first time you've met a mutable data type, the list. It is possible to add or remove items from a list at any time after it has been created. Lists can be modified in a variety of ways in Python.
A single value can be replaced in a list using indexing and simple assignment.
A string can't be used to accomplish this, as demonstrated in the Python tutorial Strings and Character Data.
In order to remove a list item, use the del command:
Suppose you'd like to change several neighboring items in a list at the same time. The following Python syntax for a slice assignment makes this possible.
Consider an iterable list at this point. iterable is substituted for the slice of a specified here:
It's not necessary to have the same number of new elements as the number of old ones. Python simply increases or decreases the list based on the task at hand. Utilize a slice which only refers to one element when you wish to replace a single element with multiple ones:
You can also add items to a list without having to remove anything from the original list. Simply type [n:n] to produce a zero-length slice at the requested index.
You can remove a large number of items from a list by assigning the correct slice to an empty list. It is possible to use the del statement with the same slice:
To add more items to the beginning or end of a list, you can use the + concatenation operator or the += augmented assignment operator:
For example, a singleton list can only have one item in it, hence, it must be added to a different list:
Python provides a number of built-in methods for modifying lists. Below, you'll find more information on these methods. The target string was not directly modified in the previous tutorial's string methods. Strings are immutable, so this is why. String methods, on the other hand, give you back a completely rewritten string object. They don't change the target string at all:
List methods differ from other approaches. Lists are changeable, therefore the target list gets modified while the list method is running.
Adds a new item to the end of a collection.
List functions change the target list on the fly. They don't give you a new one:
Adds items from an iterable to a list.
Yes, it's most likely what you're expecting. Additionally, an iterable is required as an argument to extend(). iterable> elements are inserted one at a time:
To put it another way, extend() functions similarly to the plus sign (+). Because it alters the list while it's still in place, it's equivalent to the += operator:
A new element is added to a collection with the help of this method. Object obj> is inserted into the list an at the index indicated by insert(index>, obj>). It's a[index>] obj, and the remaining list items are moved rightward after the function call.
In a list, this function removes one item. remove(<obj>) list an is cleared of obj. An exception is thrown if obj> is not in a:
In a list, this function removes one item. There are two key differences between this method and remove():
The last item in the list is simply removed by calling pop():
Specifying an index in the optional index parameter causes this command to remove and return the given item. Like string and list indexing, index can be negative.
Python lists are described in this course by a set of six qualities. Finally, lists can be reordered. Sections above have shown many instances of this. A list expands as new things are added:
Similarly, as things are removed from a list, the list gets smaller.
A tuple is a collection of things that are arranged in a specific order. When it comes to the pronunciation of a word or phrase, it depends on who you ask. A few people say it as if it were spelled "too-ple," while others pronounce it as "tup-ple," which rhymes with "supple." Because everyone I know pronounces "supple," "quintuple," "sextuple," and "octuple" as though they rhyme with "supple," my preference is for the latter.
Lists and tuples are nearly identical, with the exception of the following characteristics:
As an illustration of tuples in action, consider the following code sample:
There's no need to worry! Reversing a tuple is as simple as using our usual string and list reversal process:
It's important to remember that although though tuples are constructed using parenthesis, you still use square brackets to index and slice them.
A tuple is a list with the same properties as a list: it's ordered, it can include arbitrary objects; it's indexable and sliceable; and it can be nestable like any other list. However, they cannot be changed:
There is a way to display the values of several objects at once in a Python REPL session by simply inserting them one after the other between commas:
Because Python interprets the input as a tuple, it presents the response in parentheses. The definition of a tuple has a peculiarity that you should know about. It's impossible to be vague when creating a tuple that has no items or a tuple with two or more. A tuple is defined in Python:
Because parentheses are used to denote operator precedence in expressions, the expression (2) creates an int object. Before closing parentheses, you need to put in an extra comma (,): This tells Python that you plan to create a single tuple.
There has to be a mechanism to define a singleton tuple, even if you don't need to do it very often.
Using Python, you can display a singleton tuple by putting a comma in front of it:
You've seen this before: a literal tuple can be allocated to a single object.
When this happens, it's as if the tuple's contents have been "stuffed" into the object:
"packed" objects can be "unpacked" into a new tuple by assigning them to the new tuple's objects.
Otherwise, a problem will emerge when unpacking a tuple: if there are more variables than values, an error will occur.
Compound assignments can be created by combining the steps of packing and unpacking into a single expression.
It's important to remember that in this tuple, the components on the left and right must be equal.
It is possible to leave off the parentheses required to denote a tuple in Python assignments like this one and a few others:
If you're unsure whether or not the parentheses are necessary, go ahead and put them in if you have any doubt. Python idioms are made possible by multiple assignment. As a programmer, it is common to have two variables whose values must be swapped. While the swap is taking place, a temporary variable must be used to store one of the values.
In Python, a simple tuple assignment is all that is needed to perform a swap:
If you have ever used a Python temporary variable to exchange values, this is the pinnacle of modern technology. It's the greatest it's ever going to be.
Congratulations! You have now completed the list and tuple tutorial. Python lists and tuples were introduced, along with some of their basic features and operations. In Python, you'll be relying on these all the time. It is a list's primary property that it is organized. It is impossible to modify the order of a list's elements, unless, of course, the list is altered. The same is true for tuples, except that they can't be updated. Python's conditional statements will be covered in the upcoming lesson.
Hello readers, I hope you all are doing great. In this tutorial, we will learn how to access Firebase (a real-time database) to store and read values or data with ESP32.
It is Google’s mobile application development platform that can be used to can access, monitor and control ESP32 from anywhere in the world with its (firebase) real-time database.
Where To Buy? | ||||
---|---|---|---|---|
No. | Components | Distributor | Link To Buy | |
1 | ESP32 | Amazon | Buy Now |
Firebase real-time database is a development platform provided by Google which included multiple services to manage and authenticate data.
Firebase is basically a mobile and web app development platform I as works great with Android APIs) that includes features like firebase cloud, real-time data and Firebase authentication etc.
As per Firebase’s official documentation (https://firebase.google.com/docs/database), whenever a user creates a cross-platform application like with Android, or Apple, JavaScript SDKs, all the clients share a single.
Fig. 1 Firebase Real-time database and ESP32
The main features of the Firebase Real-time database are:
The IoT or Internet of Things is the interconnection of physical objects or devices with sensors and software accessing capabilities to communicate data or information over the internet.
To build an IoT network, we need an interface medium that can fetch, control, and communicate data between sender and receiver electronics devices or servers.
Firebase real-time database provides a platform to store data collected from sensors at the level device. Firebase works great with Android APIs.
Firebase is particularly useful in data-intensive Internet of things (IoT) applications to store from sensors and synch that data between users in real-time. For simplicity or better understanding we can say that it is a cloud service provided by Google for real-time collaborative apps.
The steps involved in creating a Firebase project are:
Fig. 2 Get started
Fig. 3 Create a project
Fig. 4 project name
Fig. 5 Enabling Google Analytics
Fig. 6 Project Created successfully
As per the official firebase documentation at: https://firebase.google.com/docs/auth , the identity of a user is required by most online services or mobile applications or we can say , it handles authentication process and logging in (in this tutorial, the ESP32). Getting to know the identity of a user enables an application to save user data securely in the cloud and provide a consistent personalized service across all of the customer's devices (android phones, computers, applications etc).
Fig. 7 Authentication
Fig. 8 Select authentication method
Next thing is creating a real-time database for the project.
Fig. 9 Real-time database
Fig. 10 Creating database
Fig. 11
Fig. 12 select location
Fig. 13 Accessing project API key
We are using Arduino IDE to compile and upload code into the ESP32 module. You must have the 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:
Fig. 14 manage libraries
Fig. 15 Install Firebase ESP Client Library
//--add necessary header files
#include <WiFi.h>
#include <Firebase_ESP_Client.h>
#include "addons/TokenHelper.h" //Provide the token generation process info.
#include "addons/RTDBHelper.h" //Provide the real-time database payload printing info and other helper functions.
// Insert your network credentials
#define WIFI_SSID "replace this with your netwrok SSID"
#define WIFI_PASSWORD "replace this with your wi-fi password"
// Insert Firebase project API Key
#define API_KEY "replace this with your API key"
// ----Insert real-time database URL
#define DATABASE_URL "replace this with your project URL"
//----Define Firebase Data object
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;
int value = 10;
bool signupSuccess = false;
unsigned long sendDataPrevMillis = 0;
void setup()
{
Serial.begin(115200);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED){
Serial.print(".");
delay(100);
}
Serial.println();
Serial.print("Connected with IP: ");
Serial.println(WiFi.localIP() );
Serial.println();
// Assign the api key ( required)
config.api_key = API_KEY;
// Assign the RTDB URL ( required)
config.database_url = DATABASE_URL;
// Sign up status
if (Firebase.signUp(&config, &auth, "", ""))
{
Serial.println("ok");
signupSuccess = true;
}
else{
Serial.printf("%s\n", config.signer.signupError.message.c_str());
}
/* Assign the callback function for the long running token generation task */
config.token_status_callback = tokenStatusCallback; // see addons/TokenHelper.h
Firebase.begin(&config, & auth);
Firebase.reconnectWiFi( true);
}
void loop()
{
if (Firebase.ready() && signupSuccess && (millis() - sendDataPrevMillis >
10000 || sendDataPrevMillis == 0))
{
sendDataPrevMillis = millis();
if (Firebase.RTDB.setInt(&fbdo, "test/int", value))
{
Serial.println("PASSED");
Serial.println("PATH: " + fbdo.dataPath());
Serial.println("TYPE: " + fbdo.dataType());
}
else
{
Serial.println("FAILED");
Serial.println("REASON: " + fbdo.errorReason());
}
value++;
}
}
Before uploading the code in ESP32 board there are some changes you need to make which includes:
Fig. 16 Header files
Fig. 17 Helper libraries
Fig. 18 Insert API key
Fig. 19 RTDB URL
Fig. 20 Firebase Data Objects
Fig. 21 Enter Network credentials
Fig. 22 variable declaration
Fig. 23 Initialize wifi module
Fig. 24 Fetch/obtain the IP address
Fig. 25 configuring API key
Fig. 26 configuring database URL
Fig. 27 sign up status
Fig. 28
Fig. 29 Loop() function
Fig. 30 Select development board and COM port
Fig. 31 Result 1
Fig. 32 Result 2
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.
Hello readers, I hope you all are doing great. In this tutorial, we will learn how to interface the BMP280 sensor with the ES32 module to get temperature, pressure and altitude readings. Later, in this tutorial, we will also discuss how to upload these sensor readings to a web server.
Where To Buy? | ||||
---|---|---|---|---|
No. | Components | Distributor | Link To Buy | |
1 | ESP32 | Amazon | Buy Now |
BMP280 or Barometric pressure sensor is a module used to measure temperature pressure and altitude. The small size and low power consumption feature of this sensor makes it feasible for battery-powered devices, GPS modules and mobile applications etc.
Fig. 1 BMP280 Sensor
The BMP280 is the product of BOSCH which is based on Bosch’s proven Piezo-resistive pressure sensor technology featured with high accuracy, long term stability, linearity and high EMC robustness.
BMP280 is the successor of the BMP180 sensor and offers high performance in all the areas that require precise temperature and pressure measurements.
Emerging applications like fitness, indoor navigation, GPS refinement requires relative accuracy and BMP280 is perfect for such applications. Very low TCO (Temperature coefficient of Offset ) makes this module preferable over other available modules for temperature measurements.
We can also use a DHT11/DHT22 sensor for temperature and humidity measurements but the BMP280 sensor provides better accuracy (i.e., 0.01°C) than DHT sensors.
There are two methods of interfacing BMP280 sensor with ESP32 module:
In the bMP280 Sensor module, there are six interfacing pins including VCC and GND.
Fig. Interfacing BMP280 and ESP32
We are using the I2C protocol for interfacing the two (ESP and BMP280) so only SCL and SDA pins will be used with power pins for interfacing. The SDO and CSB pins will be used only if you are using the SPI protocol for interfacing.
Table 1
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:
Fig. 2 manage libraries
Fig. 3 Install library
#include <Wire.h>
void setup()
{
Wire.begin();
Serial.begin(115200);
Serial.println("\nI2C Scanner");
}
void loop()
{
byte error, address;
int nDevices;
Serial.println("Scanning...");
nDevices = 0;
for(address = 1; address < 127; address++ )
{
Wire.beginTransmission(address);
error = Wire.endTransmission();
if (error == 0)
{
Serial.print("I2C device found at address 0x");
if (address<16)
{
Serial.print("0");
}
Serial.println(address,HEX);
nDevices++;
}
else if (error==4)
{
Serial.print("Unknow error at address 0x");
if (address<16) {
Serial.print("0");
}
Serial.println(address,HEX);
}
}
if (nDevices == 0) {
Serial.println("No I2C devices found\n");
}
else {
Serial.println("done\n");
}
delay(5000);
}
#include <Wire.h>
#include <Adafruit_BMP280.h>
#define BMP_SDA 21
#define BMP_SCL 22
Adafruit_BMP280 bmp280;
void setup()
{
Serial.begin(115200);
Serial.println("Initializing BMP280");
boolean status = bmp280.begin(0x76);
if (!status)
{
Serial.println("Not connected");
}
}
void loop()
{
float temp = bmp280.readTemperature();
Serial.print("temperature: ");
Serial.print(temp);
Serial.println("*C");
float altitude = bmp280.readAltitude(1011.18);
Serial.print("Altitude: ");
Serial.print(altitude);
Serial.println("m");
float pressure = (bmp280.readPressure()/100);
Serial.print("Pressure: ");
Serial.print(pressure);
Serial.println("hPa");
Serial.println(" ");
delay(1000);
}
Fig. 6
Fig. 7
Fig. 8
Fig. 9
Fig. 10 Select development board and COM port
Fig. 11 Serial monitor output
Most of the industries and organizations these days are shifting to the efficient ways of operating things and the IoT internet of things is one of them.
Internet of Things is a system of multiple inter-related computing devices. The factor ‘thing’ in IoT is designated to an entity capable of communicating data over a network (IOT), which can be a digital machine, sensor, human being, animals etc.
Each component that is included in IoT network is assigned with an unique identity called UID and the ability to communicate data over IoT network without any external human or computer intervention.
Fig. 12 IoT
ThingSpeak is an open data platform for the Internet of Things applications. It is a MathWorks web service that allows users to send sensor readings and data to the cloud. We can also visualize and act on the data (calculate the data) that is sent to ThingSpeak by the devices. The information can be saved in both private and public channels.
ThingSpeak is frequently used for IoT prototyping and proof-of-concept devices that require data analysis.
Downloading and installing the required Library file:
https://github.com/mathworks/thingspeak-arduino
Fig. 13 Adding ThingSpeak library
To check whether the library is successfully added or not:
Fig. 14
Fig, 15 Arduino IDE Library manager
Fig. 16 Getting started for free
Fig. 17 Create new account
Fig. 18 MathWorks Sign in
Fig. 19 New Channel
Fig. 20 Creating channel and respective fields
Fig. 21 save the channel
Fig. 22 Field Chart Edit
// ------style guard ----
#ifdef __cplusplus
extern "C"
{
#endif
uint8_t temprature_sens_read();
#ifdef __cplusplus
}
#endif
uint8_t temprature_sens_read();
// ------header files----
#include <WiFi.h>
#include "ThingSpeak.h"
#include <Wire.h>
#include <Adafruit_BMP280.h>
#define BMP_SDA 21
#define BMP_SCL 22
Adafruit_BMP280 bmp280;
// -----netwrok credentials
const char* ssid = "public"; // your network SSID (name)
const char* password = "ESP32@123"; // your network password
WiFiClient client;
// -----ThingSpeak channel details
unsigned long myChannelNumber = 4;
const char * myWriteAPIKey = "9R3JZEVBG73YE8BY";
// ----- Timer variables
unsigned long lastTime = 0;
unsigned long timerDelay = 1000;
void setup()
{
Serial.begin(115200); // Initialize serial
Serial.println("Initializing BMP280");
boolean status = bmp280.begin(0x76);
if (!status)
{
Serial.println("Not connected");
}
//Initialize Wi-Fi
WiFi.begin(ssid, password);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(100);
}
Serial.println();
Serial.print("Connected with IP: ");
Serial.println(WiFi.localIP());
Serial.println();
// Initialize ThingSpeak
ThingSpeak.begin(client);
}
void loop()
{
if ((millis() - lastTime) > timerDelay )
{
float temp = bmp280.readTemperature(); //temperature measurement
Serial.print("temperature: ");
Serial.print(temp);
Serial.println("*C");
float altitude = bmp280.readAltitude(1011.18); //altitude measurement
Serial.print("Altitude: ");
Serial.print(altitude);
Serial.println("m");
float pressure = (bmp280.readPressure()/100); //pressure measurement
Serial.print("Pressure: ");
Serial.print(pressure);
Serial.println("hPa");
Serial.println(" ");
ThingSpeak.setField(1, temp );
ThingSpeak.setField(2, altitude);
ThingSpeak.setField(3, pressure);
// Write to ThingSpeak. There are up to 8 fields in a channel, allowing you to store up to 8 different
// pieces of information in a channel. Here, we write to field 1.
int x = ThingSpeak.writeFields(myChannelNumber,
myWriteAPIKey );
if(x == 200)
{
Serial.println("Channel update successful." );
}
else
{
Serial.println("Problem updating channel. HTTP error code " + String(x) );
}
lastTime = millis();
}
}
We are describing only the ThingSpeak server part as the BMP280 and ESP32 interfacing part has already been discussed in the above code description.
Fig. 23 Style guard
Fig. 24 Libraries
Fig. 25
Fig. 26
Fig. 27
Fig. 28
Fig. 29
Fig. 30
Fig. 31
Fig. 32 Sensor readings
Fig. 33 setting respective Fields
Fig. 34
Fig. 35
Fig. 36 ThingSpeak server
Fig. 37 Sensor readings on the Serial monitor
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.
In PCB boards you come across LEDs fixed in them, and due to the evolving world of technology, things are changing so first leading to the crafting of new technologies that have led to changes in the LED areas. The LED case is an area that has involved the combination of two methods of technologies in order to come up with something else that is more efficient when it comes to solving the intended purpose. This LED PCB comes with advantages of longevity and durability.
This is a type of PCB that is used for the purpose of lighting in the lighting appliances like modern LED bulbs. The material used in the process of making this board currently is the metal copper clad that has a very good heat-dissipating function. In general, we should note that the single layer LED PCB is made up of three layers namely the circuit layer, the ceramic layer and the insulation layer.
This is made up of the electrolytic copper foil and is etched to form the printed circuit board where the components are attached. When you do the comparison with the traditional boards, the LED board can carry a larger amount of current.
This layer is the core technology behind this type of boards and plays greater roles in the conduction insulation and bonding of the layers.
Here aluminum is the best choice compared to its availability and the cheap prices it offers. Stainless steel, silicon and the iron can be used if the thermal conductivity required is very high.
This consist of the substrate layer together with a conductive layer. A solder mask together with a silkscreen offer protection functions to these layers.
When you don a comparison with the single layer PCBs, you will realize that this has two copper layers which apparently makes them heavier as the number of conductive layers also increase to two.
There are two assembly methods that can be employed in the assembly if the LED PCBs. These methods are used to attach components on the board and we shall discuss it below;
This method involves mounting the electronic components directly into the board copper layer.
This method involves the drilling of holes into the PCB boards where components are then mounted to the holes using the long leads that are then soldered and the whole filled with flux.
This is one of the common applications the LED PCBs where they find great use on the consumer lighting from flash lights, lamps, spotlights, lanterns to solar powered lighting applications.
LED are also becoming a common application in the electronic devices such as the computer keyboards backlights. Other devices that have employed this technology are smartphones, tablets and the televisions.
Telecommunication displays and indicators use the LED PCBS because of their durability the ability to transfer heat and their longevity since telecommunication gadgets generate a lot of heat.
LEDs have a lot of use in the traffic and the transportation industry ranging from the stop lights and the automotive themselves. In the car this PCs are found in the headlights, fog lights, brake lights, reverse lights and the indicators. Highways tunnel lighting also use this technology. The modern streetlighting system is done using the LED PCBs.
Medical lighting and the medical equipment lighting that are used for medical examination and surgery often use this type LED PCBs.
This is the next lesson in our Python course. Previously, we looked at an overview of the different data types in python such as dictionaries, Boolean and sets. This tutorial will focus on Python sets to get a deeper understanding of this data type, so let's get started. During your schooling, there is a good chance you learned about sets and set theory. Venn diagrams may even be familiar to you:
Don't worry if you don't recognize this! You should still be able to access this tutorial without any problems. Rigidly defining a set in mathematics can be both abstract and difficult to understand. A set is thought of as a well-defined group of unique objects, which are sometimes called "elements."
Python's built-in set type facilitates the grouping of items into sets, which is important in programming as well. Unique actions that can be done on a set separate it from other object types.
Using Python, you learn how to create set objects and learn about the various activities they can be used for. We've covered lists and dictionaries in previous tutorials, so you should be familiar with when a set is the right tool for the job. You'll also look at "frozen sets," which are similar to sets but differ in one significant way.
The following features describe the built-in set type in Python:
Let us explore what all that entails, and how you can interact with sets in Python.
Iter> is an iterable (imagine a list or tuple for now) that generates a list of items to be included in the set. This is the same as the list method's iter> argument .extend():
A string can also be supplied to set() because strings are iterable. As you can see, list(s) generates a list of the characters in the string s. In the same way, set(s) generates a set of the characters in s:
The resulting sets are not in any order. The definition's original order isn't always followed. Values that are duplicated such as the string 'foo' in the first two examples and the letter 'u' in the third are only represented in the set once.
Curly braces () can also be used to define a set:
Each obj> becomes a separate element of the set when defined in this way, even if it is iterable. The .append() list technique works similarly. As a result, the sets depicted above can alternatively be described as follows:
To summarize:
Consider the following differences between these two definitions:
A set can be empty. The set() method is the sole way to define an empty set in Python because empty curly braces () are regarded as an empty dictionary.
In Boolean logic, an empty set is false:
A Boolean variable can only have two values in general: True or False. In other words, we call a variable a Boolean variable if it can only have these two values. It's frequently used to denote an expression's Truth value. True equals 1 and False equals 0 in mathematics. In contrast to electronics, a light bulb has a high value (that is 1) when it is switched on, and vice versa.
The len() function, which returns the number of items in a set, can be used to test for membership with the in and not in operators:
Sets are incompatible with many of the operations that operate with other composite python data types. Sets, for instance, cannot be indexed or sliced. Python, on the other hand, provides set object methods that are quite similar to the operations given for mathematical sets.
Most, but not all, set operations in Python can be accomplished using either an operator or a method. Let's look at how set union works as an illustration of how these operators and methods function. With sets, x1, and x2, the union of the two sets yields a set that contains all members from both sets.
Consider the following:
The results of combining x1 and x2 are shown below.
Note that in the union, 'baz,' will appear in both x1 and x2 only once. There are never any duplicate values in a set.
The | operator in Python can be used to execute set union:
The union() method can also be used to get a set union. The method is called using one of the sets as an input, and the other is supplied as a parameter:
The operator and method operate identically when used in the instances above. However, there is a distinction between them. Both operands must be set when using the | operator. In contrast, the union() method takes any iterable as an input, turns it into a set, and then executes the union.
Take note of the differences between the following two statements:
Both try to combine ('baz', 'qux', 'quux') with x1. The | operator fails, but the union() method succeeds.
A list of Python set operations is shown below. Some tasks are accomplished by an operator, while others are completed by a method, and still, others are completed by both. When a set is required, procedures normally accept any iterable as an input, whereas operators require actual sets as operands.
x1 | x2 [| x3 ...]
Add two or more sets together to get the unionset.
x1.union(x2) and x1 | x2: returns the sets of all items in either x1 or x2.
With either the operator or the method, you can specify more than two sets:
All elements that appear in any of the defined sets are included in the final set.
x1 & x2 [& x3 ...]
Calculate the point at where two or more sets intersect.
The set of items shared by both x1 and x2 is returned by x1.intersection(x2) and x1 & x2:
The intersection method and operator, like set union, allow you to specify multiple sets.
Only components that appear in all of the provided sets are included in the resulting set.
Calculate the difference between at least two sets.
Two examples of x1.difference are x1.difference(x2) and x1 - x2 (x2). produce a list of all x1 elements that aren't found in x2:
difference(x2) and x1 - x2 return the set that is returned when any elements in x2 are removed or subtracted from x1.
You can specify multiple sets once more:
The procedure is executed from left to right when several sets are supplied. In the foregoing example, the first step is to compute a - b, which yields 1, 2, 3, 300. After that, the set is taken from c, leaving 1, 2, and 3:
Calculate the difference between two symmetric sets.
The sets containing all items in x1 or x2, but not both, are returned by symmetric difference(x2) and x1 x2:
Additionally, the operator ^ enables for more than two sets:
The operation is executed from left to right once multiple sets are supplied, just like with the difference operator.
Surprisingly, although the operator supports multiple sets, the symmetric_difference() function does not:
Sets can be altered, even though their components need to be immutable types. Similar to the operations above, the contents of a set can be altered using a combination of operators and processes.
Each of the aforementioned operators has an augmented assignment form that can be used to change a set. Each person takes a different approach.
x1 |= x2 [| x3 ...]
The union can be used to change the state of a set.
x1 &= x2 [& x3 ...]
Intersection can be used to change a set.
x1 &= x2 and update(x2) x1 should be updated with only the items that present in both x1 and x2:
x1 -= x2 [| x3 ...]
Make a difference in a set.
x1.difference update(x2) and x1 -= x2 remove components found in x2 from x1:
x1 ^= x2
By using symmetric difference, you can change a set.
x1=x2 and update(x2) update x1, maintaining either x1 or x2 components, but not both:
Aside from the augmented operators listed above, Python has several other ways of modifying sets.
Adds a new element to a collection.
x.add(elem>) appends elem> to x:
Removes one of a set's elements.
elem> is removed from x using x.remove(elem>). If elem> is not in x, Python throws an exception:
Removes one of a set's elements.
elem> is also removed by x.discard(elem>). If elem> is not in x, this procedure does nothing instead of issuing an exception:
A set contains the random element to be removed from it.
x.pop() removes and returns an element from x that is picked at random. x.pop() throws an exception if x is null:
A frozenset is a Python in-built type that is similar to a set but is immutable. The following non-modifying procedures are possible on a frozenset:
Attempts to change a frozenset, on the other hand, fail:
You might suppose that because a frozenset is immutable, it can't be the target of an augmented assignment operator. However, keep the following in mind:
With frozensets in place, Python does not perform augmented assignments. The expression y &= s is practically the same as y = y & s. It makes no changes to the original x. It's associating x with a new item, and the one with which it was previously connected has vanished.
The id() method can be used to check this:
Following the augmented assignment, f has a new integer identification. It has been reassigned rather than changed in situ. When a Python object is the target of an augmented assignment operator, it is updated in place. Frozensets, on the other hand, are not. Frozensets are useful in cases where you need an immutable object yet wish to utilize a set. For example, because set elements must be immutable, a set with items that are also set cannot be defined.:
When you need to define a set of sets, frozensets, which are immutable, are the way to go:
Remember from the previous dictionary instruction that a dictionary key must be immutable. The in-built set type can't be used as a dictionary key for the following reason:
If you're looking for a way to use sets as dictionary keys, try frozensets:
We must use a membership operator to see if an element exists in a set. To check if an element is present in a sequence, membership operators are employed (e.g., strings, lists, tuples, sets, or dictionaries). As mentioned below, there are two membership operators.
Use the len () function to calculate the total number of items in a set. The number of items in an object is returned by this function. The function's input can be any sort of sequence, including a text, dictionary, list, or tuple, in addition to a set.
This tutorial teaches you how to create set objects in Python and how to interact with them using functions, operators, and methods. Python's main built-in data types should now be familiar to you. Then you'll examine the organization and structure of the code of a Python program that interacts with those items. In the next topic we will look at python list and python tuple.
Hi Friends! Glad to have you on board. Thank you for clicking this read. In this post today, I’ll walk you through Edge Computing vs Cloud Computing.
Cloud computing has been around for many years while edge computing, on the other hand, has just become the prime topic of mainstream organizations. But what is the key difference between both edge computing and cloud computing, how do they work, can we implement both in the IT model of any business? These are the main questions that arise every time someone tries to get a hold of these terms. Don’t worry. We’ll discuss them in detail so you know when to pick a cloud model and when to choose edge computing.
Keep reading.
Before we go further to describe the comparison between edge and cloud, know that, both these infrastructures are independent of each other and companies separately employ these models based on their business needs and requirements. Edge computing favors the IT model of the company at times, while cloud computing is the answer to handle some issues.
Edge computing is a distributed and decentralized computing infrastructure that brings computing power and storage near the edge of the network. Simply put, the data is handled or stored near the location where it’s produced. This reduces the bandwidth and removes the latency issues (latency is a time delay between actual action and processed action), requiring fewer data to be stored with improved quality. This phenomenon is ideally suited for applications that are time-sensitive and are dependent on the quick decisions to make. Know that the introduction of IoT devices for a variety of businesses is the main driving force of this edge computing development. Gartner predicts, “Around 10% of enterprise-generated data is created and processed outside a traditional centralized data center or cloud. By 2025, this figure will reach 75%.”
Cloud computing, on the other hand, is a centralized computing infrastructure where computing is carried out at the cloud with data centers that are located miles away from the data source. This process takes time because you cannot make quick and on-spot decisions since the produced data move to the cloud for processing before you make decisions based on the processed data. In cloud computing produced data moves to the cloud for processing while in edge computing the cloud comes near the produced data.
For instance, vibration sensors are installed in the industry to monitors the metrics of vibration caused by machines. If the sensors are connected with the cloud and vibration levels go above the required readings, it takes some time to shut down the machines since the first data produced by the sensors will go to the cloud for the processing which causes time delay and the machine will take some time to shut down. While if those sensors are connected with the edge device near the location where data is produced, and if readings go above the required level, the machines will get shut down immediately since the edge device is installed near the data source and it doesn’t require time to move that data to the cloud.
Now we know what cloud and edge computing is, in this section, we’ll cover how these infrastructure work.
Three main components are used in edge computing:
In edge computing, an additional node is introduced between the device and cloud called edge device. This way no involvement of the cloud is required to manage, process, and store data. Instead edge device will serve this purpose.
It is important to note that, edge computing contributes to the cloud but it’s not a part of the cloud, and processing is done near the data source in the edge device. In cloud computing internet is necessary to maintain connectivity throughout the process to handle and store data in the data centers. While in edge computing, as the edge is not part of the cloud, you can still get results and process data without internet connectivity since the devices relying on edge infrastructure normally uses 5G or IoT (internet of things) technology to process data.
Two main components are involved in cloud computing:
Data is produced at the data source (device) and that data is then moved to the cloud with data centers where that data is being processed. Cloud computing takes more time to process data hence creating latency issues.
The following are the main advantage of edge computing.
As touched earlier, the computing power and storage bring near the edge of the network in edge computing, removing the need for cloud resources to process data. This significantly improves the performance of the system, allowing the machines to make quick decisions based on the processed data. Using this infrastructure, you are adding the intelligent computing power near the source of the data which keeps the latency low which means you’ll get processed data quickly with improved quality. Experts say edge computing combined with 5G will reduce the latency, if not zero, to 1 millisecond.
As you know, cloud infrastructure is completely owned and managed by the cloud service provided, giving you less control over the data to be managed and stored. While edge computing gives you better control over data since the data is managed and stored locally without the involvement of the cloud.
Edge computing is less expensive compared to cloud computing since less bandwidth is required and no large amount of data needs to be stored. You only need the required data to make real-time decisions. Moreover, connectivity, data migration latency issues are pretty much expensive in cloud computing. Edge computing removes the requirement of enormous bandwidth since no large amount of data is stored in data centers. Nowadays companies prefer edge computing over cloud computing because of its low operational cost and improved and optimal system performance.
Since data is stored and processed near the data source, it allows companies to keep their sensitive data within the local area network. It provides added advantage to companies obsessed with the security of their data.
The company’s requirement of IT models varies as the business grows over time. Purchasing dedicated cloud resources is not a wise move since you’re not sure what business requires as the customers' needs and requirements change. The main advantage of edge computing is its ability to scale it as per the activities of the business. Edge computing gathers and processes data locally with dedicated hardware called edge device, setting you free from depending on the software environment of data centers in cloud computing.
The following are the main advantages of Cloud Computing:
In cloud computing data is stored and processed in the cloud which means it creates the backup of your data. In case of emergency, if your data is deleted or compromised, you can collect a copy of the electronic file stored in data centers of the cloud. Organizations of every size use cloud computing to create a backup of their important data. As the company grows, the requirements of the data to process and store also grow which makes cloud computing an important part of the company’s IT infrastructure.
If you store data in local data centers, you require capital expense to install, handle, maintain and scale those data centers. With cloud computing, you no longer need to handle and manage the separate data centers since your data is stored in the cloud globally managed and supported by data centers.
The cloud service providers often offer pay-as-you-go packages which means you can customize the computing resources as per your requirement. As the business grows, the activities of the business also go complex, getting a customized package from the cloud service providers helps you vary the plan as per your exact needs and requirements.
Cloud computing offers more flexibility to businesses compared to organizations using traditional local data centers. You need to upgrade your IT infrastructure if you want more bandwidth to handle the onslaught of data, while with cloud computing you can request more bandwidth instantly. Still, it depends on the service provider you pick for cloud computing, not all providers are equal, some are better than others. So make sure you put the dedicated effort into figuring out which service provider will more efficiently complement your business.
Cloud data is easily accessible to anyone around the world. Considering the growing usage of mobile devices like smartphones and tablets is a great advancement to make the data accessible for anyone anywhere in the world. This works for businesses working with freelancers and remote employees who are not part of on-site staff. It provides better work-life balance to employees and adds flexibility to the working environment of the company.
Think about on-site IT infrastructure and drills it needs to routinely update and maintain local data centers. This is not the case with cloud computing since the software involved in this model updates themselves automatically, setting you free from the hassle of manual updating.
If you’re still reading this post, it means you got to know what both edge and cloud models hold and their advantages. It’s too early to say which one is better since both models are different and are employed based on the business needs and requirements.
If you want the backup of your data and are not concerned about the time it takes to store and process that data, cloud computing is the solution. For the large volume of data to store and process, cloud computing is used. And if you’re concerned about the time it takes to process data, then edge computing is the solution. Using this infrastructure, you can make quick and better decisions for the activities that are time-sensitive. For example in the case of automatic cars you need to make an instant decision about the car’s fuel consumption and the route it takes to reach the destination. Similarly, to successfully use the facial recognition feature to unlock the mobile, you need instant data to be processed to unlock the screen. Here edge computing works far better than the cloud model since cloud computing takes a lot of time to process facial features to unlock the screen.
Latency is another issue that edge computing handles better. For instance, the live feed you record with surveillance cameras. If these cameras are connected with the cloud, it will increase the latency and you’ll get the processed video after some time. This is not the case in edge computing. If motion sensors are installed near the surveillance cameras, in this case, the monition sensor itself will work as an edge device, and it providers immediate feed of the live recording without time delay.
More companies, no doubt, are adopting edge computing at an accelerated pace, still, it’s too early to say if this is the end of cloud computing. The Cloud model holds its values when it comes to storing a large amount of data. However, with the inception of AI and IoT devices, processing capabilities become the major concern instead of storing a large amount of data. This projects that cloud computing will remain relevant for the development of the company’s IT models, and it will work with edge computing to provide better and instant processing capabilities.
That’s all for today. Hope you’ve enjoyed reading this article. If you’re unsure or have any questions, you can reach out in the section below. I’d love to help you the best way I can. Thank you for reading this article.
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.
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.
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.
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.
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]
The components of a list can be accessed in a variety of ways.
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.
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.
lists are mutable, meaning their elements can be changed. To update a single item or a set of objects, use the assignment operator (=).
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.
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)
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.
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).
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.
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'}
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.
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
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}
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.
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 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.
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.
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}
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.
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. | Components | Distributor | Link To Buy | |
1 | ESP32 | Amazon | Buy Now |
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.
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.
There are basically two ways to connect the ESP32 to a 16 * 2 LCD display.
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
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
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:
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
#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( )
{
}
Fig. 4: Adding header files
Fig. 5: LCD data and control pins
Fig. 6: server port
Fig. 7: Enter Network credentials
Fig. 8
Fig. 9: HTML web page
Fig. 10: HTML form for data input
Fig. 11: Post button.
Fig. 12
Fig. 13: Fetch/obtain the IP adrress
Fig. 14: Set 16*2 LCD
Fig. 15: Initialize the server
Fig. 16: Send web page to client
Fig. 17
Fig. read the input from HTML form
Fig. 18
Fig. 19
Fig. 20
Fig. 21: Select development board and COM port
Fig. 22: web Page
Fig. 23: Enter the Input to ESP32
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.