Reading Data from Firebase Database with ESP32

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.ComponentsDistributorLink To Buy
1ESP32AmazonBuy Now

Project overview

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

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:

  • Firebase applications remain responsive even when they are not connected to the internet. If any changes were missed while in offline mode, they will be automatically synchronized once connectivity is restored.
  • Unlike hypertext transfer protocol requests, Firebase RTDB uses data synchronization to update changes in the database within milliseconds, making it easier to access the database from a web browser or a mobile device.

Firebase in IoT:

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.

Components required:

  • ESP32 development board
  • Arduino IDE for programming
  • Firebase account
  • Firebase API key and project URL

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. 2 manage libraries

  • Search for the Firebase ESP Client library in Library Manager and click Install.
  • We are attaching an image, where we are installing the Firebase ESP-Client (2.3.7 version) library.

Fig. 3 Install Firebase ESP Client Library

Firebase API key and Project URL

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.

  • To access the project API key, go to Firebase website and open the project you have created.
  • Go to left sidebar >> setting >> project setting and copy the Web API key.
  • Paste that API key in your Arduino IDE code.

Fig. 4 Project Setting

Fig. 5 Project API key

  • Got to Real-time database on left sidebar and copy the project URL.
  • Paste the project URL in your Arduino IDE code.

Fig. 6 Project URL

 

Code

//--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)

}

}

}

Code Description

  • The libraries we are using are:
    • The first one is h, which is used to enable the Wi-Fi module and hence wireless network connectivity.
    • Another library we are using is the h which is responsible for interfacing ESP32 and Firebase Real-time Database.

Fig. 7 Header files

  • We also need to add two helper libraries (required by the Firebase library).
  • The TokenHelper library is responsible for managing the token generation process.
  • On the other hand, the RTDBHelper library is responsible for providing helper functions to print data coming from the Firebase database.

Fig. 8 Helper libraries

  • Next, we need to insert the project API key obtained from the Firebase project setting page.

Fig. 9 Insert API key

  • Similarly, insert the RTDB (real-time database) URL.

Fig. 10 RTDB URL

  • Next, we are defining three firebase data objects, responsible for linking App to Firebase.

Fig. 11 Firebase Data Objects

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

Fig. 12 Enter Network credentials

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. 13 Initialize wifi module

  • 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. 14 Fetch/obtain the IP address

  • Here, we are assigning the API key to the firebase configuration.

Fig. 15 configuring API key

  • Similarly, the database URL is also assigned to firebase configuration

Fig. 16 configuring database URL

  • Next, we are checking or verifying the Firebase sign-up status.
  • In the signup() function the last two arguments are empty, indicating the anonymous user.
  • If you have enabled different sign-up methods during the Firebase authentication method like Google account, Facebook etc then you need to add the respective credentials as arguments.
  • The respective results of signup status will be printed on the serial monitor.

Fig. 17 sign up status

  • Next, you need to assign the callback function for token generation.

Fig. 18

Loop()

  • Once the signup is successfully done, we are ready to fetch the data stored on the Firebase real-time database in every 10 seconds.
  • RTDB.getInt() command is used to store the data in /test/int node. But before that we are checking the data type that is ‘int’(integer). If the data type of the message/data received from Firebase RTDB is ‘int’ only then the data will be stored inside the integer type variable i.e., “read_data”.

Fig. 19 Fetch data from Firebase RTDB

  • If the data type is other than integer then an error will be printed on the serial monitor.

Fig. 20

  • Similarly, we can read/fetch various types of data like float, string, array etc. from the firebase database.

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 ESP device is connected with Wi-Fi, you should see the data fetched from Firebase, printing on the serial monitor with a particular delay (as per the code instructions).

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.

Conditional Statements in Python

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.

What will you learn?

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.

Outline

  • To begin, you'll learn the basics of the if statement in its most basic form.
  • Next, you will understand why control structures require a way for grouping statements together into compound statements or blocks using the if statement as a model.
  • Finally, you'll learn how to write code that makes difficult decisions.

Let`s get started.

The if statement in Python

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:

  • This "expr" is an expression that is evaluated within the context of logic.
  • Python statements, like ‘statement’, must have an indentation of at least one space. (You'll understand why in a moment.)

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.

Using Blocks and Indentation to Group Statements

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.

Python indentation

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.

Is there a limit for nested blocks?

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.

What Do Other Languages Do?

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.

Which Is Better?

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.

Advantages:

  1. Clean, concise, and consistent: Python's usage of indentation is excellent.
  2. Writing code in languages that do not employ the off-side rule, the indentation of code is fully independent of the block definition and code function. While it's possible to create incorrect impressions by simply looking at code, it's also possible to create incorrect impressions by only looking at code.
  3. Code formatting guidelines should be followed anyway, thus using indentation assures that you are adhering to them. This sort of mistake is practically difficult to make in Python.

Disadvantages:

  1. The majority of programmers dislike being compelled to accomplish things in a specific way. Generally, they have firm beliefs about what they think is attractive and what they think is not. Because they don't want to be confined to a single choice.
  2. This can make it difficult for the Python interpreter to detect the level of indentation when indented lines are accompanied by a combination of space and tab characters. Then again, it is possible to configure editors in a way that prevents them from doing this. No matter what programming language you use, it is generally discouraged to use tab and space together in source code.

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.

The else and Elif Clauses

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.

How many elif clauses can be specified?

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:

Short-circuit evaluation of elif clauses

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.

One-Line if Statements

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.

The Ternary Operator in Python

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?

Statement "pass" in Python

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:

Conclusion

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.

Lists vs Tuples in Python

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.

What will you learn?

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.

What are lists?

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:

What are the characteristics of Python lists?

  • Lists are sorted.
  • There is no limit to what can be included in a list.
  • The index can be used to get at list items.
  • You can nest lists indefinitely.
  • Lists can be edited.
  • Lists are dynamic.

What do we mean by lists are sorted?

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:

Can any object be included in a list?

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.

What more can be included in a list?

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:

Can list elements be accessed by index?

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:

How is slicing applied in lists?

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.

What other features are available for slice?

  • You may discover some negative values in slice operation, therefore both positive and negative indices can be used. The following is an example:
  • One way to get around this problem is to just leave out the first and second indexes of the list, respectively:
  • A positive or negative stride can be specified:
  • Use the same syntax to reverse lists as you do strings:

Lists can also be nested

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.

Mutability of lists

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.

Modifying a Single List Value

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.

How to delete from a list

In order to remove a list item, use the del command:

Changing the Values of Multiple Lists

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:

Inserting elements to a list

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.

Deleting multiple elements from lists

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:

Incorporating Items into a List by Adding Them At The End

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:

Methods That Modify a 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.

Append()

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:

extend()

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:

insert()

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.

remove()

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:

pop(index=-1)

In a list, this function removes one item. There are two key differences between this method and remove():

  • Instead of removing the actual object, you specify its index.
  • It returns a value: the item that was deleted.

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.

Are lists dynamic?

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.

Python Tuples

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.

Defining and Using Tuples

Lists and tuples are nearly identical, with the exception of the following characteristics:

  • When creating a tuple, the elements are enclosed in parentheses (()) rather than square brackets (). ([]).
  • Tuples cannot be changed.

As an illustration of tuples in action, consider the following code sample:

What mechanism for tuples relate to that of lists?

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:

Why would you choose tuples over lists?

  • A tuple is faster to manipulate than a list in terms of program execution. Assuming the list or tuple isn't too large, you may not notice this.
  • Data modification is not always desired. It is safer to use a tuple rather than a list when the values in the collection are supposed to be constant throughout the program.
  • Another Python data type, known as a dictionary, requires an immutable value as one of its components. This can be accomplished with a tuple, but not with a list.

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:

Is it possible to create a tuple with just one item?

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:

Packing, assigning and unpacking of the tuples

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.

Tuple compound assignment

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.

Swapping in tuples

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.

Conclusion

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.

ESP32 Firebase

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.ComponentsDistributorLink To Buy
1ESP32AmazonBuy Now

What is Firebase?

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:

  • Firebase applications remain responsive even in offline mode. If any changes are missed during the offline mode, then after the connectivity is reestablished those changes will be automatically synchronized.
  • Firebase Real-time database makes it easier to access the database from a web browser or a mobile device.
  • Unlike hypertext transfer protocol requests, Firebase RTDB uses data synchronization which makes it possible to update the changes in the database within milliseconds.

Role of Firebase Realtime Database in IoT

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.

Project Overview

  • In this tutorial we are going to create a Firebase project with real-time database to read and store data with ESP32. Steps included to achieve the target are; creating a firebase project, storing data from ESP32 to firebase real-time Database, Reading data from firebase real-time database with ESP32.

Prerequisites

  • ESP32 development board
  • Arduino IDE
  • Necessary Library (Firebase ESP Client)
  • A Google account to access Firebase
 

Getting Started with Firebase

  • Create a project

The steps involved in creating a Firebase project are:

Fig. 2 Get started

  • Click on Create a project.

Fig. 3 Create a project

  • Assign a name to your project and accept the terms and conditions then click on the continue

Fig. 4 project name

  • Disable the “Enable Google Analytics” option and click on real-time.

Fig. 5 Enabling Google Analytics

  • Now your project is ready click the

Fig. 6 Project Created successfully

Authentication

    • Next we need to set the authentication methods for the app.

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).

  • Click on

Fig. 7 Authentication

  • You will be redirected to a new page, click on ‘get started.
  • There are multiple methods available to authenticate you account, as shown below.
  • Select any of the authentication method.

Fig. 8 Select authentication method

Next thing is creating a real-time database for the project.

  • Creating a Real-time Database
    • Click on the Real-time database given at the left sidebar.

Fig. 9 Real-time database

  • Then, click on Create Database.

Fig. 10 Creating database

  • Select your nearest location.

Fig. 11

  • Select the Start in test mode option and click on enable

Fig. 12 select location

  • Now your database is successfully created. You will be redirected to a new page containing the database URL.
  • Copy the URL and paste in your ESP32 code.
  • Now the next requirement is getting the API key.

Project API

    • Go to left sidebar and click on Project Overview and then project setting.

Fig. 13 Accessing project API key

  • Copy the web API key and paste in your ESP32 code.
  • That’s all about creating a Firebase account, project, and verification. Now, we are ready to interface the database and ESP32 module.

Programming with Arduino IDE

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:

  • Go to Tools >> Manage Libraries.

Fig. 14 manage libraries

  • Search for the Firebase ESP Client library in Library Manager and click Install.
  • We are attaching an image, where we are installing the Firebase ESP-Client (2.3.7 version) library.

Fig. 15 Install Firebase ESP Client Library

Arduino IDE Code ( To store data from ESP32 to Firebase Database)

//--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:

  • Adding network credentials
  • Inserting API key
  • Inserting Firebase project URL
  • Installing necessary library files

Code Description

  • The libraries we are using are:
    • The first one is h, which is used to enable the Wi-Fi module and hence wireless network connectivity.
    • Another library we are using is the h which is responsible for interfacing ESP32 and Firebase Real-time Database.

Fig. 16 Header files

  • We also need to add two helper libraries (required by the Firebase library).
  • The TokenHelper library is responsible for managing the token generation process.
  • On the other hand, the RTDBHelper library is responsible for providing helper functions to print data coming from the Firebase database.

Fig. 17 Helper libraries

  • Next, we need to insert the project API key obtained from the Firebase project setting page.

Fig. 18 Insert API key

  • Similarly, insert the RTDB (real-time database) URL.

Fig. 19 RTDB URL

  • Next, we are defining three firebase data objects, responsible for linking App to Firebase.

Fig. 20 Firebase Data Objects

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

Fig. 21 Enter Network credentials

  • Next, we are defining some variables to store integer value, status of sign up to firebase account, and delay element etc.

Fig. 22 variable declaration

 

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. 23 Initialize wifi module

  • 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. 24 Fetch/obtain the IP address

  • Here, we are assigning the API key to the firebase configuration.

Fig. 25 configuring API key

  • Similarly, the database URL is also assigned to the firebase configuration

Fig. 26 configuring database URL

  • Next, we are checking or verifying the Firebase sign-up status.
  • In the signup() function the last two arguments are empty, indicating the anonymous user.
  • If you have enabled different signup methods during the Firebase authentication method like Google account, Facebook etc then you need to add the respective credentials as argument.
  • The respective results of signup status will be printed on the serial monitor.

Fig. 27 sign up status

  • Next, you need to assign the callback function for token generation.

Fig. 28

Loop()

  • If, the sign up status is true (or Successful), then we are ready to send the data from ESP32 to Firebase Real-time database.
  • For demonstration purpose, we are sending integer value to the Firebase database. You can also send a string, float, array, sensor reading etc. as per your requirements.
  • senInt() command is used to send integer values. This command is passing three arguments first on is the firebase database object, the second argument is the database node path and the third one is the ‘value’ we are communicating to Firebase real-tie database.
  • Similarly, we can share string, float, or array etc.

Fig. 29 Loop() function

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. 30 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.
  • Go to https://console.firebase.google.com.
  • Select the project you have created.
  • Click on left sidebar and then click on Real-time Database.
  • A new page will open, containing the data uploaded from the ESP32.
  • We have attached an image below for your reference.
  • An integer value will be uploaded to the Firebase Real-time database in every 10 seconds.
  • In the image attached below, you can see three different values displaying. But only the integer value (in yellow color) is active and rest of the data is inactive.

Fig. 31 Result 1

  • The integer value is increasing by 1 in every 10 second.

Fig. 32 Result 2

  • Similarly, we can interface and upload sensor reading to the Firebase database.

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.

ESP32 BMP280 sensor Interfacing with ThingSpeak WebServer

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.ComponentsDistributorLink To Buy
1ESP32AmazonBuy Now

BMP280

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.

Technical specifications of BMP280

  • Operating voltage: 1.8 -3.3V DC
  • Communication protocols supported: SPI, I2C
  • Ultra low power consumption
  • Temperature accuracy: 1°C
  • Temperature range: -40 to 85°C
  • Absolute accuracy : 1 hPa

Components required:

  • ESP32 development board
  • Arduino IDE for programming
  • BMP280 sensor
  • Breadboard
  • Connecting wires

Interfacing BMP280 with ESP32

There are two methods of interfacing BMP280 sensor with ESP32 module:

  1. I2C protocol
  2. SPI protocol

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

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. 2 manage libraries

  • Search for the Adafruit BMP280 library in Library Manager and click Install.

Fig. 3 Install library

Getting I2C address

  • In order to interface your ESP32 with BMP280, you should know the I2C address of the sensor (BMP280).
  • To obtain the address of the I2C device, copy and paste the below attached code into your Arduino IDE.
  • Compile and upload the code.
  • Open the serial monitor at 115200 baud rate.
  • Now you should see the address of your I2C device printed on the serial monitor.
  • Copy the I2C address and paste in your final code (interfacing esp32 and BMP290 sensor).

#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);

}

Code (Interfacing and fetching sensor reading from BMP280 with ESP32)

#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);

}

Code Description

  • The first task is adding necessary header files.
  • We are using two libraries:
    • The Wire.h is used to enable I2C communication/interfacing.
    • The second library we are using is, Adafruit_BMP280.h is to control the BMP sensor and access its respective function.

Fig. 4

  • As we mentioned earlier, we are using the I2C protocol for interfacing BMP280 with ESP32. So we need to define the I2C GPIO pins.
  • In the ESP32 DevKit V1 development board, the GPIO_21 and GPIO_22 are the SDA and SCL pins for I2C communication.
  • Then a bmp280 object is declared for interfacing the sensor.

Fig. 5

Setup()

  • In the setup() function, we are initializing the serial communication at 115200 baud rate for debugging purposes.
  • The BMP280 sensor is initialized with bmp280.begin() function where we are passing the I2C address of the module as an argument.
  • Next, we need to check the status of the interface and the respective result will be printed on the serial monitor.

Fig. 6

Loop()

  • The next task is getting the sensor readings.
  • Here we are measuring three parameters, temperature, humidity and altitude.
  • A float type variable “temp” is defined to store the temperature readings observed from BMP280 sensor using readTemperature() function.

Fig. 7

  • Next, the altitude is measured using bmp280.readAltitude function.
  • We need to adjust the altitude to the local forecast using the multiplying factor.

Fig. 8

  • The bmp280.readPressure() function is used to obtain the pressure using BMP280 sensor.
  • BMP280 sensor readings will be updated every time with a delay of 1 second.

Fig. 9

Testing

  • Open your Arduino IDE and paste the above code.
  • 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. 10 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).
  • Now you should see the readings obtained from barometric pressure sensor.

Fig. 11 Serial monitor output

Uploading BMP280 Sensor data to ThingSpeak server

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.

Programming with Arduino IDE

Downloading and installing the required Library file:

  • Follow the link attached below to download the thingSpeak Arduino library:

https://github.com/mathworks/thingspeak-arduino

  • Open the Arduino IDE.
  • Go to Sketch >> Include Library >> Add .ZIP Library and select the downloaded zip file.

Fig. 13 Adding ThingSpeak library

To check whether the library is successfully added or not:

  • Go to Sketch >> Include Library >> Manage Libraries

Fig. 14

  • Type thingspeak in the search bar.

Fig, 15 Arduino IDE Library manager

  • The ThingSpeak library by MathWorks has been successfully downloaded.
 

Getting Started with ThingSpeak

  • To create and account or log in to ThingSpeak (operated by MathWorks) server follow the link: https://thingspeak.com/
  • Click on Get Started for free.

Fig. 16 Getting started for free

  • Enter the required details to create a MathWorks account as shown below:

Fig. 17 Create new account

  • If you have already created a MathWorks account, then click on Sign in.

Fig. 18 MathWorks Sign in

  • Create a channel by clicking on the New Channel

Fig. 19 New Channel

  • Enter the respective details in the channel.
  • Because we are measuring three parameters (temperature, pressure and altitude), hence we need to create three different fields in this channel.

Fig. 20 Creating channel and respective fields

  • Press “save” button.

Fig. 21 save the channel

  • After successfully saving the channel, a new window will open containing the channel details and Channel Stats.
  • In the same window, go to API Keys which contains the Write API keys and Read API keys.
  • Copy the Write API key and paste this in ESP32 Arduino code to upload the sensor readings on ThingSpeak server.
  • You can also customize the chart in Private View. Click on the icon present at the top right menu of Field Chart (in red box) to edit the chart.
  • Edit the details as per your requirements and click on save button to save the details.

Fig. 22 Field Chart Edit

  • Now your ThingSpeak channel is ready to communicate and save/store data.

Code (Arduino IDE)

// ------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();

}

}

Code Description

We are describing only the ThingSpeak server part as the BMP280 and ESP32 interfacing part has already been discussed in the above code description.

  • The style guard is used at the beginning to declare some function to be of “C” linkage, instead of “C++”
  • Basically, it allows the C++ code to interface with C code.

Fig. 23 Style guard

  • Add the necessary header/library files.
  • We have already discussed above how to download and add the ThingSpeak library file to Arduino IDE.

Fig. 24 Libraries

  • Enter the network credentials (SSID and Password).

Fig. 25

  • A Wi-Fi client is created to connect with ThingSpeak.

Fig. 26

  • Define timer variables.

Fig. 27

  • Add the channel number and API (Write) Key. If you have created only one channel then the channel number will be ‘1’.

Fig. 28

Setup()

    • Initialize the Serial monitor with a 115200 baud rate for debugging purposes.

Fig. 29

  • Set ESP32 Wi-Fi module in station mode using mode() function.
  • Enable ESP32’s Wi-Fi module using begin() function which is using SSID and password as arguments.
  • Wait until the ESP32 is not connected with the wifi network.

Fig. 30

  • Initialize the ThingSpeak server using begin() function that is passing client (globally created) as an argument.

Fig. 31

 

Loop()

  • We are defining three float type variables to save temperature, altitude and pressure measurements respectively.

Fig. 32 Sensor readings

  • Setting up the ThingSpeak fields for respective sensor measurement. The various sensor readings are passed as arguments inside the ThingSpeak.setField() function with there respective filed number.

Fig. 33 setting respective Fields

  • writeFields() function is used to write data to the ThingSpeak server. This function is using the channel number and API key as an argument.

Fig. 34

  • Return the code 200 if the sensor readings are successfully published to ThingSpeak server and print the respective results on the serial monitor.

Fig. 35

Results

  • Open your Arduino IDE and paste the above code.
  • Compile and upload the code into the ESP32 development board.
  • Before uploading the code make sure that you have selected the correct development board and COM port.
  • Make sure the Wi-Fi network to which your ESP device is supposed to connect is active.
  • Open the serial monitor at a 115200 baud rate and press the EN button from ESP32 development.
  • Once your ESP32 is connected with the wi-fi network, open the channel you have created on the ThingSpeak server.
  • Now you see the sensor readings displayed on their respective fields.

Fig. 36 ThingSpeak server

  • You can also compare the data displayed on the server with the serial monitor.

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.

Introduction to LED PCB

Hello everyone. Today is a great day that we are going to put our focus on another type of PCB. So far in the previous articles, we have looked at high speed, metalcore, high density interconnect and the ceramic types of PCBs. In this article, we are going to introduce another type of PCB that might find great use in your day-to-day interaction with the printed circuit boards. it is very important for a designer to take note of how PCBs have evolved and how they have become an important aspect in the design of successful electronic devices. It has become hardly difficult to come across any time of an electronic device that does not involve the use of printed circuit boards.

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.

Introduction to the LED PCBs

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.

  • The LEDs are laid directly in the circuit layer where they are mounted.
  • The heat that comes out of the LED is quickly linked to the substrate layer for dissipation. This is done through the insulation layer then dissipated through the substrate layer.
  • Copper, aluminum and iron are the most used thermal conductive layer material since they are readily available.
  • The iron core is mostly used in motor high-end PCBs that have a lot of heat dissipation.

How to order LED PCB online?

There are numerous online PCB companies, where we can place the LED PCB order. We are going to take the example of PCBWay Fabrication House, a well renowned PCB Manufacturing House. They have an excellent support team, and it's recommended to first discuss your PCB design with the team, they will guide you at every step. So, follow these steps to place an order of LED PCB on PCBWay:
  • First of all, create an account on the PCBWay official site.
  • After that click on the PCBWay Calculator, which is an excellent tool to get the quote for your PCB order.
  • As you can see in the above figure, I have selected Aluminium PCBs, as LED PCBs are normally aluminum PCBs to avoid heat dissipation.
  • Now click on Calculate and get the quote for your order.

The LED PCB working principle

  • The LED is mounted on the surface of the circuit layer and the heat that is generated when the PCB is under operation is quickly passed to the metal base layer via the insulating layer.
  • This heat is then passed out by the metal base layer to achieve the purpose of heat dissipation of the device.
  • See the attached diagram for a better understanding of the process;

LED PCD structure

Circuit 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.

Insulating layer

This layer is the core technology behind this type of boards and plays greater roles in the conduction insulation and bonding of the layers.

Metal substrate layer

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.

Types of the LED PCBs

The single layer LED PCB

This consist of the substrate layer together with a conductive layer. A solder mask together with a silkscreen offer protection functions to these layers.

  • This type of the LED PCB does not have any circuit layer on the back side.
  • Their structure is very thin and they are very weightless.

Double layer PCB

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.

  • Double layered PCBs are durable since this type of circuit layer can withstand the high currents applied and it has the best heat dissipation mechanism.

Assembly methods of the LED PCB

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;

Surface-mount assembly

This method involves mounting the electronic components directly into the board copper layer.

  • the process is highly automated and offers flexible connections and offers spaces for high density connections.
  • They play great roles in circuitry that require high connections and accuracy.

Through-hole assembly

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.

  • The process involves a lot of inspections to make sure that the great accuracy and the effectiveness are achieved.
  • This method off course provides a strong board with long durability.

Considerations while designing the LED PCBs

  • Ideal board design; you must figure out which is the ideal board design that you should incorporate. In engineering everything starts with the design. It is the first step that comes in.
  • Picking the proper orientation; when we talk about orientation, we are after how the flow of the circuit is achieved from one end to the other. The way in which the data and the electricity flow in the circuit is what we are referring to us the orientation.
  • Component placement; in addition to the circuit and the obvious LED, there are many other components that form the printed circuit boards. these components include the resistors, the capacitors, etc. the components should be placed such that they avoid the solder side of the board were solders lie behind the through hole side of the board.
  • Avoid placement of the components on the PCB outline; this will help you manage the board better and also ensure that the design is sturdy and very reliable.
  • Vias should not be placed at the end of the STM Pads; vias allows the placement of circuits in tow or more layers if the PCB boards. these vias can go through the surface of the top layer through to the bottom layer. Avoid passing the via through the pads of the surface mounted devices since this will weaken the components.
  • Definition of the net width design; due to consumption of different current in the circuits, the design paths will vary with the size of the tracks and this will also affect the net width of this design outcome.
  • Cost optimization and the budget issues; this is how the overall budget of the designed PCB will go up to. Therefore, this must also be considered when coming up with the LED PCB.

Industrial applications of the LED PCBs

Consumer lighting

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.

Consumer electronics

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.

Telecommunications

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.

Transportations

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

Medical lighting and the medical equipment lighting that are used for medical examination and surgery often use this type LED PCBs.

Benefits of this LED PCBs

  1. Reduced consumption of power
  2. More efficiency compared to the traditional boards.
  3. They are smaller in size
  4. This type of board is mercury free
  5. It is radiofrequency free
  6. It is much environment friendly
  7. Cheap and this implies reduced cost.
  8. It has a longer life compared to others.

How to use Sets in Python?

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.

What will you learn?

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.

What is a set?

The following features describe the built-in set type in Python:

  • Sets are not in any particular order.
  • Each element in the set is unique. It is not permitted to use duplicate elements.
  • A set's elements can be changed, but the set's elements must be immutable.

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:

  • set() takes an iterable as a parameter. It creates a list of things that should be included in the collection.
  • Even though the items in curly brackets are iterable, they are added into the set intact.

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:

What is a bool?

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.

Determine the size and composition of your group.

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:

Working with a Set

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.

Using Operators vs. Using Methods

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.

Methods and operators that are available

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.

union

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.

intersection

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.

Difference

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:

Symmetric difference

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:

Making Changes to Sets

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.

Methods and Operators for Augmented Assignment

Each of the aforementioned operators has an augmented assignment form that can be used to change a set. Each person takes a different approach.

Update

x1 |= x2 [| x3 ...]

The union can be used to change the state of a set.

Intersection

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:

Difference_update

x1 -= x2 [| x3 ...]

Make a difference in a set.

x1.difference update(x2) and x1 -= x2 remove components found in x2 from x1:

Symmetric_difference_update

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:

Other Set Modification Methods

Aside from the augmented operators listed above, Python has several other ways of modifying sets.

Add

Adds a new element to a collection.

x.add(elem>) appends elem> to x:

Remove

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:

Discard

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:

Pop

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:

Frozen Sets

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:

Frozensets and Augmented Assignment: A Deep Dive

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:

How do we know if an element in a set exists?

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.

  • in: Returns True if the object on the left is contained within the object on the right.
  • not in: Returns True if the left-hand item is not included in the right-hand object.

Calculating a set's length

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.

Conclusion

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.

Edge Computing vs Cloud Computing

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.

Edge Computing vs Cloud Computing

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.

What is Edge Computing?

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%.”

What is Cloud Computing?

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.

How Do They Work?

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:

  1. Cloud
  2. Edge device
  3. Device

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:

  1. Cloud with data centers where is processed and stored
  2. Device (like a laptop, smartphone, tablet) where data is produced

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.

Advantages of Edge Computing

The following are the main advantage of edge computing.

1: Improved Performance and low latency:

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.

2: Better Control Over Data:

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.

3: Reduced Cost:

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.

4: Data sovereignty:

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.

5: Scalability:

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.

Advantages of Cloud Computing

The following are the main advantages of Cloud Computing:

1: Backup and Disaster Recovery

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.

2: Low maintenance cost

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.

3: Pay-as-you-go service

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.

4: Flexibility

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.

5: Mobility

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.

6: Automatic Software Update

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.

Edge Computing vs Cloud Computing – Which one is better?

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.

What the Future Holds?

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.

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.

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