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