Getting Started with Raspberry Pi Programming Series

to our new beginner’s course on Raspberry Pi. This course is appropriate for anyone using either a traditional Raspberry Pi board or the new Raspberry Pi 400 board that includes an integrated keyboard and display. Learning how to code, building robots, and doing plenty of other strange and exciting things are all possible with this low-cost computer setup. The Raspberry Pi can do everything a computer can do, from surfing the web to viewing movies and music, and playing video games.

Raspberry Pi is much more than a modern computer. It`s created to educate young people on how to program in languages such as Scratch and Python, and it comes with all of the major programming languages pre-installed. The world is in desperate need of programmers now more than ever, and Raspberry Pi has sparked a new generation's interest in computer science and technology. Raspberry Pi is used by people of all ages to build intriguing projects ranging from old-school gaming systems to internet-connected weather equipment.

Where To Buy?
No.ComponentsDistributorLink To Buy
1Raspberry Pi 4AmazonBuy Now

What are the aims of this course?

In this course, we'll learn how to make games, build robots, or hack all kinds of fantastic projects. The Raspberry Pi 4 Model B will be covered in this course. In the event that you're working with a different model of Raspberry Pi, don't be worried. whatever is taught here can be applied to any other model in the family.

What is this mini-computer?

It is a small computer about the size of a credit card that can run the Linux operating system. It uses a "system on a chip," which combines the CPU, GPU, RAM, USB ports, and other components into a single chip.

To distinguish it from traditional computers that conceal their internal components behind a casing, the Raspberry Pi's ports and functions are fully exposed, a protective case is available to buy. If you want to know how different computer components work and where to put the various peripherals, this is a great resource.

Features

All Raspberry Pi models share one feature in common:

  • Software written for one model can be used on another, as they are interchangeable.
  • Raspberry Pi operating system can even run on a pre-release Model B prototype. Although it will take longer, still run.

With this, what are you able to accomplish?

Now you've got a little machine that runs a lot of free software, so that's good. Exactly what can you do with it? Fortunately, I've got a simple and fun Python project that I used to teach middle school children in a coding lesson.

  • It's possible to create a weather station, a calculator, a gaming gadget, and a lot more out of the same thing. If you have a Raspberry Pi, you can even make a customized espresso machine that is secure like a Raspberry Pi locked door lock, as this one.
  • Can be used as a game server
  • Controller for robots
  • Webserver
  • Cryptocurrency Mining

Advantages of using this mini-computer

  • Low price
  • High computing power in a small board
  • Numerous interfaces
  • Linux and Python are supported

Disadvantages

  • Windows cannot be installed on the computer.
  • Inconvenient to use as a Desktop PC.
  • There is no graphics processor.
  • Internal eMMC storage is not present.
  • We can't attach external RAM as in a normal computer.

Components in a Raspberry pi

The Raspberry Pi features a number of parts that can be used to control the Raspberry Pi as well as other devices. The following ports will be available on your Raspberry Pi:

  1. System-on-chip

The majority of the Raspberry Pi's system resides on an integrated circuit, which is what the term "system-on-chip" refers to. Included in this is the CPU, which is referred to as a computer's 'brain,' as well as the graphics processing unit (GPU).

  1. Random-access memory (RAM)

A brain is useless without memory, therefore you'll notice another chip to the side of the SoC, tiny and black plastic, like a cube where RAM is located. When you're working on a Raspberry Pi, the RAM stores your work; it's only when you save it to the microSD card that it's written to the microSD card. The volatile and non-volatile memories of the Raspberry Pi are made up of these components. When the Raspberry Pi is turned off, the volatile RAM loses its contents, however, the non-volatile microSD card retains them.

  1. Raspberry pi`s radio module

A metallic lid covers the Raspberry Pi's radio component, which allows it to communicate wirelessly with other devices. In actuality, the radio has two main functions. Wi-Fi and Bluetooth are built-in, so you can use them to communicate with your computer and other nearby smart devices, sensors or cellphones.

  1. power management integrated circuit (PMIC)

Just behind the middle row of USB ports, an additional black, plastic-covered chip is seen towards the board's bottom border. The USB controller manages the four USB ports. The network controller is positioned next to this chip. An integrated circuit (PMIC) is also located on the upper left side of this board. It is in charge of converting power from a USB port to the precise voltage that the Raspberry Pi needs.

  1. Ports for connecting USB devices

The circuit board contains a variety of ports, beginning with four ports in the right side of the bottom edge. You can connect any USB-compatible device to your Raspberry Pi using these ports, including keyboards, mice, digital cameras, and flash drives. One of the two types of USB ports is a USB 2.0 port, which uses version two of the USB standard; the other is a USB 3.0 port, which uses version three.

  1. Ethernet port

There is an Ethernet port. Using an RJ45 cable, a Raspberry Pi can be linked with a wired computer network via this port. You'll notice two LEDs at the bottom, which indicate the connection is operational.

  1. Raspberry Pi AV jack

There is a 3.5 mm audio-visual jack. Connecting to amplified speakers rather than headphone jacks improves sound quality, but the headphone jack can still be used. Audio and video signals can be transmitted using the TRRS (tip-ring-ring-sleeve) adapter, which connects the 3.5 mm AV jack with projectors, tv, and other displays that can receive composite video signals.

  1. Camera connector

The camera serial interface (CSI), or camera connector, as it is most commonly called, is located above the AV jack and has a strange-looking plastic flap that may be pulled up (CSI). This allows you to connect a camera, which you'll learn later in this course.

  1. micro-HDMI ports

There are two micro HDMI connections available, which are a scaled-down version of the connectors seen on gaming consoles, set-top boxes, and televisions. Multimedia denotes that it can transport both audio and video information, and high-definition indicates that the quality will be excellent. A computer monitor, television, or projector will be needed to connect the Raspberry Pi to these adapters.

  1. Type-C port

The port above the HDMI ports is where you'll plug in the Raspberry Pi's power supply. USB Type-C ports can be found on smartphones, tablets, and other mobile devices. Instead of a standard mobile charger, employ the certified Raspberry Pi USB Type-C Power Supply for the best results.

  1. Display connector (DSI)

There is a strange-looking connector at the top of the board, which appears to be the camera connector at first sight, but it's not. It is for usage with a Raspberry Pi Touch Display.

  1. Raspberry Pi’s GPIO header

In two rows of 20 pins each, you'll find 40 metal pins along the right edge of the board. To communicate with peripherals such as LEDs and buttons to temperature sensors, joysticks, and pulse rate monitors, the Raspberry Pi includes a function known as GPIO (general-purpose input/output).

  1. Raspberry Pi’s microSD card connector

The Raspberry Pi has one more port, the micro-SD connector, which is on the other side of the circuit board. The MicroSD card is inserted here and you'll find all the files you've saved and installed as well as the operating system that makes your Raspberry Pi work.

What can you expect from the Raspberry Pi?

  • 1GB of RAM, and dual-band 802.11ac wireless LAN
  • This device has a Bluetooth 4.2 connection; it also has four USB 2.0 connections, an HDMI port, a composite video port, and 40 GPIO pins.
  • 3D graphics, Camera interface (CSI), Display interface, and Micro SD card slot (DSI)

What operating system is it using?

Unfortunately, the Raspberry Pi lacks the ability to run either Macintosh or Windows. Instead, it uses Raspbian, a Linux distribution. Installing Raspbian on your own micro-SD card is also possible using the NOOBS installation. You'll see this loading screen when you insert in the microSD card with Raspbian installed and turn on the Raspberry Pi.

As you've seen, the desktop on your huge PC looks exactly like the one you are used to. A web browser, terminal, picture viewer, calculator, and a slew of other tools are all included by default.

Requirements before you begin

The Raspberry Pi is the heart of your project, but without a power supply or storage, it won't be able to go very far. To get started, you'll need the following:

  1. The Raspberry Pi

      1. A Power Supply

The power supply standard for the Raspberry Pi 4 has been upgraded from microUSB to USB-C, which is an improvement. Powering your Raspberry Pi is best done with a dedicated power adapter from the Raspberry Pi Foundation.

      1. MicroSD Card

The later Pi models use microSD cards instead of the normal SD cards that were used in the original Pi models A and B. However, not all SD cards function correctly, therefore it's preferable to acquire a pre-loaded operating system with the original Raspberry Pi microSD card or a tested suitable card, such as the SanDisk Ultra 32GB.

      1. Case

This is technically optional, but we strongly advise it. It is a good idea to use a case to protect your bare board rather than leaving it exposed. The FLIRC case has a built-in heatsink, making it an excellent choice for older models of the Raspberry Pi.

      1. Mouse, Keyboard, and HDMI Cable

You can control your Raspberry Pi using a keyboard and a mouse. Raspberry Pi can utilize almost any USB-connected keyboard and mouse, wired or wireless. However, don`t use 'gaming' keyboards with flashing lights since they consume too much power to be used successfully.

USB gamepads are also necessary when you are building consoles like a gaming rig, therefore, don't forget about them.

First time set up

We are now going to set up our minicomputer therefore follow these simple steps to get yours up and running:

  • An SD card should be inserted into the SD card slot on the pi board. For the time being, we strongly advise you to stick with Raspbian until you are more comfortable with its features.
  • Use one of the USB ports to connect a mouse and a keyboard to the system. When using 'gaming' mice or other high-end equipment that requires software and drivers, it might waste power and place additional strain on the system. Just use 'plug-and-play' equipment to keep things easy and hassle-free.
  • Using the HDMI port, connect a monitor. Connect the monitor to a wall outlet, and then turn the power on and off as necessary. If you turn on the Raspberry Pi right now, nothing will happen. Adapters for non-HDMI monitors that don't impede access to the USB ports should be used.
  • In order to use Ethernet instead of Wi-Fi, you will need to connect an Ethernet cable as well. The speaker or headphones should be plugged in as well if you wish to hear sound from the speakers. However, to get the Raspberry Pi up and running, you don't need either of these items.
  • Finally, insert the micro-USB cable into the power source and into the wall socket. The Raspberry Pi's red LED will light up, and you'll be able to see it booting up on the monitor. Once you get back to your computer, you'll see a desktop screen.

Congratulations! You've successfully assembled your Raspberry Pi! I hope you have something like this:

Conclusion

At this point in the course, we've learned about the Raspberry Pi computer and what each component does. Our minicomputer has now been set up, and in the next tutorial, we'll learn how to use the python programming language with the Raspbian operating system.

While Loop in Python

Welcome to the next lesson of our python programming class. In the last session, we looked at the use of If-else statements and created simple programs to demonstrate the concept. While loops are another type of conditional statement, and in this tutorial, we'll look at how they're used.

What will you learn?

In this article, you'll learn how to prematurely exit a while loop, a Python control structure for endless iteration. You will also learn how to write conditions in a single line to produce short and readable code.

Iteration in while loop

The term "iteration" refers to the practice of repeatedly running the same piece of code. A loop is a type of programming structure that implements iteration.

Both indefinite and definite iterations are recognized as valid programming constructs. Infinite iteration doesn't specify how many times the loop will be executed. As long as a condition is met, the chosen block will be executed again. An iteration that uses a definite iteration specifies how many times it will run the selected block.

What are the use cases of while loops?

  • User Input: When we request user input, we must verify that the value entered is correct. We can't reasonably predict how many times the user will enter an invalid input before the software can proceed. As a result, a while loop would be ideal in this situation.
  • Search: another excellent use case for a while loop is looking for an element in a data structure because we can't predict how many iterations will be required to get the target value. A while loop, for example, can be used to build the Binary Search algorithm.
  • Games: A while loop can be used in a game to keep the game's primary logic running until the player loses or the game is over. A while loop is an excellent solution because we can't predict when something like this will occur.

The while Loop

While Loops are used to iterate over the same code block for an unlimited couple of iterations until a condition is met.

While Loops are used to repeat the same code block indefinitely until a condition is met, if a given Boolean condition is completed at the end of the block, the "do while" loop will continue to run a provided block of code, or it will not.

Only one statement is required for the Do While Loop to terminate. However, the While loop may terminate with no statements executed, while the While loop may terminate with statements executed.

This type of control flow statement specifies iteration, allowing the code to be executed again and again. When we know how many times we want to run a code section, a for loop comes in handy.

Here, we'll explore how the Python while statement can be used to build loops. We'll begin with a simple design and gradually add to it.

Listed below is a basic while loop's structure:

Block denotes an execution block that will be repeated over and over again. As with an if statement, this is indicated by indentation.

Indentation is used to define blocks in all Python control structures. See the previous tutorial on grouping statements for a refresher.

In the controlling expression, expr, variables are initialized and updated during the loop's execution.

In this case, the expr parameter is evaluated first in a Boolean context. If this is true, then the loop's body is run. The body is executed when the expression returns to true. The program moves to the topmost statement following the loop body if the condition in expr is false.

Take a look at the following loop:

This is what we're seeing in this case. n starts as five. The loop body is run because n > 0 is true. n is greater than 0. Line 3 of the loop body prints the value of n after decreasing by 1 to 4 places.

The expression is re-evaluated from the top of the loop after the loop's body has completed. Because it's still true, the code in the body runs once again, printing 3 on the screen.

It goes on like this until n equals zero. That is when the expression is tested, and the loop is broken. The program would typically restart execution from the top most statement following the loop's body, but there isn't one here.

It's worth noting that the controlling expression of the while loop is tested first. If the loop body is false at the start, it will never be executed:

Because of this, n is set to zero when the loop is encountered. There is no need for the loop body because the controlling statement n > 0 is false.

Below is another while loop that doesn't use the numeric comparison:

Lists evaluated in a Boolean context are either truthy or false, depending on whether or not they contain elements. As long as there are elements in it, a is true. The loop terminates when the list is empty and all items have been deleted using the pop () method.

Break and continue Python

The whole body of the while loop is executed each time it is executed. Python has two keywords, break and continue, to prevent a loop from repeating itself.

This statement breaks a loop completely and immediately in Python. Python performs the next statement in the program after the loop body, which ends the current loop iteration. As soon as an expression is evaluated, it is evaluated again to see if the loop will continue or end.

The following diagram illustrates the difference between the statements "break" and "continue":

Break.py is a Python script that demonstrates the use of the 'break' statement:

Using a command-line interpreter to run break.py yields the following results:

The break code is executed when n reaches the value of 2.0. Execution immediately moves to the print () call on line 7 after complete termination of the loop.

A continue statement replaces the break in the next script, continue.py.

The output is something like this:

When n is 2, the loop is terminated by the continue statement. Thus, the number 2 is omitted. The condition is re-evaluated at the top of the loop, and it is still true. As before, the loop terminates when n equals 0.

Else condition

While loops in Python can have an optional else condition at the end. Unlike most other programming languages, Python has this unique functionality. Syntax in the form of a diagram:

The other clause's further statements will execute when the while loop completes, as shown in this example.

You may be wondering, "How is that useful?" at this point. After the while loop, you could insert the following statements directly after it:

What’s the difference?

Additional statements will be run regardless of whether or not the while loop is terminated.

An else condition will only execute if the loop stops "by exhaustion"—that is until the controlling condition is false; otherwise, no subsequent statements will be executed. If a break statement is used to break the loop, the else condition is not executed.

Think about the following scenario:

Variable n becomes 0, and therefore n > 0 became false. The loop's block runs until the condition is exhausted. The else clause is executed since the loop is allowed to run its course.

Consider the following example to see the difference:

The else condition is not executed because the loop is prematurely interrupted by the break.

The term else may appear to have a different meaning in the while loop then it does in the if statement. In order to make it more understandable, you may try one of the following:

  • You can see it as an "if" statement that repeats itself over and over, with the "else" clause ultimately being performed when the condition fails.
  • It's best to think of everything else as if it were a break so that the following block is executed if there was no break.

You are free to disregard either of these interpretations if you don't find them helpful.

In what situations is else condition useful?

If you need to find a certain item on a list, this is a common scenario. If the item is discovered, you can use the break to leave the loop. Also, else condition can contain code to be run if the item is not found:

Infinite Loops

Assume you've written an infinite while loop. This may sound weird, right?

As an illustration, consider the following:

Ctrl+C, a keyboard interrupt, was used to end this code. There was no way this could have ended. The vertical ellipsis represented in this output has taken the place of several output lines that were omitted.

We're all going to be in a lot of trouble if True can ever be false. On the other hand, False creates an infinite loop that might conceivably run indefinitely.

However, this is a typical pattern, and it may not sound like something you would want to do. Code for a service that accepts service requests and operates indefinitely is a good example. In this situation, "forever" implies until you turn it off or the universe reaches the point of no return.

Alternatively, keep in mind that the break statement can be used to exit a loop. Instead of evaluating a condition at the top, conditions recognized within the loop body may make it easier to terminate the loop.

If you'd rather, you can use pop () to delete each item in the list in turn, as illustrated above:

Not a is true when a is empty, and the break statement terminates the loop.

Multiple break statements can be specified in a loop:

Breaking out of the loop at various points rather than trying to define every possible termination condition in the loop header is often preferable in situations like this.

Infinite loops can be convenient in some circumstances. It's important to remember that the loop must be stopped sometimes, or it will become limitless.

Nested while loops

Generally, it is possible to nest Python control structures inside one another. Nested conditional statements, for example, are possible: if/elif/else.

The following code shows how a while loop can be nested inside of another while loop:

Nested loops are affected by statements like "break" or "continue" since they are nested within each other.

Loops can be nested in and out of the if/elif/else statements and the other way around.

All Python control structures can be mixed and matched to your heart's content. That is precisely how it should be. You can only nest while loops a maximum of four deep, which would be unpleasant if there were unforeseen constraints like these: 'A while loop cannot be embedded within an if statement.' Trying to recall them all would be nearly impossible.

Poor programming language design is evidenced by the presence of seemingly random numerical or logical constraints. Python, fortunately, does not have any.

One-Line while Loops

You can specify a while loop in the same way you do an if statement: on a single line. If the loop body has many statements, semicolons (;) can be used to divide them:

To be clear, this technique only works with simple declarative. Compound statements cannot be combined in a single line. As a result, you can write an if statement on the same line as a while loop:

You can also do this:

Note that PEP 8 forbids the use of numerous assertions on a single line. "Since this is a bad idea anyway, you generally shouldn't do it too often.

Conclusion

The Python while loop was used in this tutorial to demonstrate indefinite iteration. You can now create sophisticated and straightforward while loops, thanks to the knowledge you've gained thus far. The else clause can be used in conjunction with a while loop to handle endless loops. If you've followed along, you should understand how to run the same code repeatedly. The next lesson will cover iteration with for loops with an explicit limit on the number of iterations.

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.

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