Math Functions and Operations in Python

Hello friends, I hope you all are doing great. This is the 7th lesson of our Python tutorial. We were introduced to Python numbers in the previous chapter and learned how they are utilized with expressions, so we have a good understanding of math operations.

We'll go over a couple more arithmetic functions and complex numbers in this lesson. I will try my best to keep it simple. Let's get started!

Python round function

You can work with numbers in Python using a few built-in functions. Three of the most common will be discussed in this section:
  • Rounding to a specific number of decimal places can be done with round().
  • abs(), which returns a number's absolute value.
  • pow(), which raises a number to a certain power

As an added bonus, you'll discover how to test for the existence of an integer value using a floating-point number.

It's possible to round a number with round():

Round() acts strangely when the integer ends in .5.

2.5 is reduced to 2, and 3.5 is increased to 4. We'll dig a little deeper into this because most people assume that a decimal number ending in .5 is rounded up.

Python 3 uses a mechanism known as rounding ties to round numbers. The term "tie" refers to any number with a fifth digit. 1.37 is the only one that is not a tie.

One decimal place left of the last digit is all that is needed to break even integers down into their constituent parts. You round to the nearest whole number if the digit is even in this case. When an odd-numbered digit is entered, you round up. Hence, a reduction of 2.5 rounds to 2 and a rise of 3.5 rounds to 4.

When dealing with floating-point numbers, the IEEE advises against using anything but rounding ties because of their reduced influence on procedures involving a large number of values.

IEEE – what is it?

With over 350,000 members from over 150 countries, the IEEE is the biggest technical professional society in the world. An organization committed to the advancement of electrical and electronic engineering and computer science theory and practice has been established.

IEEE 754 is an IEEE-maintained standard for using floating-point integers on computers. It was first published in 1985, and is still widely used by hardware manufacturers today.

In order to round a value to the desired number of decimal places, a second argument to round() might be utilized.

3.142 and 2.72 is the result of rounding the numbers 3.14159 and 2.71828 to three decimal places, respectively.

There must be an integer as the second argument to round() Python raises a TypeError if it isn't.

In some cases, round() does not get the answer quite right:

Because it is exactly halfway between 2.67 and 2.68, the number 2.675 is a tie. The expected result of round(2.675, 2) would be 2.68, but Python produces 2.67 instead since it rounds to the nearest even value. Errors in floating-point representation are to blame, not a rounding problem ().

Floating-point numbers are irritating, but this isn't a problem specific to Python. C/C++, Java, and JavaScript are all affected by the same flaws in the IEEE floating-point standard.

Although floating-point numbers have a small amount of error, the outputs for round() are still useful in most cases.

How do we find the absolute value using abs()?

If n is positive, n`s absolute value is n, and if n is negative, it is -n. Examples include 3 and 5, which each have their own distinct absolute values.

In Python, abs() is used to get the number's absolute value.

A positive integer of the same type as its input is returned by the abs() function every time it is invoked. To put it another way, when it comes to absolute values of integers and floating points, they are both always positive integers.

How do we use pow() to raise a power?

The ** operator was previously used to raise a number to a power. If you want, you can use the pow() function instead.

There are two arguments to pow().

In order to raise 2 to its exponent 3 in the following example, we can utilize the pow() function.

It is possible to have a negative exponent in pow():

** and pow() are two different functions, so what's the difference between them?

With a third optional input, the pow() function takes the first number as a modulo, and then computes the second number's power. If (x ** y)%z is what you're looking for, then Pow(x, y, z) is the same thing. To illustrate, consider the following scenario:

Eight is the result of raising two to the power of three. 8 % 2 returns reminder 0 since 2 divides 8 by itself.

Check if a Float Is Integral

Functions like .lower(), .upper(), and .find() may be familiar to you. There are also ways for converting between integers and floating-point numbers, as well.

There is a handy number approach that isn't utilized very often .is_integer() method of floating-point numbers. In this case it returns True, otherwise it returns False.

.is_integer() can be used to verify user input. When placing an order for pizza, you'd need to make sure that the customer entered the correct amount of pizzas in the order form.

Using the built-in functions round(), abs(), and pow() does not require any additional imports. But these are just three of the many functions available in Python for manipulating numbers.

Check Your Understanding

Add two decimal places to an input field in order to display a user-specified number in two decimal places. You'll see something like this as the output.

Solution:

In order to get user input, use input():

A last blank space can be seen at the conclusion of the prompt string, for your convenience. This guarantees that the colon in the prompt is separated from the user's input when they begin typing.

It is necessary to first convert the input() value to float before rounding it:

If the user input string does not contain a numerical number, the above code thinks that it does.

The value can now be rounded to two decimal places using the round() method.

To round an integer, pass it as the first parameter to the round() function. You can choose how many decimal places you wish to round to in the second input field.

Using an f-string, enter the rounded number to print the result.

Even though round() is fantastic, if you're only interested in rounding numbers for display purposes, you'd be better off utilizing the methods mentioned below.

Formatting language.

Languages for document formatting determine how printed text and visuals should be organized. Text formatting notation, page description languages, and, most broadly, markup languages are all subclasses of markup languages that specify the intended purpose of a document.

How to print python numbers in style.

When a user requests a list of numbers, they must first enter those values into a string. To do this using f-strings, you can use curly brackets to surround the variable assigned to a number:

A simple formatting language is supported by those curly brackets, which can be employed to change the appearance of the final formatted string.

Instead of using curly brackets to format n to two decimal places, use n:.2f instead.

An extra colon (:) indicates that everything following it is part of a special formatting rule. As you can see, the.2f standard is used in this case.

A fixed-point number is displayed in Python using .2f since the .2 will truncate the result to the nearest tenth of a decimal place. If the number is less than two decimal places, there will still be two decimal places displayed.

The answer to n:.2f is 7.12 when n is 7.125. Python rounds to the nearest integer, just like round() does, when it comes to formatting integers in strings. If you substitute n = 7.126 for n = 7.125 in n:.2f, you get 7.13:

Replace .2 with .1 to get the decimal rounded up to one place:

Your chosen decimal place count is always displayed in the fixed-point number.

The , option allows you to use a comma for separating the integer portion of huge integers by thousands:

The , should be included before the .in in your formatting specification when rounding off or grouping by thousands.

Currency values can be displayed by using .2f.

% Is a useful option for displaying percentages.

Using the percent option at the conclusion of your formatting specification is mandatory, and you cannot use the f option with it. As an illustration, .1% shows a number with one decimal place exactly:

Check Your Understanding

Group thousands by commas when printing the number 150000. There should be two decimal places on all currency displays, and the dollar sign should always appear first.

Solution:

One step at a time, let's build up our F-string.

F-string 150000 without any formatting looks like the following:

Set yourself prepared to add the formatting specifiers by putting this in place first.

It is possible to display the value as float by using a colon (:) after both 150000 and letter f.

A precision of six decimal places is the default setting in Python. There should only be two decimal places in your currency, so you may just add . 2 between the : and the f:

Make sure the number is shown in its entirety by including a colon (:) after the number and before the period (.).

There should also be dollar signs ($) to indicate that the price is in US dollars.

Complex Numbers

Because it is so uncommon in other programming languages, Python has support for complex numbers right out of the box. Python's support for complex numbers, while uncommon outside of scientific computing and computer graphics, is a major plus for the language.

It is common knowledge that a complex number contains two components: a real component and an imaginary component.

When writing complex numbers in Python all that is required is to write the real component, the plus sign, and then the imaginary section with the letter j after them.

This is what we see when we look at the number n in Python's code:

Thus, the output is no longer misinterpreted as a mathematical expression when it is shown in this way.

The real and imagistic components of an imaginary number can be retrieved using the .real and .imag characteristics:

Even though the real and imaginary components were defined as integers, Python nevertheless delivers them as floats.

The conjugate of a complex number can be found using the .conjugate() method.

Find the complex number whose real part and imaginary portion are the same as the opposite-sign complex number's conjugate.

Unlike .conjugate(), the .real and .imag properties do not require parentheses following their names.

Instead of calculating a complex number, the .conjugate() method returns data about the number, while the .real and .imag methods just provide information.

In object-oriented programming, the distinction between methods and properties is critical.

Float and integer arithmetic operators, with the exception of the floor division operator (//), all function with complex numbers. For the sake of keeping things simple, complex arithmetic's mechanics are outside the scope of this article. Rather, consider the following arithmetic examples that demonstrate the use of complex numbers and operators:

The .conjugate() method for int and float objects is interesting, but not surprising, from the perspective of mathematics.

Conjugated numbers are returned when using .real and .conjugate(). However, while using .imag, it always returns 0. As long as the number is an integer, .real and .imag will return integers; if it is an unsigned int, they will return floats as long as it is an integer.

It's possible that you're wondering when you'll actually need to employ complex numbers. In Python, you may never have to deal with complex numbers unless you're doing data analysis or web development.

Science and computer graphics necessitate complex numbers for computation. Because of this, when dealing with complex numbers, Python's built-in support is handy.

Conclusion

Congratulations for making it to this point. During this tutorial, you've learnt how to work with numbers in Python. Python provides built-in support for complex numbers as well as the basic types of numbers, such as integers and floating-point numbers. Now that you've learned how to write Python code, you'll be able to conduct a wide range of calculations. You'll come across a wide range of issues in your programming career that you can address with this knowledge. Let’s meet in the next chapter as we talk more about exceptions in python.

Floating-Point and Integer Numbers in Python

Welcome to chapter 6 of our python course. Previously, we introduced integers and saw how they may be combined with strings and stored in variables. Today, we'll take a closer look at the python number types and how they're stored in variables to see what actions are possible.

What you'll learn in this tutorial is how to:

  • Add, subtract, multiply, and divide numbers.
  • Work with modular.
  • Use exponents.
  • Use expressions.
  • Use a predetermined number of decimal places to round numbers
  • Use strings to format and show numeric data.

With this in mind, let`s start.

How are integers created?

Integers can be created by simply inputting a number. For example, the tutorial variable is assigned the integer 6 in the following way:

>>>Tutorial = 6

In this case, the integer literal is 6 since it is written into the code exactly as it appears. Using int () and str (), you can turn a string containing an integer into a number (). Commas or decimal points are commonly used to separate digits in huge quantities written by hand. When compared to 1000000, the value 1,000,000 is easier for reading. Use underscores (_) instead of the commas (,) if you want to separate digits in an integer literal. Integer literals of one million can be expressed in one of the following ways:

There is no limit to the size of an integer, which may seem unexpected given that computers have a finite quantity of storage. Atom`s interactive window may be used to enter in the largest number you can think of and Python will be able to run it with no problem.

Floating-Point Numbers

Numbers having decimal places are called floating-point numbers. -1.75 is a floating-point number, just like 1.0. float is the name of the data type for floating-point numbers:

>>> type (1.0)

<class 'float'>

A floating-point literal or a text converted to a float using float () may be used to construct floats, much like integers.

It is possible to express a floating-point literal in any one of three ways. There are various ways to construct a float literal with a value of one million.

To produce integer literals, you can utilize the first two techniques. An E notation float literal is also used in the third technique.

Exponential notation - what is it?

Numerical values that might otherwise result in a lengthy string of digits in decimal form can be expressed using the E notation.

You can use E notation to write a floating-point literal by starting with an integer and ending with a value. The number before e is multiplied by 10 raised to power the value that is after e. This means that 1e6 is comparable to 1×106.

Displaying very big floating-point integers with E notation is also possible in Python.

It is true that floats have a maximum size, unlike integers. Your system's maximum floating-point number will vary, but a value like 2e400 should be much beyond the capability of the majority of PCs. 2e400 is equal to 2×104°°, which is a staggeringly large digit!

When you get close to maximum allowed float value, the specialized float inf is returned by Python.

The symbol "inf" represents infinity, and it simply indicates that the number you're attempting to compute exceeds the computer's maximum supported floating-point value. Inf is still a float type:

A negative floating-point value that exceeds your computer's minimum floating-point number is represented by the -inf keyword in Python.

If you're a coder, you're unlikely to see inf and -inf unless you deal with exceedingly high numbers.

Let's see whether we grasp numbers correctly.

Exercise 1: Create two variables, num1 and num2, by writing a python program. Integer literals 25000000 should be allocated to both num1 and num2, one written with underscores and the other without. Two distinct lines should be used to print num1 and num2.

Mathematical expressions and operators

In this session, Math operations such as multiplication, subtraction, addition and division will be covered. We'll also pick up a few coding standards for expressing mathematical ideas.

PEP 8 Recommendations

Anywhere you can, keep your whitespace free of trailing spaces. A backslash, space, and newline do not constitute a line continuation indication because they are both hidden. Pre-commit hooks in many projects including CPython itself reject it, and some editors do not save it.

Assigning (=), augmenting (+=, -=, etc.), comparing (==,!=, >, =, >=), Booleans, and comparison operators (is, isn't, is, isn't), as well as any other binary operators, should always be enclosed in a single space on either side (and, or, not).

If operators of the lowest priority are used, consider separating them with whitespace. Each binary operator should have precisely the same number of whitespaces on either side.

Addition

The + operator is used to perform addition operations:

>>> 1 + 2

"Operands" refers to the values placed before and after the plus sign (+). This example uses two integers, but the type of operands does not have to be the same.

Adding an int to a float is as simple as this:

The sum of 1.0 and 2 is a float, as shown is 3.0. When a float is multiplied by another float, the output is always another float. It is always an int when two integers are added together.

PEP 8 proposes using a space to separate the operands of an operator.

Despite the fact that Python is capable of evaluating 1+1, many programmers prefer the more readable 1+1. All of the operators in this section should follow this general rule of thumb.

Subtraction

To perform subtraction, you need to use the - operator between the integers.

An int is always produced when two integers are subtracted. The outcome is always a float when one of the operands is a float.

To express negative values, the - operator can be used as follows:

>>> -3

Output: -3

Even though it may appear to be strange, subtracting a negative from another number is possible.

The first of the four instances are the most in line with PEP 8. It's possible to make it extra clear that the second - is altering 3 by placing parenthesis around it.

In order to make your code clearer, it is recommended that you utilize parenthesis. Despite the fact that computers are able to run code, humans are only able to read it. Your code should be as readable and understandable as possible.

Multiplication

Use the * operator to multiply two numbers:

There are no exceptions to this rule when it comes to multiplication. When you multiply two integers, you get an int, and when you multiply a float by a number, you get a float.

Division

When two numbers are to be divided, the / operator is used:

The / operator always returns a float, unlike addition, subtraction, and multiplication, which yield integers. You may use int () to ensure that the result of dividing two numbers is an integer:

It is important to note that the int () function discards any fractional parts of the number

The floating-point number 2.5 is obtained by dividing 5.0 by 2, while the integer 2 is obtained by subtracting .5 from the result of int (2.5).

Floor Division operator

The operator (//), often known as the floor division operator, can be used instead of the cumbersome int (5.0 / 2):

First, the / operator splits the numbers on each side of it, and then rounds down to an integer. When one of the values is negative, you may not get the expected result.

For instance, -3 / 2 produces -2. The first step is to divide -3 by 2 to get -1.5. Then -2 is rounded to the nearest -2. -1.5. 3 / 2 returns 1, on the other hand, since both values are positive.

A float number is returned if one operand is a float value, as seen in the preceding example. And that's why 9// 3, and 5.0// 2, respectively, return the integers 3 and 2.0, respectively.

When you divide a number by 0, the following happens:

If Python encounters a ZeroDivisionError, it warns you that you've just attempted to violate a universal law.

Exponents

When you use the ** operator, you can multiply an integer by a power.

Integers are not required to be used as exponents. Floats are another option:

Raising a number to power 0.5 implies taking the square root of that number. The square root of nine is a float, thus even though nine`s data type is an int, Python generates a float 3.0. If both operands of an expression are integers, the ** operator returns an integer and if one of the operands is floating-point number it returns a float.

It's also possible to raise numbers to negative powers like shown below:

If you divide a number raised to a positive power by 1, then you have raised the number to the negative power. As a result, 2 ** -1 equals 1 / (2 ** 1), which is equal to 1 / 2 or 0.5. It's easy to see how 2 ** -2 may be represented as 1 / (2 ** 2), 1 / 4 or 0.25.

Using the Modulus Operator

5% of 3 is 2, so 3 divides 5 once and gives a remainder of 2. Seven also divides 20 twice, leaving 6 as a remainder. In the previous example, 16 divided by 8 is 0, thus 16 % 8 equals 0. The outcome of dividing the value to the right of % by the number to the left is always 0.

Determining the divisibility of two numbers is a typical use of percent. Number n, for example, is only an odd number when n % 2 is zero. What do you suppose is returned by 1% 0? Let's give this a try.

When you divide one by zero, you get 1 which is the remainder of 1 % 0. Nevertheless, Python throws a ZeroDivisionError since it is impossible to divide 1 by 0.

An error like ZeroDivisionError has little impact on your project in interactive window of IDLE. Even if a prompt window will pop up, you can continue to write code in your editor until the error is fixed.

The execution of a script is halted if Python discovers an error while running it. The software crashes in other words.

When you use the percent operator with negative values, things get a little more complicated:

Python has a well-defined behavior that produces these outcomes, even if they appear surprising at first. To find an integer's residual after multiplying it by another number, Python utilizes the formula r = x- (y * (x / y)).

Arithmetic Expressions

Complex expressions can be created by combining operators in new and interesting ways. Python can calculate or evaluate an expression to yield a result made up of integers, operators, and parentheses.

An example of an arithmetic expression is shown below.

Evaluating expressions follows the same set of guidelines as performing standard arithmetic operations. These rules were presumably taught to you as the sequence of operations in school.

Among the operators that have equal precedence are these operators "*," "/," "%," and "%". Thus, 2*3 - 1 yields 5, rather than 4, when divided by 3. Because the * operator takes precedence over the - operator, 2*3 is evaluated first.

In the above example, you may have noticed that the requirement requiring a space before and after each operator was not followed. Whitespace in complex expressions is addressed in PEP 8:

If the operators with the lowest priority are being used, then whitespace should be added around them. Using a single space and the equal number of whitespaces on both sides of a binary operator is perfectly acceptable.

Even if parenthesis isn’t essential, it's always good to include them to indicate the order in which steps should be taken.

Conclusion

In this lesson, you've learned how to use Python's numbers with expressions. In the next chapter, you'll learn how to employ math functions and number techniques and learn how to avoid typical mistakes that might lead to program failures.

How to use Variables in Python?

Welcome back! This is the fifth lesson in our Python programming course. In the last chapter, we discussed how string data types are used in Python. In this tutorial, we’re going to discuss variables in python and the rules for naming them in Python. In addition, you'll learn the fundamentals of working with numbers and strings.

What are variables?

All programming languages use variables as a fundamental building block of their language. It is the allocation of memory that is dedicated to data storage and manipulation. Variables are program elements that keep track of data. The following is an example of a variable.

x = 100

It's called x in the diagram below, and it has a value of 100 in it. In this case, the variable name is x, and the data it contains is the number.

For a variable, its data type is just the type of data it contains.

Data types - what are they?

If a variable has a certain data type, it can be used with any mathematical, relational, or logical operation without resulting in an error; this is known as the data type in programming. There are many different types of data, such as strings and integers, that are used to categorize different kinds of information.

How do computers store Python variables?

As a Python programmer, we don't have to do anything to free up space. Garbage collection handles this.

There are two types of memory:

Stack memory

Stack memory is used to hold all functions and their calling references. The lifo rule governs how a stack operates. Continuous blocks make up the stack memory. When a function is called, the variables it returns are kept in the program's call stack, where they can be freed upon function completion and the program's exit successfully.

Heap memory

Heap memory refers to the memory allocated at run time when each instruction is performed. A heap is used to store global variables, which can be shared by all functions in the program, rather than the local variables defined within a function. Here, x = 23 is an example.

Number types in Python

Integers, floats, and complex numbers are all available as numeric types in Python. In this tutorial, we'll learn about integers because we'll be using them to show how variables work.

For simplicity's sake, an integer is a number that does not include a decimal point or fraction. They might be both positive and negative at the same time. For example, the numbers 1, 2, 3, 500, and 10000000.

The int class contains all integer variables. The class name can be found using the type () method, as illustrated in the example below.

Python's Rules for Variable Naming

  • When naming a variable, it should begin with a letter or an underscore (_). For example, Age, _age, and Age.
  • There are no special characters allowed in the variable name, except for the underscore (_). There are several examples of this: age_, _age
  • Variables are case-sensitive. Therefore, age and Age are two different things.
  • However, the variable name can have numbers at the end, but not at the start. Age1 is a good illustration of this.
  • Python keywords should not be used in the name of a variable. Reserved words are another term for keywords. True, False, None, and Def.

Techniques for naming a variable with numerous words.

  • Camel Case: As a visual aid, the second and following words are capitalized. For example, pythonTutorial
  • Pascal Case: Similar to Camel Case, except that the initial letter is capitalized instead of being lowercase. For example, PythonTutorial
  • Snake Case: Underscores divide each word. For example, python_tutorial

Variable Assignment

A variable refers to an item's specific name. Instead of having to declare or specify a variable like in other programming languages, Python simply uses the equals (=) sign to create a variable and assign a value.

As stated, "n is allocated the value of 300" in the example above. You can then use n in a statement or expression, and its actual value will be substituted for n.

Just like with a literal value, variables can be shown directly from the interpreter prompt in a REPL session, without the usage of print ().

In the future, if you use n again and alter its value, the new value will be used:

Chained assignment in Python allows the same value to be assigned to many variables at the same time:

The above-chained assignment gives the variables a, b, and c the value 300 at once.

Python's Variable Types

Python has two types of variables: global variables and local variables. To utilize the variable in other parts of your program or module, you need to declare it as a global one. It is common practice in Python to use local variables when creating new variables.

Using the following program, you can see how Python variables function by comparing the local and global variables.

  1. Using Python, let's create a global variable called "f" and assign it the value 101, which is printed in the output.
  2. f is a new local scoped variable declared by function f. When this variable is set to its default value, "I'm studying Python." is printed as an output. This Python declared variable is distinct from the global variable "f" specified before.
  3. A function call's local variable f is disposed of once the execution has completed. At line 12, the global variable f=101 is displayed when printing the value of "f" once more.

You can utilize a global variable in a function in Python if you include the global keyword in the variable definition.

  1. The "f" variable is global in scope and has been assigned a value of 101, which is printed in the output of the code.
  2. The variable f is declared to exist by using the keyword global. That which was previously defined as a globally applicable variable will be used here. When we print the value, it comes out to 101.
  3. Inside the function, we modified the value of "f." The new value of the variable "f" remains even after the function call has ended. Line 12 prints the value "changing global variable" when value of "f." is printed.

Variables are statically typed in many programming languages. A variable's data type is specified when it is created, and any value that is assigned to it must always be of the same type.

However, Python variables are exempt from this rule. It is possible in Python to give a variable a value of one type and then change it to another type later on:

In reality, what happens when you assign a value to a variable?

This is an important subject in many programming languages, but the answer in Python is a little different.

Since Python is a highly object-oriented language, every piece of data in a program is an object of some type or class. This will be brought up again and again in the course of these tutorials.

References to objects

Take a look at the following coding:

Translators are instructed to perform the following actions when provided with a statement print (300).

  • Creating and supplying the value 300 to an integer object
  • The console will show it.

As you can see, the built-in type () function creates an integer object.

An object can be referenced by a Python variable's symbolic name, which serves as a pointer or reference. After assigning a variable name to an object, you can use that name to refer to the object. However, the object itself still contains the data. For instance,

An integer object with the value of 300 is created and the variable n is assigned as an identifier.

n is a pointer to an integer object, and the following code confirms that:

Then consider the following assertion:

What happens if it is executed? A new object is not created. Since n points to the same item, m points to a new symbolic name or reference.

Next, you may try something like this:

Python now constructs a new integer object named m, which has a value of 400.

Finally, let's consider that the following statement is executed:

As a result, Python generates a string object named "foo" and uses that as a pointer in n.

The integer object 300 is no longer mentioned anywhere. There is no way to get in touch with it.

The lifespan of an item will be mentioned at various points in this series of tutorials. When an item is first created, at least one reference to it is made, which marks the beginning of its life. A reference to an object can be added or destroyed at any moment during its lifetime, as you saw in the example above. As long as there is at least one reference to the thing, it lives on.

Objects are no longer accessible when the number of references to them reaches zero. Its time had come to an end at that moment. The allocated RAM allocated to Python will eventually be reclaimed so that it can be utilized for something else. Garbage collection, as it's called in computer jargon, is a very simple way to manage your own memory.

Object identity

Every Python object is assigned a unique identifier number when it is created. No two objects will ever share an identifier, even if their lives overlap for a period of time. It is not possible to utilize the same identifier for an object after its reference count reaches zero and it is garbage collected.

A Python object's id can be obtained using the id () function, which is part of the standard library. Id () can be used to verify that two variables are actually pointing at one another:

Even after an assignment such as this, which results in the same number being returned for id(n), it is clear that these two numbers point to the same thing. As soon as m is reassigned to the value 400, they no longer point to the same item, but rather to different things, take into account the following:

M and n are both 30-valued integers in this example. The id(m) and id(n) are identical in this example, While running the program, the interpreter makes use of previously created objects for numbers in the [-5, 256] range. As a result, if you assign different integer values in this range to different variables, they will all refer to the same thing.

Delete a variable

Python variables can also be deleted by use of function del "variable name". Python's error "variable name is not defined" indicates that you've erased the variable in the following example of the language's delete variable function.

Variable type casting

Test the concatenation of several data types such as string and integer. The number "99" will be added to the word "Guru," for example, A Type Error will arise if the number is not expressed as a string when declaring variables in Python. This differs from Java, which does not require the number to be declared as a string.

You will obtain an undefined result if you run the following code.

a="Guru"

b = 99

print a+b

Use print(a+str(b)) to concatenate both a and b into a string.

what is type casting?

This is the process of changing one data type to another. Data type conversion is necessary in some scenarios. For instance, you may want to combine two numbers where one of the variables' existing values is an integer and the other is a string. Python typecasting is required before addition, as it must transform a string's data type to an integer.

Types of conversions in type casting

  • Explicit conversion

Type casting in Python can be done using a variety of functions.

  1. The INT () function is used to specify integer literals. A string literal is converted to an integer value.
  2. Use STR () to convert an integer to a string ().
  • Implicit conversion

Data types in Python are implicitly converted by the Python interpreter, which means that the user is not required to intervene in the process. See the examples below for a better understanding of the subject.

Conclusion

Congratulations! Your perseverance has paid off. The focus of this session was on Python variables, object references, and identity, as well as the naming conventions for Python identifiers and a brief discussion of integers. Let’s meet in our next tutorial as we discuss about Python data types and how they're put to use.

Introduction to Metal Core PCB

Hello everyone and welcome to this article. Previously we have been discussing different types of PCB boards and for sure we have not exhausted everything. Today we are going to focus on a very important aspect of the PCB design which is the thermal characteristics of the PCB's working environment. Up to this moment, we have interacted with boards that work best in normal working conditions. But remember there are some working conditions, that have very harsh environment such as high temperatures. Let us take for example temperature in boilers or even electric heaters. Do you think normal FR-4 boards can survive in such temperatures? Don’t you think they will melt off if exposed to high thermal radiation? Your guess is as good as mine. For us to have a solution on this matter of high thermal temperatures, there had to be introduced another type of board that could resist such an environment and gives the solution to what the designers wanted. They had to develop the metal core printed circuit boards. These types of boards are suitable in the environment where there is high heat generation and this heat needs to be dissipated away from the circuit and avoid reaching the most critical components of the same circuit which might damage them.

The rapid developments that have been achieved in the Light Emitting Diode industry more so in the area of high-power LEDs, have brought up a challenge on heat dissipation. The LEDs are always mounted on the printed circuit boards and they might end up bringing a lot of problems, especially on the heat generated from them. Without proper laid down structures to dissipate the excess heat will end up damaging the board. To solve this, designers have chosen to implement the use of metal core PCBs.

Definition of the Metal Core PCB.

  • As the name indicates, the metal core printed circuit board (MCPCB) is made up of a metallic base as opposed to the traditional FR4 material.
  • The metal core material is being used because it offers good heat conduction properties and hence the board will have an efficient heat dissipation mechanism.
  • This heat is being dissipated as a result of heat buildup that originates from the electronics component during the operation.
  • The purpose of the metal core is to ensure that it diverts the heat generated away from the crucial components of the circuit and moves it towards the less critical components such as the heat sink areas.
  • This shows that this type of PCB board is significant for thermal management.
  • When designing a multilayer MCPCB, the metal core layers should be spread on both sides of the board.
  • Let us use an example of the 12-layer MCPCB board, the metal core will be at the bottom and the top layer and also at the center that is at the 6th layer.
  • They are made up of thermal insulating layers, metal copper foil and metal plates.
  • For the purpose of our article, we shall have to use MCPCB as the abbreviation of this metal core printed circuit board.

Metal core PCB boards are special types of PCBs that have a metallic layer that is made up of copper or aluminum. This metallic layer is what gives it this name.

How to order Metal Core PCB?

There are many online PCB companies offering Metal Core PCB manufacturing. We are going to take the example of JLCPCB, a China-based online PCB Fabrication House. JLCPCB offers competitive rates and provides excellent results and is considered one of the best PCB manufacturers. You can place a PCB order on JLCPCB's official website.

  • As you can see in the above figure, I have placed an order of 5 PCBs of size 100x100mm.
  • At the top, I have selected Aluminium, instead of FR-4.
  • It has calculated the price to $2 for 5 Pcs and you will get the delivery in 2-3 days.
Normally, SMD components are placed in Metal Core PCBs and JLCPCB offers the best SMT services. You should first check these JLCPCB SMT services to get an idea. Let me highlight its important points:
  • They offer single-sided placement on the PCB board.
  • JLCPCB has an extensive Library for SMT parts and you need to select the components from there.
  • JLCPCB manufacture SMT Components in-house and thus gives the best results.
  • JLCPCB places automated solder paste and then performs Solder Paste Inspection(SPI).
  • I have attached the SMT Assembly screenshot in the below figure:
You can check JLCPCB SMT Services from this video as well:

So, it's quite easy to order for manufacturing of Metal Core PCB on JLCPCB.

Layers of metal core PCBs

When you compare the metal core PCB with other traditional standard PCBs you will realize that it has special layers. The total number of these layers on the PCB will be determined by the total number of conductive layers that you really need. They can be of single or multiple conducting layers. The layers can be categorized into three types

  • Base layer
  • Copper layer
  • Dielectric layer.

Base Layer

  • The layer is made up of metal and this is the reason the PCB has the name.
  • Since it is made up of metal, the board can withstand a lot of temperature and pressure compared to the traditional FR-4 PCBs.
  • The board is also very strong, lasting and durable.
  • The metal core base plays the role of the heat sink where it spreads the heat away from the components a role that cannot be achieved by the use of the fans.
  • This base layer can be made up of different metals although the most used types of metals are Aluminum and copper.
  • Aluminum is the most preferred metal because of its cheaper prices but copper is the best when it comes to performance but is more costly.
  • The thickness of this base is determined by the customer requirement or the designer specification although it is in the range of between 1 and 4 mm.

Copper layer

  • It is the first layer that is present in all types of PCBs.
  • It is the conduction layer that helps in the transiting of the electric signals.
  • In other places, they refer to it as the circuit layer since this is where all the conductive circuits and even paths are made.
  • The thickness of this layer is determined by the requirements and according to the project layers.

Dielectric layer

  • This is the most important layer in the MCPCB which you will not find in the FR-4 PCB.
  • We have noted that the top layer is the copper layer and the bottom layer is the metal core layer. We know that these layers are conductive and in between than they are separated by the dielectric layer which acts as the insulator for separating the two conductive layers.
  • By separating the copper and the metal layer, the dielectric protects them from electric shorts.
  • The main purpose of this layer is to aid in heat dissipation. It picks heat from the top copper layer, passes it through it into the metal core where it is dissipated completely.
  • The size of the dielectric layer should be kept as thin as possible so that it does not have any effect on the overall thickness of the final board.

Types of metal core PCBs.

There are three major categories of the MCPCB as discussed below;

Single-sided metal core PCB

This type of metal-core PCB has the copper traces printed on one side of the board and the board comprises of the following;

  • The solder mask.
  • The copper circuit.
  • The metal layer performs as the conductive link.
  • The integrated circuit components
  • The dielectric layer

The single-sided board also has a dielectric layer that is sandwiched between the copper and the metal core layer.

Double-sided metal core PCB

  • This type of MCPCBs comes with a metal layer that lies between two conductive layers of the board. It also has a dielectric that is sandwiched between the copper core and the metal core.
  • The metal core is usually the conductor.

Multilayer metal core PCB

It comes with over two layers hence having a structure that looks like the FR-4 type of PCB materials.

  • However, this type of board is much complicated in its design.
  • For this type of board to achieve maximum performance, it utilizes too many components, grounds and the signal nature.

Process for the production of the metal core PCBs.

Let us have a look at the steps that can be followed in the design of the metal core printed circuit boards as listed below;

  • The first step is the creation of the design and the output. This can be done by the use of electronic design automation software such as KiCAD, Proteus, Altium, OrCAD, etc.
  • Check the DFM and after checking, by using a film print the copy of the designer.
  • Use the printed film to print the MCPCB and while undergoing this process, it is advised that you do it in a very clean environment to ensure that your outcome will have no errors.
  • During this process, you might end up with excess copper and therefore you have to use a chemical to etch the excess copper and remove it.
  • Ensure that you have punched all the alignment in a well-organized line.

After this step, you now need to confirm the digital image that you have with the original Gerber files from the designer using an inspection laser to confirm if you have done the right thing.

After the confirmation that you have done the right thing, now the design can be moved to the final process of the design. This final step involves the unpacking of the PCB layers accordingly. We are supposed to locate the drill points and this can be done by the use of the x-ray locator.

Now the board is supposed to undergo the process of plating and deposition of copper where the whole PCB is electroplated with the copper layer before the board is taken through the final process of v-scoring and profiling.

MCPCBs metal bases

The aluminum substrate

The PCBs that are made out of aluminum offer very smart heat dissipation and a good heat transfer mechanism. Aluminum PCBs are very light in weight and are used in LED lighting applications, electronic communication and audio frequency equipment. Listed below in the characteristics of the aluminum substrate;

  • The thickness should be between 2 to 8 mm.
  • Has a thermal conductivity that ranges between 5 to 2 watts per meter kelvin.
  • The peeling strength of not less than 9lb/in
  • The soldering strength; safety factor of 288 degrees centigrade for more than 180 seconds.
  • Has Greater than 3000V of breakdown voltage
  • 0.03 dielectric loss angle.
  • Flammability of UL 94V-0.
  • The size of the panel is 18” x 24”.

Copper base

PCBs made out of the copper core have better performance than those made out of aluminum. But aluminum is preferred to copper by most clients because copper is more expensive. Another disadvantage of copper core over aluminum is that copper boards are heavier and involve a tough process of machining. Copper has a higher rate of corrosion as compared to the aluminum core.

The benefits of the MCPCBs

  • The metal boards can undergo etching to control the way heat that is generated by the components flows.
  • These boards are very important in high vibrations systems since the components cannot fall off due to strong mounting on the metal core.
  • Metals are harmless and can be recycled.
  • With metal, you expect a more durable product as compared to the normal epoxy boards.
  • Metals have high thermal conductivity characteristic and this means that it provides a faster means of heat transfer.

Applications of the MCPCBs

This type of board finds great use in the field of LED technology. Some of the applications are listed below;

  • Light-emitting diodes both in the backlight unit and the general lighting.
  • Heat sinks and heat spreaders for cooling systems.
  • Power regulations and automobiles are more so in hybrid car systems.
  • Used in the semiconductor thermal insulation boards. semiconductors are the top heat emitters in the PCBs and this heat requires a better method to manage it which can be offered by the MCPCBs.
  • Amplifies for audio. Amplifiers can be made from the FR-4 material, but if you need quality, best performance and reliability, I would advise the use of the metal core PCBs.
  • Used in the hybrid and the electric motor control system and motor drivers. These are applications that generate a lot of heat that a normal PCB cannot withstand. For this reason, MCPCBs are best suited for such applications.
  • Used in the modern solar panels
  • Used in the control of motion.
  • Finds application in the solid-state relays.

ESP32 DHT11 Interfacing with ThingSpeak WebServer

ESP32 module comes with multiple inbuilt features and peripheral interfacing capability is one of those features. ESP32 module also consists of an inbuilt temperature sensor, but that can only measure the temperature of the ESP32 core not the temperature of the surrounding environment. So it is required to use a peripheral sensor to measure the temperature of the surrounding environment like home, garden, office etc.

Hello readers. I hope you all are doing great. In this tutorial, we will learn how to interface DHT11 (temperature and humidity sensor) with the ESP32. Later in this tutorial, we will discuss how to share the sensor readings obtained from the DHT11 sensor to a web server.

Before moving towards the interfacing and programming part, let’s have a short introduction to the DHT11 sensor, its working and its connections.

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

DHT11 (A Temperature and Humidity Sensor)

Fig. 1: DHT11 sensor

DHT11 is used to measure humidity and temperature from its surrounding. It monitors the ambient temperature and humidity of a given area. It consists of an NTC (negative temperature co-efficient) temperature sensor and a resistive type humidity sensor. It also consists of an 8-bit microcontroller. The microcontroller is responsible for performing ADC (analog to digital conversion) and provides a digital output over the single wire protocol.

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

DHT11 sensors can also be used to implement a wired sensor system using a cable length of up to 20 meters.

There are two DHT modules (DHT11 and DHT22) available in the market to measure temperature and humidity. The purpose of both module are same but with different specifications. Like DHT22 sensor provides broader temperature and humidity sensitivity ranges. But DHT22 is costlier than DHT11. So you can prefer to use any of the module, as per your requirements.

Components required

  • ESP32 development board
  • DHT11 sensor
  • 10K resistor
  • Connecting wires
  • Breadboard

Interfacing DHT11 with ESP32 module

Table: 1

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

Fig. 2: ESP32 and DHT11 connections/wiring

Arduino Programming

We are using Arduino IDE to compile and upload code into ESP32 module. To know more about Arduino IDE and how to use it, follow our previous tutorial i.e., on ESP32 programming series. Link is given below:

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

Adding required libraries in Arduino IDE

DHT11 sensor uses single wire protocol to communicate data which requires a precise timing. In order to interface DHT11 sensor with ESP32 module it is required to add necessary libraries. To install the DHT11 sensor library;

  • Go to Tools >> Manage Libraries.

Fig. 3: manage libraries

 
  • Type DHT in the search bar and install the DHT sensor library as shown below.

Fig. 4: Install DHT sensor library

   

Arduino IDE code to interface DHT11 with ESP32

#include "DHT.h"

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

#define DHTTYPE DHT11 // DHT 11

// Initializing the DHT11 sensor.

DHT dht(DHTPIN, DHTTYPE);

void setup() {

Serial.begin(115200);

Serial.println(F("DHT test string!"));

dht.begin();

}

 

void loop() {

// Wait a few seconds between measurements.

delay(2000);

// Reading temperature or humidity takes about 250 milliseconds!

// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)

float h = dht.readHumidity();

// Read temperature as Celsius (the default)

float t = dht.readTemperature();

// Read temperature as Fahrenheit (isFahrenheit = true)

float f = dht.readTemperature(true);

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

if (isnan(h) || isnan(t) || isnan(f)) {

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

return;

}

// Compute heat index in Fahrenheit (the default)

float hif = dht.computeHeatIndex(f, h);

// Compute heat index in Celsius (isFahreheit = false)

float hic = dht.computeHeatIndex(t, h, false);

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

Serial.println(h);

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

Serial.print(t);

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

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

Serial.print(f);

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

Serial.print(F("Heat index: "));

Serial.println(hic);

Serial.println(" ");

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

Serial.print(hif);

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

}

Code Description

  • Add the necessary header files required to interface the DHT11 sensor.

Fig. 5: Add necessary libraries

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

Fig. 6: Global declarations

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

Fig. 7

 

Setup()

  • Inside the setup function, the first task is initializing the serial monitor at a 115200 baud rate for debugging purposes.
  • Initialize the DHT sensor using begin() function.

Fig. 8

Loop()

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

Fig. 9

  • readTemperature() function is used to read the surrounding temperature with DHT11 sensor.

Fig. 10

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

Fig. 11

  • Another float type variable hif is defined to store the heat index value.
  • computeHeatIndex() function is used to calculate the heat index value.

Fig. 12: Heat index

Results

  • Open the Arduino IDE and paste the above code.
  • Compile and upload the program after selecting the correct development board and COM port.
  • Connect the DHT11 sensor with ESP32 board as per the given circuit instructions.

Fig. ESP32 and DHT11 interfacing

  • Open the serial monitor at 115200 baud rate and press the enable (EN) button from the ESP32 development board.
  • You should see the temperature, humidity, Heat index readings printed on the serial monitor.

Fig. 13: Readings observed from DHT11 sensor

Uploading DHT11 sensor reading to ThingSpeak Server

The IoT 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.

Espressif Systems created the ESP32 Wi-Fi chip series. The ESP32 module is equipped with a 32-bit Tensilica microcontroller, 2.4GHz Wi-Fi connectivity, an antenna, memory, and power management modules, and much more. All of these built-in features of this ESP32 module make it ideal for IoT applications.

ThingSpeak web servie

It is an open data platform for the Internet of Things (Internet of Things). ThingSpeak is a MathWorks web service that allows us to send sensor readings/data to the cloud. We can also visualise and act on the data (calculate the data) sent to ThingSpeak by the devices. Data can be stored in both private and public channels.

ThingSpeak is commonly used for internet of things prototyping and proof of concept systems requiring analytics.

 

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. 14: Getting started for free

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

Fig. 15: Create new account

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

Fig. 16: MathWorks Sign in

  • Create a channel on MathWorks server by clicking on the New Channel
  • ThingSpeak web service allows its user to create and save maximum of 4 channels for free.
  • If you are want access to more channels then you need to make payment for that.

Fig. 17: New Channel

  • Enter the respective details in the channel.

Fig. 18: Fill the channel details

  • Here we are creating two fields. First one represents the temperature and another one is to represent the humidity measured using DHT11 sensor. You can also add more fields as per your requirements.
  • A new URL containing the channel details and channel Stats will open, once you have successfully created the channel. On the same page/url, API keys are available for both read and write services.
  • Go to API Keys and copy the write API key and paste in your Arduino IDE code. So that ESP32 can send or write the DHT sensor readings to the MathWorks server.
  • In Private view your can also customize your chart. To edit the chart, click on the icon present on the top right corner of field chart.
  • Edit the details as per your requirements and click on the Save

Fig. 19: Field Chart Edit

 

Arduino IDE programming

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. 20: Adding ThingSpeak library

To check whether the library is successfully added or not:

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

Fig. 21: manage libraries

  • Type thingspeak in the search bar.

Fig. 22: Arduino IDE Library manager.

  • The ThingSpeak library by MathWorks has been successfully downloaded.

Code

//------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 "DHT.h"

#include "ThingSpeak.h"

//-----netwrok credentials

char* ssid = "replace this with your SSID"; //enter SSID

char* passphrase = "replace this with your password"; // enter the password

WiFiServer server(80);

WiFiClient client;

//-----ThingSpeak channel details

unsigned long myChannelNumber = 3;

const char * myWriteAPIKey = "replace this with your API key";

//----- Timer variables

unsigned long lastTime = 0;

unsigned long timerDelay = 1000;

//----DHT declarations

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

#define DHTTYPE DHT11 // DHT 11

// Initializing the DHT11 sensor.

DHT dht(DHTPIN, DHTTYPE);

 

void setup()

{

Serial.begin(115200); //Initialize serial

Serial.print("Connecting to ");

Serial.println(ssid);

WiFi.begin(ssid, passphrase);

while (WiFi.status() != WL_CONNECTED) {

delay(500);

Serial.print(".");

}

// Print local IP address and start web server

Serial.println("");

Serial.println("WiFi connected.");

Serial.println("IP address: ");

Serial.println(WiFi.localIP());

server.begin();

//----nitialize dht11

dht.begin();

ThingSpeak.begin(client); // Initialize ThingSpeak

}

void loop()

{

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

{

delay(2500);

// Reading temperature or humidity takes about 250 milliseconds!

float h = dht.readHumidity();

// Read temperature as Celsius (the default)

float t = dht.readTemperature();

float f = dht.readTemperature(true);

if (isnan(h) || isnan(t) || isnan(f)) {

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

return;

}

Serial.print("Temperature (ºC): ");

Serial.print(t);

Serial.println("ºC");

Serial.print("Humidity");

Serial.println(h);

ThingSpeak.setField(1, h);

ThingSpeak.setField(2, t);

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

  • The style guards are used at the beginning of the program to declare some function to be of “C” linkage, instead of “C++” Basically, to allow C++ code to interface with C code.

Fig. 22: Style guard

  • Add the required header files. In this example we are using three libraries, Wi-Fi.h, DHT.h, ThingSpeak.
  • We have already discussed above how to download and add the DHT and ThingSpeak library files to Arduino IDE.

Fig. 23: Libraries

  • Enter the network credentials (SSID and Password) of the access point to which your ESP device is supposed to connect for internet connectivity.

Fig. 24

  • To access the created web server we also need to assign a port and usually port 80 is used for local web server.

Fig. 25: server port

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

Fig. 26

  • Global declaration of timer variables.

Fig. 27: Timer variables

  • 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 passing two arguments SSID and password.
  • Wait until the ESP32 is not connected with the wifi network.

Fig. 30: connect to wifi

  • Once ESP32 is successfully connected to Wi-Fi network, the localIP() function will fetch the IP address of the device.
  • begin() function is used to initialize the server.

Fig.31: Fetch and print IP address

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

Fig. 32

  • Set the number of fields you have created to the ThingSpeak server. We are adding only two fields. First one represents the humidity measured by the sensor from its surrounding and the 2nd field represents the temperature in degree Celsius.
  • You can also add further fields like for temperature in Fahrenheit, heat index etc.
  • ThingSpeak allow the user to add up to maximum of 8 fields for different readings.

Fig. 33

  • 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

  • Copy the above code and paste it into your Arduino IDE.
  • Make the required changes in the above code and the changes required includes, network credentials (SSID and Password), API key, Channel number etc.
  • Compile and upload the above program into ESP32 development after selecting the correct development board and COM port.
  • Make sure the Access Point (Wi-Fi) is ON to which your ESP device is supposed to connect.
  • Open the serial monitor at a 115200 baud rate and press the EN button from the ESP32 development board.

Fig. 35: Results on the Serial monitor

  • Open the channel you have created on the ThingSpeak server.
  • You should see the charts updated with the latest temperature and humidity readings.

Fig. 36: Displaying humidity on thingSpeak server

Fig. 37: Displaying Temperature on ThingSpeak server

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

What’s The Difference Between Edge Computing And Cloud Computing?

Public cloud computing systems enable businesses to complement their data centers with worldwide servers that can scale processing capabilities up and down as required. In terms of value and security, hybrid public-private clouds are unparalleled.

However, real-time AI applications demand substantial local processing capacity, frequently in areas distant from centralized cloud servers. speedpak tracking is among the services including AI for the safety of your goods and parcels.

Moreover, some workloads demand low latency or data residency and must stay on-premises or specified locations.

That is why many businesses use edge computing to implement AI applications.

Instead of storing data in a centralized cloud, edge computing saves data locally in an edge device. Moreover, the gadget may function as a stand-alone network node without an internet connection.

Cloud and edge computing offer many advantages and application cases.

Cloud Computing; Overview

Cloud computing is a computing approach in which scalable and elastic IT-enabled capabilities are supplied as a service through the Internet.

Cloud computing's popularity is growing as a result of its many advantages. Cloud computing, for example, has the following benefits:

  • Lower initial investment
  • Price Variability
  • On-demand computation with no bounds
  • IT management has been simplified.
  • Simple updates
  • The dependability is excellent.
  • Time is money

Edge Computing; Overview

Edge computing is the process of physically bringing computational capacity closer to the source of data, which is generally an Internet of Things device or sensor. Edge computing, so named because of how computing power is delivered to the network's or device's edge, enables quicker data processing, higher bandwidth, and data sovereignty.

Edge computing lowers the need for huge volumes of data to travel between servers, the cloud, and devices or edge locations to be processed by processing data at the network's edge. It is especially relevant for current applications like data science and artificial intelligence.

Cloud Vs. Edge Computing

Edge and cloud computing have unique advantages, and most businesses will utilize both. Here are some things to think about when deciding where to deploy certain workloads.

In contrast, cloud computing is ideal for non-time-sensitive data processing, but edge computing is ideal for real-time data processing.

Also, the former requires a dependable online connection, while the latter should encompass rural regions with little or no internet access.

Furthermore, cloud computing stores data in the cloud, but edge computing includes very sensitive data and tight data rules.

Medical robotics is one example of when edge computing is superior to cloud computing because surgeons want real-time data access. These systems include a significant amount of software running on the cloud.

Still, the sophisticated analytics and robotic controls increasingly used in operating rooms cannot tolerate latency, network stability difficulties, or bandwidth limits. In this case, edge computing provides the patient with life-saving advantages.

A Blend Of Both; Hybrid Cloud Architecture

Convergence of cloud and edge is required for many enterprises. Organizations centralize when possible and disseminate when necessary.

Firms may benefit from the security and management of on-premises systems with hybrid cloud architecture. It also makes use of a service provider's public cloud resources.

For each firm, a hybrid cloud solution implies something different. It might imply training in the cloud and deploying at the edge, training in the data center and deploying at the edge using cloud management tools, or training at the edge and deploying in the cloud to centralize models for federated learning. There are several options to connect the cloud and the edge.

Conclusion

Though both the computing systems are equally important, each carries distinctive perks. As the world is moving toward the hybrid approach, understanding the right computing choice will ease your process. Our guide will assist in this regard.

IoT Based Motion Detection with Email Alert using ESP32

The IoT 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.

Espressif Systems created the ESP32 Wi-Fi chip series. The ESP32 module is equipped with a 32-bit Tensilica microcontroller, 2.4GHz Wi-Fi connectivity, an antenna, memory, and power management modules, and much more. All of these built-in features of this ESP32 module make it ideal for IoT applications.

Hello readers, I hope you all are doing great. In this tutorial, we will learn another application of ESP32 in the field of IoT (Internet of Things). We are using a PIR sensor to detect motion and an Email alert will be generated automatically whenever a motion is being detected.

Fig.1

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

Overview

The HCSR-501 sensor module is used with ESP32 to detect the motion. So whenever a motion is detected, the PIR sensor will generate a HIGH output signal which will act as an input to the ESP32 module. In the absence of motion, the output of the PIR sensor will remain LOW. If a HIGH input signal is generated from the PIR sensor module, the LED (either peripheral or inbuilt) will be turned ON and along with that, an Email will be generated to the receiver’s email address as per the program instructions.

Software and Hardware requirements

  • ESP32 development board
  • HCSR-501 PIR sensor module
  • LED
  • Resistor
  • Connecting Wires
  • Sender’s email account details
  • Receiver’s email address
  • ESP-Mail-Client Library

What is HCSR-502 PIR sensor module and how does it work?

Fig. 2 PIR Motion Sensor

PIR stands for Passive Infrared sensors. It detects heat energy in the surrounding environment using a pair of pyroelectric sensors. Both sensors are placed next to each other, and when motion is detected or the signal differential between the two sensors changes, the PIR motion sensor returns a LOW result (logic zero volts). It means that in the code, you must wait for the pin to go low. The desired function can be called when the pin goes low.

There are two potentiometers available in the HCSR-501 PIR motion sensor module. One of the potentiometers is to control the sensitivity to the IR radiations. Lower sensitivity indicates the presence of a moving leaf or a small mouse. The sensitivity can be changed depending on the installation location and project specifications.

The second potentiometer is to specify the duration for which the detection output should be active. It can be programmed to turn on for as few as a few seconds or as long as a few minutes.

PIR sensors are used in thermal sensing applications such as security and motion detection. They're commonly found in security alarms, motion detection alarms, and automatic lighting applications.

SMTP

The simple mail transfer protocol (SMTP) is an internet standard for sending and receiving electronic mail (or email), with an SMTP server receiving emails from email clients.

SMTP is also used to establish server-to-server communication.

Gmail, Hotmail, Yahoo, and other email providers all have their own SMTP addresses and port numbers.

Fig. 3 SMTP

How does SMTP work?

To send emails, the SMTP protocol, also known as the push protocol, is used, and IMAP, or Internet Message Access Protocol (or post office protocol or POP), is used to receive emails at the receiver end.

The SMTP protocol operates at the application layer of the TCP/IP protocol suite.

When the client wants to send emails, a TCP connection to the SMTP server is established, and emails are sent over the connection.

SMTP commands:

  • HELO – This command is sent only once per session and it is used to identify the qualified domain names and the client to the server.
  • MAIL – used to initiate a message
  • RCPT – Identifies the address
  • DATA – This command is responsible for sharing data line by line

SMTP server parameters for email service

There are various email service providers available like, Gmail, Yahoo, Hotmail, Outlook etc. and each service provider have unique service parameters.

In this tutorial, we are using the Gmail or Google Mail service.

Gmail is the email service provided by Google and Gmail SMTP server is free to access and anyone can access this service, who has a Gmail account.

  • SMTP server: smtp.gmail.com
  • SMTP port: 465
  • SMTP sender’s address: Gmail address
  • SMTP sender's password: Gmail Password

Create a new Gmail account (Sender)

It is recommended to create a new email account for sending emails using ESP32 or ESP8266 modules.

If you are using your main (personal) email account (for sending emails) with ESP and by mistake something goes wrong in the ESP code or programming part, your email service provider can ban or disable your main (personal) email account.

In this tutorial we are using a Gmail account.

Follow the link to create a new Gmail account : https://accounts.google.com

Fig. 4 create new gmail account

Access to Less Secure apps

To get access to this new Gmail account, you need to enable Allow less secure apps and this will make you able to send emails. The link is attached below:

https://myaccount.google.com/lesssecureapps?pli=1

Fig. 5 permission to less secure apps

Interfacing ESP32 and HCSR-501

Table 1

Fig. 6 ESP32 and HCSR-501 connections

Arduino IDE Programming

We are using Arduino IDE to compile and upload code into ESP32 module. To know more about ESP32 basics, Arduino IDE and how to use it, follow our previous tutorial i.e., on ESP32 programming series. Link is given below:

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

Necessary Library

To enable the email service in ESP32 it is required to download the ESP-Mail-Client Library. This library makes the ESP32 able to send email over SMTP server.

Follow the steps to install the ESP-Mail-Client library:

  1. Go to the link and download the ESP-Mail-Client library:

https://github.com/mobizt/ESP-Mail-Client

  1. Open your Arduino IDE.
  2. Then to add the ZIP file go to Sketch >> Include Library >> Add.ZIP Library and select the downloaded ZIP file.

Fig. 7 Adding ESP-Mail-Client Library

  1. Click on

Arduino IDE Code

//To use send Email for Gmail to port 465 (SSL), less secure app option should be enabled. https://myaccount.google.com/lesssecureapps?pli=1

//----Add the header files

#include <WiFi.h>

#include <ESP_Mail_Client.h>

//-----define network credentials

#define WIFI_SSID "public"

#define WIFI_PASSWORD "ESP32@123"

//--add the Server address and port number with respect to a particular email service provider

#define SMTP_HOST "smtp.gmail.com"

#define SMTP_PORT esp_mail_smtp_port_587 //port 465 is not available for Outlook.com

 

//----The log in credentials

#define AUTHOR_EMAIL "techeesp697@gmail.com"

#define AUTHOR_PASSWORD "Tech@ESP123"

//----The SMTP Session object used for Email sending

SMTPSession smtp;

//---Declare the message class

SMTP_Message message;

//---Callback function to get the Email sending status

void smtpCallback(SMTP_Status status);

const char rootCACert[] PROGMEM = "-----BEGIN CERTIFICATE-----\n"

"-----END CERTIFICATE-----\n";

int inputPin = 4; // connect with pir sensor pin

int pir_output = 0; // variable to store the output of PIR output

void setup()

{

pinMode(inputPin, INPUT);

pinMode(LED_BUILTIN, OUTPUT);

Serial.begin(115200);

pir_output = digitalRead(inputPin);

Serial.println();

Serial.print("Connecting to AP");

WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

while (WiFi.status() != WL_CONNECTED)

{

Serial.print(".");

delay(200);

}

Serial.println("");

Serial.println("WiFi connected.");

Serial.println("IP address: ");

Serial.println(WiFi.localIP());

Serial.println();

/** Enable the debug via Serial port

* none debug or 0

* basic debug or 1

*

* Debug port can be changed via ESP_MAIL_DEFAULT_DEBUG_PORT in ESP_Mail_FS.h

*/

smtp.debug(1);

/* Set the callback function to get the sending results */

smtp.callback(smtpCallback);

/* Declare the session config data */

ESP_Mail_Session session;

/* Set the session config */

session.server.host_name = SMTP_HOST;

session.server.port = SMTP_PORT;

session.login.email = AUTHOR_EMAIL;

session.login.password = AUTHOR_PASSWORD;

session.login.user_domain = "mydomain.net";

/* Set the NTP config time */

session.time.ntp_server = "pool.ntp.org,time.nist.gov";

session.time.gmt_offset = 3;

session.time.day_light_offset = 0;

/* Set the message headers */

message.sender.name = "ESP Mail";

message.sender.email = AUTHOR_EMAIL;

message.subject = "Email Alert on Motion detection";

message.addRecipient("Anonymous",

"replace this with receiver email adderss");

String textMsg = "Motion Detected!!!!!";

message.text.content = textMsg;

message.text.charSet = "us-ascii";

message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;

message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;

/* Set the custom message header */

message.addHeader("Message-ID: <abcde.fghij@gmail.com>");

/* Connect to server with the session config */

if (!smtp.connect(&session))

return;

}

void loop()

{

if (pir_output == HIGH)

{

//----Start sending Email and close the session

if (!MailClient.sendMail(&smtp, &message))

Serial.println("Error sending Email, " + smtp.errorReason());

digitalWrite(LED_BUILTIN, HIGH);

Serial.println("Motion detected!");

Serial.println("Email sent");

}

else {

digitalWrite(LED_BUILTIN, LOW);

Serial.println("No Motion detected!");

}

delay(1000);

ESP_MAIL_PRINTF("Free Heap: %d\n", MailClient.getFreeHeap());

//to clear sending result log

smtp.sendingResult.clear();

}

/* Callback function to get the Email sending status */

void smtpCallback(SMTP_Status status)

{

/* Print the current status */

Serial.println(status.info());

/* Print the sending result */

if (status.success())

{

Serial.println("----------------");

ESP_MAIL_PRINTF("Message sent success: %d\n", status.completedCount());

ESP_MAIL_PRINTF("Message sent failled: %d\n", status.failedCount());

Serial.println("----------------\n");

struct tm dt;

for (size_t i = 0; i < smtp.sendingResult.size(); i++)

{

/* Get the result item */

SMTP_Result result = smtp.sendingResult.getItem(i);

time_t ts = (time_t)result.timestamp;

localtime_r(&ts, &dt);

ESP_MAIL_PRINTF("Message No: %d\n", i + 1);

ESP_MAIL_PRINTF("Status: %s\n", result.completed ? "success" : "failed");

ESP_MAIL_PRINTF("Date/Time: %d/%d/%d %d:%d:%d\n", dt.tm_year + 1900, dt.tm_mon + 1, dt.tm_mday, dt.tm_hour, dt.tm_min, dt.tm_sec);

ESP_MAIL_PRINTF("Recipient: %s\n", result.recipients);

ESP_MAIL_PRINTF("Subject: %s\n", result.subject);

}

Serial.println("----------------\n");

//You need to clear sending result as the memory usage will grow up as it keeps the status, timstamp and

//pointer to const char of recipients and subject that user assigned to the SMTP_Message object.

//Because of pointer to const char that stores instead of dynamic string, the subject and recipients value can be

//a garbage string (pointer points to undefind location) as SMTP_Message was declared as local variable or the value changed.

smtp.sendingResult.clear();

}

}

Note: The exact code cannot be used. As a result, before uploading the code, you must make some changes such as replacing the SSID and password with your network credentials, email address of sender and receiver, SMTP setting parameters for respective email service providers, and so on. We'll go over these details as well during the code description.

Code Description

  • The first step is adding the required header files or libraries.
  • Here we are using two libraries:
    • The first one is h, which is used to enable the Wi-Fi module and hence wireless network connectivity.
    • Another library file required is the h to enable email service over SMTP (simple mail transfer protocol).

Fig. 8

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

Fig. 9

  • Enter the SMTP parameter of the respective email service provider like, Gmail, Yahoo, Outlook, Hotmail etc. (In this tutorial we are using Gmail service).
  • Parameters used below are for Gmail.

Fig. 10

  • Enter the sender’s email login details (email address and password ).

Fig. 11

  • Insert recipient’s email address.

Fig. 12

  • SMTPSession object is used for sending emails.

Fig. 13

  • Next step is declaring a message

Fig. 14

  • This smtpCallback() function is used to get the email sending status.

Fig. 15

  • This function also includes printing the results like success and failure of email sent.

Fig. 16

  • Next we are defining a variable to store the GPIO pin number to which the PIR sensor is to be connected.
  • Next variable pir_output is used to store the current state of PIR output and initially it is fixed to zero.

Fig. 17 Variable for PIR sensor

Setup()

  • Initialize the serial monitor at 115200 baud rate for debugging purpose.
  • Set the mode as INPUT for the GPIO pin to which PIR module is to be connected i.e., GPIO 4.
  • We are using the built-in LED (LED turns ON when a motion is detected.
  • The digitalRead() function is used to read the output of PIR sensor module, by passing the GPIO pin (to which PIR sensor is connected) as an argument and results will be stored inside pir_output

Fig. 18

  • 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. 19

  • 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. 20

  • debug() is used to enable the debug via Serial port where ‘0’ and ‘1’ are used as arguments where;
    • 0 - none debug
    • 1 - basic debug
  • Inside ESP_Mail_FS.h header file, ESP_MAIL_DEFAULT_DEBUG_PORT can be used to change the Debug port.
  • Set the callback() function to get sending results.

Fig. 21

  • Setting session configuration includes, assigning the server address, port number of the server (here we are using Gmail services), email login details of the sender etc.

Fig. 22

  • Next step is setting the message header.
  • Message header will be set inside the setup() function which includes, sender’s name, subject, sender’s email address, receiver’s email address and name.
  • A string type variable textMsg is defined to to store the message to be transferred over email.

Fig. 23

  • connect() function.is used to connect to server with session configuration.

Fig. 24

Loop

  • ESP32 is continuously checking for the input from PIR sensor inside the loop function.
  • If the input received from pir sensor is HIGH the ESP32 will generate an email to the client for that sendMail() function is used and if mail transmission is failed then that will be printed on the serial monitor along with the reason.
  • The inbuilt LED on ESP32 will be turned ON and the respective results will be printed on the serial monitor.

Fig. 25 ‘If motion detected’

  • If the input received from the PIR sensor is LOW then the LED will remain LOW/OFF and no email alert will be generated.

Fig. 25 No motion detected

  • Finally, clear the email log to avoid excessive memory usage.

Fig. 26 Clear the email log

Testing

  • Open the Arduino IDE.
  • Paste the above code into your Arduino IDE.
  • Make the required changes in the code like, network credentials, email service parameters of the respective email service provider, sender and receiver email address and define the message you want to share over SMTP server.
  • Select the right development board and COM port for serial communication.

Fig. 27 select development board and COM port

  • Compile and upload the program into the ESP32 development board.
  • Connect the HCSR-501 module with the ESP32 as per the circuit/connect details given above.

Fig. 28 ESP32’s Inbuilt LED is turned ON when a motion is detected

  • Open the serial monitor with 115200 baud rate.

Fig. 29 Serial monitor

  • Check the receiver email account.

Fig.30 received email on motion detection

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

What is Edge Computing?

 Hi Friends! Hope you’re well today. In this post, I’ll walk you through What is Edge Computing?

Edge computing is the extension of cloud computing. Cloud computing is used for data storage, data management, and data processing. While Edge Computing does serve the same purpose with one difference: edge processing is carried out near the edge of the network which means data is processed near the location where it’s produced instead of relying on the remote location of the cloud server.

Confused?

Don’t be.

We’ll touch on this further in this article.

Curious to know more about what is edge computing, the difference between edge computing and cloud computing, benefits, and applications?

Keep reading.

What is Edge Computing?

Edge computing is the process where data is processed near or at the point where it’s produced. The word computing here is used for the data being processed. Simply put, Edge computing allows the data to be processed closer to the source of data (like computers, cell phones) rather than relying on the cloud with data centers. This process is used to reduce bandwidth and latency issues.

For instance, Surveillance cameras. When these cameras are required simultaneously to record a video, if you use cloud computing and run the feed through the cloud, it will increase its latency (latency is the time delay between actual data and processed data) and reduce the quality of the video.

This is where edge computing comes in handy. In this particular case, we can install a motion detector sensor that will sense the movement of the physical beings around the camera. This motion-sensing device will act as an edge device that is installed near the data source (camera). When live feed data is processed near the edge devices instead of the cloud or data centers, it would increase the video quality and practically reduce the latency to zero.

Cloud storage takes more time to process and store data, while edge computing can locally process data in less time. The market of edge computing is expected to grow from $3.5 billion to $43.4 billion by 2027, according to experts in Grand View Research. Many mobile network carriers are willing to apply edge computing into their 5G deployment to improve their data processing speed instead of picking the cloud server.

How does Edge Computing Work?

Normally in cloud computing, two components are used: the device and the cloud server. In edge computing an intermediate node is introduced between the device and the cloud server, this node is called an edge device.

How data was stored in data centers before edge computing stepped in? Yes, this is the main question to discuss before we explain how edge computing works.

Before edge computing, data was gathered from distributed locations. This data was then sent to the data center which could be an in-house facility or the public cloud. These data centers were used to process the stored data.

In edge computing that data processing is carried out near or at the point from where data originates. This is very useful for making real-time decisions that are time-sensitive. Like in the case of automatic cars interacting with each other.

Plus, less computing power is required in edge computing since we don’t need to push back all data to the data center. Like in the case of a motion-detecting sensor installed near the camera. In case we require a video of a particular instance, we need to pull out the entire information recorded inside the camera to reach that particular instant clip. However, when the motion sensor is installed near the camera that acts as an edge device, we only require that information where that sensor has detected the movement of any physical beings, and we can easily discard the rest of the information and we don’t need to store that information into the cloud server.

Know that edge data centers are not the only way to store and process data. Rather, edge computing involves the network of different technologies. Some IoT devices can become a part of this edge computing and can process data onboard and send that data to the smartphone or edge server to do the difficult calculations and efficiently handle the data processing.

Cloud Computing Vs Edge Computing

An edge computing environment is developed using a network of data centers spread across the globe. The data centers in edge computing are different than the data centers at cloud computing. In former data centers store and process information locally and comes with the ability to replicate and transfer that information to other locations. While in the latter, data centers are located hundreds of thousands of miles away. The network latency issues and unpredictable pricing model of the cloud storage allow the organizations to prefer private data centers and edge locations over public cloud.

Google Cloud, Amazon Web Services, and Microsoft Azure are the best examples of cloud computing. They use cloud computing infrastructure which is developed to transfer the data from data source to one centralized location called data centers.

While facial recognition lock feature of the iPhone uses an edge computing model. If the data in this feature runs through cloud computing, it would take too much time to process data, while the edge computing device, which is the iPhone itself, in this case, does this processing within a few seconds and unlocks the mobile screen.

For massive data storage or for software or apps that don’t require real-time processing needs, cloud computing is the better solution and is commonly called the centralized approach. And if you require less storage with more real-time processing power that is carried out locally, edge computing is the answer and is called a decentralized approach where not a single person is making a decision, rather decision power is distributed across multiple individuals or teams.

Know that companies typically harness the power of both cloud computing and edge computing to develop advanced IoT frameworks. These two infrastructures are not opposite but are complementary for designing a modern framework.

Difference between Edge Computing and IoT

Edge computing is a form of distributed computing infrastructure that is location-sensitive while IoT is a technology that can use edge computing to its advantage. Edge computing is a process that brings the processing data as near to an IoT device as possible.

Don’t confuse an edge device with an IoT device. The device is the physical device where data is stored and processed while the IoT device, on the other hand, is the device connected to the internet. It is nothing but the source of the data.

Benefits of Edge Computing

Edge computing is changing the way how data is stored and processed. This gives a more consistent and reliable experience at a significantly lower cost.

  • With cloud computing, you require more bandwidth to transfer and communicate the data between the device and cloud server. With edge computing, on the other hand, you’ll require reduced bandwidth since edge devices are installed near the data source.
  • Edge computing guarantees low latency, better quality with better control over the transmission of sensitive data.
  • Moreover, edge computing allows conducting on-site big data analytics which helps in real-time decision making. This process keeps the computing power local which means you are not dependent on the centralized system, rather this creates a decentralized approach where decision power is distributed across the local edge data centers.
  • Edge computing comes in handy where bandwidth is reduced and the connectivity is unreliable. Such as in the places like a rainforest, remote farms, ships at sea, oil rigs, and desert. In such cases, edge computing does the processing work on the site or in other cases on the edge device itself – for instance, water sensors that check the quality of the water in remote villages. When the data is computed locally, the amount of required data you need to send can be reduced significantly, requiring less bandwidth, time, and cost which may otherwise be compulsory if data is processed remotely on a centralized location.

Challenges and Risks of Edge Computing

With new technology comes new security issues and edge computing is no different. From a security point of view, data at the edge computing can become vulnerable because of the involvement of local devices instead of the centralized cloud-based server. A few ricks of edge computing include:

Hackers always seek to steal, modify, corrupt, or delete data when it comes to edge computing. They strive to manipulate edge networks by injecting illegal hardware or software components inside the edge computing infrastructure. The common practice followed by these hackers is node replication where they inject malicious node into the edge network that comes with an identical ID number as assigned to the existing node. This way they can not only make other nodes illegitimate but also can rob sensitive data across the network.

Tampering of connected physical devices in edge networks is another malpractice carried out by potential hackers. Once they approach the physical devices they can extract sensitive cryptographic information, change node software and manipulate node circuits.

Routing attach is another security risk in edge computing. This approach can affect the way how data is transferred within the edge network. The routing information attacks can be categorized into four different types:

  • Wormholes
  • Grey holes
  • Hello Food
  • Black holes

In wormholes attach, hackers can record packets at one location and tunnel them to another. In grey holes attach, they slowly and selectively delete the data packets within the network. In a hello food attack, they can introduce a malicious node that sends hello packets to other nodes, creating routing confusion within the network. While in black holes attach the outgoing and incoming packets are deleted which increases the latency.

Know that these practices can be avoided by establishing reliable routing protocols and incorporating effective cyber security practices within the network. It’s wise to put your trust in manufacturers who have proper policies in practice to guarantee the effectiveness of their edge computing solutions.

Edge Computing Examples

Edge computing comes in handy where quick data processing is required. With computing power near the data source, you can make better and quick real-time decisions.

A few edge computing examples include:

  • Facial recognition
  • Virtual or augmented apps
  • Remote monitoring of assets in the oil & gas industry
  • In hospital patient-monitoring
  • Cloud gaming
  • Content delivery
  • Traffic management
  • Smart homes
  • Surveillance or security cameras
  • Alexa or Google assistant
  • Industrial automation

Predictive maintenance is another example where edge computing can play a key role. It helps to identify if the instrument needs maintenance before its major failure or total collapse. This saves both time and money which would otherwise require for entire instrument replacement.

Conclusion

Edge computing becomes common practice among many organizations since it provides more control over processed data.

This trend will continue to grow with time and it is expected by 2028 edge services will become widely available across the globe.

Wireless technologies such as WiFi 6 or 5G will work in favor of edge computing, giving chance to virtualization and other automation capabilities, at the same time making the wireless network more economical and flexible. Many carriers are now working to incorporate edge computing infrastructure into their 5G developments to provide fast real-time processing capabilities, particularly for connected cars, mobile devices, and automatic vehicles.

It is not about which one is better cloud computing or edge computing. It’s about the requirement. If you want data to be processed quickly near the source, you’ll adopt edge computing and if you want more data storage and data management, you will pick cloud computing.

The prime goal of edge computing is to reduce bandwidth and practically reduce the latency to zero. With the extension of real-time applications that require local computing and storage power, edge computing will continue to grow over time.

That’s all for today. Hope you find this article helpful. If you have any questions, you can reach out in the comment section below. I’d love to help you the best way I can. Thank you for reading this article.

What is Industrial IoT (Internet of Things)

Hi guys! Hope you’re well today. In this post today, I’ll cover What is Industrial IoT (Internet of Things?)

IIoT is now a talk of mainstream conversation. This term has blown up in the past couple of years. Before we move further to describe IIoT, it is evident that industries are no longer dependent on the traditional production processes that happened to be costly and guaranteed no optimal results. Now companies are willing to incorporate automation in manufacturing and production processes. Smart systems, no doubt, are dangerous for the traditional labor workforce, but on the other hand, they create more opportunities for the people equipped with the latest business trends.

Curious to know more about Industrial IoT, how does it work, the difference between IoT and IIoT, examples of IIoT, the impact of IIoT on jobs and workers, and the advantages of IIoT?

Keep reading.

What is Industrial IoT?

The Industrial Internet of Things, also known as Industry 4.0 or Industrial Internet, is the use of smart connected machines, embedded sensors, and actuators mainly used to enhance the overall efficiency and productivity of manufacturing and production processes.

At its core, it is used to automate processes for the production of optimal products that build a strong connection with the customers and create new revenue streams. Automation leads to accuracy and better efficiency and removes the likelihood of error that is difficult to attain by a simple human workforce. The Industrial IoT is used across a range of industries including manufacturing, oil and gas, logistics, mining and metals, transportation, aviation, energy/utilities, and more.

How does Industrial IoT work?

The smart devices deployed in Industrial IoT are used to capture, store and analyze data in real-time and that data is delivered to the company leaders to make faster, smarter business decisions.

A typical Industrial IoT system contains:

  • Intelligent systems are used to store and capture data.
  • Connected internet devices are used as a data communication structure.
  • Analytical applications that guarantee optimized processes by using that raw data.
  • Tools that allow managers and decision-makers to use that data for better decisions.

For example, I own a PCB manufacturing industrial unit. And I want to know which types of PCBs are most popular among customers. With IoT technology I can:

  • Use sensors to find out which areas of the industry are most crowded by the customers.
  • Hunt down the sales data to figure out which types of PCBs are selling faster.
  • Make sure demand and supply align so popular PCBs don’t go out of stock.

The information gathered by the smart devices helped me to make better decisions on which items to stock up on which ultimately helped me save both time and money.

Difference between IoT and IIoT

  • Both IoT and IIoT work on the same principle: using a network of intelligent devices and sensors for collecting, storing, monitoring, and analyzing data.
  • IIoT is nothing but an extension of IoT. The IoT is mainly used for commercial and domestic purposes, making the consumers’ life more easy and convenient. You can see its applications in wearable devices, smart microwaves, fitness devices, self-driving cars, and smart home automation systems.
  • While IIoT, on the other hand, is employed for increasing the productivity and overall efficiency of the industrial units. The set of smart devices and sensors used in IIoT collect and analyze data, automate production processes and guarantee a secure atmosphere by providing information in advance about industrial units that need maintenance.
  • The IIoT can be employed in supply chain robots, transportation and construction vehicles, agricultural systems, solar and wind power and smart irrigation system, and more.

Industrial IoT Examples

You’ll find a range of Industrial IoT examples. A few of them include:

  1. Predictive Maintenance

When a certain industrial process or a piece of instrument is at the brink of total failure, preventive and proactive maintenance is applied to allow a quick fix to the problem beforehand. This saves both time and money which otherwise results in costly instrument replacement. Traditional methods are obsolete to identify the problem in advance since they often required access of labor to remote places to perform manual testing. With IIoT, you get an alert when the problem starts developing, which provides a valuable insight into whether the instrument requires overhauling or complete replacement.

  • For instance, industries that manufacture elevators now install multiple sensors inside the product to make sure any problem can be identified before it halts the business operations. These sensors communicate with the cloud environment through data points that provide earlier automated notifications to the company technicians. This way any issue can be fixed in advance before it escalates to serious consequences.
  1. Process Automation

Automating the process is the main takeaway of employing IoT in industrial settings. When industrial processes are automated and involve no human intervention, it removes the likelihood of errors and improves operational productivity, and reduces overall production costs.

  • Only those industries excel and grow, that can produce maximum output with the minimum cost. In most industries, the energy cost is 30 to 50 % of the total cost of production processes. With process automation, the computer programs take inputs from the installed sensors and streamline the process that guarantees the optimal strategy for the plant. What makes these computer programs super important is their ability to learn from the given data and predict future trends to speed up the production process tailored to the changing conditions. The software directly controls the industrial equipment and allows it to move at a speed requiring minimum energy. Moreover, it also predicts if preventive maintenance is required, hence less energy, cost, and time is required to stop and restart the industrial unit for the regular inspection.
  • A smart irrigation system is another great example of IIoT used by farmers. Soil moisture and weather conditions are key factors to identify when watering is required for the crops. Soil moisture sensors are installed that provide moisture readings and send alerts to the system that automate the watering process. This way resources are used properly and more efficiently.
  1. Remote Monitoring

Remote monitoring is challenging for the industries. With traditional methods, not only is it difficult but also inefficient and risky. The businesses require consistent monitoring of the instruments working out in the field. Manual testing is risky since the field environment is often occupied with lots of heat, vibration, or humidity. And the access of humans is not recommended to those places.

  • For instance, tanks at production oil wells require consistent monitoring to identify if there is overflow which can be dangerous and often result in expensive cleanup costs. To minimize the risk and ensure a secure working environment, the company can install an IoT system that comes with an automated tank monitoring solution that monitors level readings and sends this data to the on-field engineer for managing pickups and deliveries. Moreover, it sends alerts for predictive maintenance based on the level readings and actual data. Using this method, companies don’t require any consistent physical existence of the human being on the field except when required.
  • In agriculture, it is often required to evenly distribute water across crop fields. Center pivots are mainly used for this purpose where water is sprinkled on the crops when center pivots move in a circle. Any damage to this center pivot can cause a loss of millions of dollars in revenue. Remote monitoring of the water pressure inside the center pivots can provide an insight into the disconnected fittings and leakage. Alerts and notifications are then sent to the farmers that take proper steps to nurture crop growth and avoid issues in advance before they aggravate a serious problem.

Impact of IIoT on workers and jobs

With the inception of digital technology, workforce transformation is on the rise. This new wave of technology, no doubt, removes the need for certain jobs but it also creates the possibility of generating new ones. According to the survey of business leaders in Accenture, this new digital era will create more jobs than it will eliminate.

The Industrial IoT provides scores of opportunities in optimization, automation, smart industry, intelligent decision making, industrial control, asset performance management, and in the sectors directly dealing with the customer’s behavior. They strive to create an environment tailored to the exact customer’s needs and demands so they keep coming back for what industries have to offer.

The IIoT makes the processes more efficient and improves productivity. It advocates for smart work, not hard work. Plus, the smart devices in IIoT removes the possibility of errors that may otherwise affect the production process if the traditional workforce is employed. Automation can gather data from hard-to-reach places, even reducing the risks to human lives. When a worker knows, they will get a notification on the smartphone about the tank leakage or the certain equipment that needs replacement, which means danger can be predicted in advance before it goes catastrophic.

This leads us to the conclusion: to survive in the ocean of digital transformation, it’s obligatory to equip yourself with the latest trends in engineering and information technology and liberate yourself from traditional research and development processes.

Advantages of Industrial IoT

There are many advantages of industrial IoT and low operating cost tops the list. With IIoT, you no longer need the physical presence of a human that requires monthly wages, paid leaves, healthcare costs, and holidays. Moreover, it doesn’t require commissions, monthly bonuses, and pensions that are compulsory if you induct human employees into your industry. More advantages of IoT include:

  1. To run production units consistently, companies need hundreds of employees in rotation for all three shifts and the plant still shuts down for maintenance and holidays. With IIoT, industrial units can run all day without any break 24/7 and 365 days a year. The plant only closes down when the maintenance is needed which is different than the regular maintenance since in this case maintenance is only needed when IoT sends alerts about the critical process or a piece of unit risks failure.
  2. When humans are employed in the industrial unit, there is always a likelihood of error no matter how hard they try to thwart it. With smart systems, no such errors occurred which guarantee the uniform and optimum quality of the products.
  3. With IIoT, manufacturing processes are more flexible. If you employ a worker for any task, you need to give them training in advance to get a hang of the entire instrument. Robots don’t require such training. They only need a program to perform any task.
  4. Industrial automation ensures the safety and security of human beings. Companies no longer need humans to send them to hard-to-reach places that are subjected to high risks like high temperature, vibration, and pressure. With IIoT you can remotely check the status of instruments on the field.
  5. Automated processes come with high precision and accuracy. They depend on the data gathered by sensors and streamline the overall industrial process based on the given information. Everything is done and controlled by the connected devices and no human intervention is involved which removes the possibility of error.

Conclusion

Industries have been incorporating automation into their production and manufacturing processes.

And this trend will increase over time and you’ll witness more industries are stepping into the realm of automation.

Industries are committed to upgrading their system and instruments to keep up with the modern trends and to make a footing in disruptive technologies.

This process is, no doubt, more efficient, delivers better results, maintains product quality, and is more economical. Even though it requires a high initial cost, it doesn’t need a regular labor force, reducing the overall operating cost of the processes.

If you want to make your worth in the industry, it is wise to keep you updated with the latest industry trends to make sure you’re not left out in the traditional industry jobs.

That’s all for today. Hope you find this article helpful. If you have any questions regarding IIoT, you are most welcome to ask in the section below. I’d love to help you the best way I can. Thank you for reading this article.

How to use Strings in Python?

Welcome to the fourth lesson of this python course. Our previous session taught us how to utilize the print function in python, so we have a firm grasp of the terminology and the functions themselves. In this lesson, we'll cover a few more Python terms, such as:

  • Strings
  • Operators
  • Input function

Also, we'll build a simple program to print out an imagined dog so that we may better grasp how these concepts are employed. So, let's get started now.

Why do we need to understand these terms?

Programming is a lot like building a structure out of blocks. Even with just a few types of children's toy blocks and some time and imagination, you can build anything. Because we'll be utilizing these phrases all the time in programming, it's critical that you know what they mean and how to use them.

What exactly are the strings?

An alphabet, word, or other character collection is referred to as a "string." As one of the most fundamental data structures, it serves as a framework for manipulating data. An in-built string class called "str" is available in Python. After they've been produced, strings are "immutable," which means that they can't be rewritten. Because of the immutability of strings, we must generate new ones each time we want to represent newly computed values.

Quotes are used to denote a string. There are a variety of ways to accomplish this:

  • Single quotation marks, as in the following example: For "double" quotations in your string, use "single" quotes."
  • Use double quotation marks. Using single quotations in your string is easy with double-quotes.

"Double quotes allow you to embed 'single' quotes in your string."

  • If you want to use triple quotes, you can do so in the following way: (""" """), (''' ''')

Triple quoted strings to make it possible to work with a set of multiple-line strings and include all of the whitespaces that accompany them.

The fact that a string cannot be changed results in an error if you try to do so. The adjustments require the creation of a new string.

Instead, use this method.

The built-in len() function can be used to determine the length of a string:

String slicing in python

Strings can be sliced and indexed since they are a sequence of characters. A string's indexing starts at 0 and is based on each character in the string.

The initial character in the string is C, which is located at position 0 of the index. The final syllable is a period, which is the string's sixteenth character. When you want to access characters in the opposite direction, you can use -1 as an index. when it's strung together, Chocolate and cookie are separated by a whitespace, which has its own index, 9 in this example. Slicing is a good way to verify this.

For the same reason as for other sequential data types, you can read and manipulate Python strings using their associated index numbers. It is possible to slice an object using its index values in Python to select a specific element or a subset of elements. You don't have to write a loop expression to identify or access specific substrings in a string. Slicing does this for you automatically.

Suppose you were trying to find the cookie substring in the following string. What's the best way to go about it?

Range slicing is used in these situations. The range slicing syntax is as follows:

Alternatively, you might use a negative stop index:

In this case, when you slice a sentence without giving an end index, you get characters from the first index to its last. In the same way, slicing a string without a starting index indicates that you begin at the beginning and end at the end.

Additionally, the stride parameter can be accepted by string-slicing as a third argument, which specifies the number of characters to advance once the initial one is picked from the string. In the default configuration, stride has a value of 1.

stringnu = "1020304050"

print (stringnu [0:-2:2])

Striding allows you to reverse a string, which is a really cool feature. With a stride of -1, you can begin at the end of the string and move forward one character at a time. With a value of -2, you can start at the end and move two characters at the same time.

String operations

String operations such as slicing and range slicing are frequent. As simple as adding, string concatenation is also available.

Concatenating a string with another data type, on the other hand, will fail.

You attempted to concatenate an integer value with a string, which is not permitted. Integer addition or string concatenation is not understood implicitly by the interpreter. However, give this a try:

The reason for this is that you used concatenation after you turned the integer into a string.

A string can be repeated using the * method.

wordsig = 'hip '

line1 = wordsig * 2 + 'hurray! '

print (line1 * 3)

To manipulate strings, Python comes with several built-in methods and utility functions. It is possible to use these built-in techniques to replace substrings, to put some words in a paragraph in capital letters, and to locate the position of a string within another text.

  • capitalizes the first character in the string returned by capitalize().
  • islower(): will return true/false when all characters in the string are lowercase/uppercase.
  • If a substring is passed to find(substring), it will be returned at the string's lowest index. When searching for substrings, you may optionally specify a start and end index for each location in the string that you want to search for. If the substring is not found, it returns -1.
  • count(substring) returns the number of times a substring appears in the string. The string's start and stop indexes are also programmable.
  • isspace() When the string has a whitespace character, the value is true. Otherwise, it is false. A space, a tab, and a new line are all whitespace characters. When working with real-world datasets, this can come in handy because the proper spacing may not be encoded properly during format conversion.
  • A function called lstrip() eliminates all leading whitespace from a string. It's a feature that comes in handy when dealing with real-world datasets.
  • If the string contains just digits, isdigit() returns true; otherwise, it returns false.
  • All instances of the substring are replaced with new using replace (sub-strings, new). A third argument, max, can be specified to replace as many of the substring occurrences as the value of max allows in the string. This is not an in-place replacement, so the immutable attribute of the string remains intact.
  • split(delimiter="") provides a list of substrings based on the specified delimiter (or a space if none is provided).

Python string formatting

Multiple string formatting options are available in Python. To better understand these formatting strings, let`s dive right in.

% Format

Python has a built-in modulo percent operation. The interpolation operator is the name given to it. There is a percent followed by the data type that must be prepared or transformed. This operation then replaces the word "percent datatype" with one or more components of that type:

Percent d is used for integers, whereas percent s is used for strings; you've seen both. Octal values can be converted to octal equivalents with this type of conversion, as can Hexadecimal values with this type, and Floating-Point Decimal Format with this type.

Python string formatter class

One of the built-in string classes is the formatter class. The format () method can be used to perform sophisticated variable substitutions and value formatting. Rewriting public methods such as format () and vformat () allows you to build your own string formatting techniques (). There are a number of methods that are designed to be replaced by subclasses, such as parse (), get field, get value, check unused arguments, format field, and convert field ().

Template strings

Templates allow substitutions based on dollars rather than percentages. A major reason for template syntax creation in Python Version 2.4 was that, despite the strength of percent string formatting, errors are easy to make, because the forms that follow '%'are extremely restrictive. This is a common blunder when it comes to percent formatting: forgetting to include the e in percent (variable).

substitution () and safe_substitute() are two methods specified within templates (). You can use them in the following ways:

Safe substitution () is an advantage to employing a template, in addition to other advantages.

String literal formatting

In Python 3, this is yet another way to format strings. A prefixed 'f' or 'F' string literal is known as a formatted string literal or f-string. Within curly brackets, you may include identifiers that will be utilized in your string.

What's the point of adding another string formatting option? well, this is because practicality and simplicity are appealing.

To demonstrate why f-strings are the best way to format strings in Python, check out the examples below.

Please note that the preceding code is only compatible with Python 3.6 and above. With f-strings, Python expressions can be used inside curly braces, which is a significant benefit of using them.

What's the point of having so many string formatting options?

Syntax is the most important consideration here. For the most part, it boils down to the trade-off between simplicity and the amount of verbosity you're willing to sacrifice. People with a C programming background will find it easy to use the percent sign to format strings, for example. Using the format () function can be more verbose, but it provides a wider range of options.

Input function with strings

While your application is running, you can utilize input routines to get data from the user. A key benefit of this approach is that it does not rely on preexisting values or file content to function. The syntax for the input function is as follows.

input([prompt])

Input functions will cause our application to pause. After the user inserts the text into the Python shell or command line, the application resumes.

input(message)

In order to prompt the user for text, you'll need to provide a message. It's important that a user understands what they need to do by reading this message. As a result, a user may wonder why the software isn't progressing. For example,

input ("Enter email address: ")

print ("Confirm it is your email address:")

In order to request an email address from a user, we've implemented the input () method. Messages in brackets are displayed on the same line where a user is expected to enter text in the command line.

Note that as soon as a user inputs data into the input () function, it is automatically converted to a string.

How to draw an imaginary dog.

Using the fundamentals of strings that we've learned in this lesson; we'll construct a simple program that prints out an image of a dog.

Let's open up our favorite coding editor, Atom, and get started. Before looking at the solution, I advise you to give it a shot on your own.

  • Step 1: In the code editor where the hello.py file is loaded, write the print function () to print out the upper body of our dog image.
  • Step 2: Insert double quotes or single quotes inside the print function. This shows the output will be a string.
  • Step 3: Write "o" in the speech marks.
  • Step 4: Close the speech marks and reopen the speech marks. This is because we want to add another string to the same print function. Add hyphens to represent the neck and upper body.
  • Step 5: Add a plus sign between the strings to concatenate the strings.
  • Step 6: Create another function to print the legs. Same way we did the upper body, we will now print the legs. Inside this function, we create a string and write four slashes to represent legs. Now our dog program is complete, save the file and run the code using one of the methods we learnt in the previous tutorial. The results should be:

Conclusion

Congratulations! You've made it this far. You have learned about string slicing, what strings are, and explored a variety of string-related processes. Many approaches to formatting strings have also been discussed. But don't forget that practice is the key to mastering any skill! I'll see you in the next tutorial.

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