Hello friends, I hope you all are doing great. Today, we are going to start Section-III of our Raspberry Pi 4 Programming Course. In this section, we will interface different Embedded Sensors with Raspberry Pi 4. Today's our first lecture in Section-III, so I am going to interface a simple LDR sensor with RPi4.
So, let's get started:
The following items are required to finish this Raspberry Pi photoresistor module guide. You don't need a breadboard to accomplish this, but having one would be helpful.
It is a common practice to employ photoresistors to determine the presence or absence of visible light or to quantify the amount of light hitting a particular surface. Their resistance is exceptionally high in the dark, reaching up to 1M ohm, but when subjected to light, the LDR sensor's resistance reduces rapidly, often to only a few ohms. Light-dependent resistors (LDRs) are nonlinear devices whose sensitivity shifts depending on the incident wavelength of light. To protect their ecosystems, some nations have outlawed the use of lead and cadmium in LDRs.
By analyzing the electromagnetic radiation in the "Infrared", "Visible" and "Ultraviolet" regions of the electromagnetic spectrum, Light Sensors can produce an output signal indicative of the brightness of the surrounding light. A passive device called a light sensor transforms this "light energy," which can come from either the visible or infrared regions of the spectrum, into an electrical signal. Because they convert the energy of light (photons) into a usable form of electricity, light sensors are also referred to as photoelectric devices or photo sensors (electrons).
There are two primary types of photoelectric devices: those that produce electricity when exposed to light (photovoltaics, photoemissive, etc.) and those that modify their electrical properties when exposed to light (photoresistors, photoconductors, etc.).
The light-dependent resistor (LDR) sensor is used to detect the intensity of light in the surroundings. The LDR is a device constructed from a sensitive semiconductor material i.e. cadmium sulfide, which undergoes a dramatic shift in electrical resistance when exposed to light, going from several 1000 Ohms in the dark to just a few Ohms, when illuminated.
Most photoresistive light sensors employ cadmium sulfide(CdS). However, other semiconductor substrate materials like lead sulfide (PbS), lead selenide (PbSe), and indium antimony (InSb) can detect light intensity as well. Since cadmium sulfide has a spectral response curve similar to the human eye's and can be modulated with a handheld torch, it is utilized to create photoconductive cells. The peak wavelength at which it is most sensitive is typically between 560-600nm (nanometers), making it part of the visible spectrum.
The ORP12 cadmium sulfide photoconductive cell is the most widely used photoresistive light sensor. This photosensitive resistor's spectral response is concentrated around 610 nm in the yellow-to-orange part of the spectrum. When the cell is in the dark, its resistance is extremely high at around 10M's, but it drops to about 100's when illuminated (lit resistance). As the resistive path zigzags across the ceramic substrate, the dark resistance increases and the dark current drops. Because of its low price and wide range of possible applications, the CdS photocell is frequently used in auto-dimming systems, light- and dark-sensing controls for streetlights, and photographic exposure meters.
Below is an illustration of how a light-dependent resistor can be used as a light-sensitive switch.
This simple circuit for detecting light consists of a relay activated by exposure to sunlight. The photoresistor LDR and the resistor R1 make up a potential divider circuit. In the absence of light, the LDR's resistance rises into the Megaohm (M) range, and as a result, the transistor TR1 receives zero base bias, turning the relay off. The LDR's resistance drops in response to more light, elevating the base bias voltage at V1. When the base bias voltage of transistor TR1 reaches a certain threshold, as defined by the resistance R1 in a potential divider network, the transistor turns "ON," activating the relay, which controls some external circuitry. With a return to darkness, the LDR's resistance rises, reducing the transistor's base voltage and turning "OFF" the transistor and relay at a predetermined level of illumination established by the potentiometer circuit.
Changing the relay's "ON" or "OFF" point to a custom brightness is as simple as swapping out the fixed resistor R1 for a potentiometer VR1. The switching end of a simple circuit like the one depicted above may need to be more consistent owing to fluctuations in temperature or supply voltage. Using the LDR in a "Wheatstone Bridge" configuration and substituting an Operational Amplifier for the transistor makes it simple to construct a light-activated circuit with increased sensitivity.
To build the circuit of the LDR sensor with RPi4, follow these instructions. You can also refer to the
below
circuit diagram:
Now is the time to start writing Python code for LDR:
This project's code is simple and will let us know whether it's bright outside, partly cloudy, or overcast. The lack of analog inputs on the Pi is the primary limitation of this device. So far, we have only worked on the digital modules, but here we need an analog pin to get a reliable reading of the input resistance variation. So, we'll count how long the capacitor takes to recharge and then set the pin high. This is a quick but unreliable way to gauge the ambient light level.
Here I will quickly go over the code for the LDR sensor with Raspberry Pi. As a first step toward establishing a connection with the GPIO pins, we import the necessary GPIO package. The time package is also imported, allowing us to schedule script inactivity.
#!/user/local/bin/python
import RPi.GPIO as GPIO
import time
Next, we change the GPIO modes to GPIO.BOARD so that the pins used in the script match the hardware. One variable only needs to be set because there is just one input/output pin. If you use a specific GPIO pin, assign its number to this variable.
GPIO.setmode(GPIO.BOARD)
#define the pin that goes to the circuit
pin_to_circuit = 7
The following function we'll look at is RC time, and it takes a single input: the circuit's PIN. In this code, we set the value of a variable named count to zero, and then, when the pin is set to high, we return that number. Our pin is then configured as an output before being brought low. Then we let the program rest for ten milliseconds. When this is done, the pin is converted to an input, and a while loop is started. In this loop, the capacitor is charged until it is around 3/4 full, at which point the pin swings high. Once the pin is set to high, we send the count back to the primary method. This number can be used to toggle an LED, trigger an action, or be stored to compile data on brightness fluctuations.
def rc_time (pin_to_circuit):
count = 0
#Output on the pin for
GPIO.setup(pin_to_circuit, GPIO.OUT)
GPIO.output(pin_to_circuit, GPIO.LOW)
time.sleep(0.1)
#Change the pin back to the input
GPIO.setup(pin_to_circuit, GPIO.IN)
#Count until the pin goes high
while (GPIO.input(pin_to_circuit) == GPIO.LOW):
count += 1
return count
#Catch when the script is interrupted, clean it up correctly
Try:
# Main loop
while True:
print(rc_time(pin_to_circuit))
except KeyboardInterrupt:
pass
finally:
GPIO.cleanup()
Even though this is a trivial procedure, I'll run through it fast so you can get it up and work on your Pi without any hiccups. I am employing Raspbian, the operating system used in all the guides here. Read my Raspbian installation instructions if you need assistance. In most circumstances, all the necessary software will already be installed. Using git clone, the source code can be downloaded. Here's a command that will carry out your request.
git clone https://github.com/pimylifeup/Light_Sensor/
cd ./Light_Sensor
The code can also be copied and pasted, but only into a Python script. When working with Python code, my preferred text editor is nano.
sudo nano light_sensor.py
To save your changes and leave the file, press CTRL+X then Y. Finally, the following command will execute the code.
sudo python light_sensor.py
Hopefully, you've fixed the script and are now getting readings that accurately reflect the light levels on the sensor. Be bold about posting a comment if you need help.
A light sensor can be implemented in a variety of circuitry contexts. Some that sprang to mind when I was penning this guide are as follows:
An LDR can detect the onset of daylight, allowing for the activation of an alarm to rouse you from sleep. With a reliable program and sensor, you may set the alarm to increase in volume as daylight fades gradually. One way to keep tabs on your garden is to use a light sensor to measure how much sun each section of your garden is getting. This could be helpful knowledge if you're planting anything that needs a lot of sun or vice versa. Using the Room Monitor, you can ensure the lights in a particular room are switched off whenever no one is there. This might be set up to send you an alert if the light is found in an unexpected place.
This fantastic sensor has a wide variety of applications. However, if you need something more precise than a photocell, consider the Adafruit dynamic range sensor. You had no trouble installing this light sensor on your Raspberry Pi. Please comment below if you have any issues or suggestions or think I need to include something. In the next section, we'll see how to interface a Soil Moisture Sensor with Raspberry Pi 4. Till then, take care. Have fun!!!
Modern digital business needs reliable feature flag management. You probably already know that since you're here reading this article. Read it in full, then, and discover what to expect from a real-deal feature management software your company can most certainly benefit from.
Feature flags, also known as feature toggles, are a software development best practice that enables developers to safely and rapidly roll out new features in production. Feature flags provide teams with the ability to easily turn features on or off without having to deploy new code. This allows teams to quickly develop, deploy, and run experiments on their application while minimizing the risk of an unstable deployment. Feature flags can also be used to enable A/B testing and canary releases.
Releasing new features confidently is a goal. Many development companies aim at it, but at the same time they want to avoid a crisis that usually comes from bad execution of new ideas. Any software can be ruined by a single update, you know. What's more, modern consumers will not hesitate to ditch a product with faulty functionality. Restoring confidence is sometimes more difficult than building an app from the scratch. That's why the digital industry must be cautious. Luckily, a pro feature management tool can reduce the risk by providing means for delivering new features available to users selectively and with a certain amount of subtlety.
The above allows test execution, including A and B testing. Different user segments provide responds that are often negative, but they are valuable. Smart feature deployment is all about getting the data from the user-side, making adjustments without a massive crisis in case of a failure. This is why a good feature management software is an essential investment for any serious company from the digital industry.
There are many feature management tools out there, but not all of them are actually worth their price tags. The thing is, it must be a comprehensive product. Feature releases can become a complicated process, especially when software development teams work on large projects that consist of layers upon layers of code. It is not unusual these days that a digital endeavor is, in fact, a cluster of products cooperating with each other. Therefore, truly the best feature management software ought to provide an ability to control all these processes. A surprisingly cheap or even free feature flagging platform will be limited to basics only. Basics, however, are not enough nowadays.
Reliability is crucial, of course. Complex feature release management mustn't be based on unstable solutions. An experimental feature itself has a right to be faulty, but a tool that delivers it must be tough as nails. So, where to find professionally complete and reliable feature flagging software? Try this address for starters: https://www.getunleash.io/feature-management.
If you plan to run a start-up, it helps to have some basic understanding of IT management. Here are some key pointers on how best to manage your business IT systems:
You should know how your IT systems work and how they can be managed. This will help you keep them working well, which is especially important if your business depends on them for important functions like payroll or customer service. The earlier in the process that someone understands their role and responsibilities in running the company's technology, the better off they'll be when troubleshooting problems arise later on down the road.
Make sure your hardware and software are secure.
Ensure that you have the right licenses for your software.
Use cloud storage for your data security and recovery.
Conduct regular backups using your cloud system or external hard drive
Use a firewall to protect your network from unauthorized access.
Install antivirus, anti-spyware and anti-malware software on each computer (and smartphone) in the organization so that all data can be protected from outside threats.
Cloud storage is one of the best ways to store your data in a secure, accessible and reliable way. Further, Cloud storage makes it easy to access your files from anywhere and at any time. It reduces costs because you don’t need to buy or maintain expensive hard drives, which means that you can save up money for other things like marketing materials or new equipment.
Cloud storage also has some great benefits: like It keeps your information safe from hackers who might want access to it so that they can steal it or sell it on black market sites.
It's important to have a backup of your company's data , which is why you'll need to take steps to ensure that it doesn't get lost or damaged. The most basic way of backing up your files is by using an external hard drive or USB. If you're using the cloud system provided by your hosting provider, then there is also an option for automatic backups (but this might not be suitable for all businesses).
You should also keep in mind that not all kinds of information will fit onto one computer file—for example, some documents contain links between multiple pages; others have embedded images that could be lost if they weren't backed up before being deleted from their original source material.
If you need help with an IT issue or have technical questions, it is essential to get it resolved quickly. This can be a time-consuming process and require specialist skills that many startups don't have in-house.
It's also important to keep your business running smoothly as well as making sure that any problems are dealt with promptly by the right people at the right time (and not just left until later). While hiring an IT expert may seem like a great idea at first glance—especially if they're willing to offer their services for free—it's more likely that you will end up spending more money than you would have had by using other options.
It's important to understand how your IT systems work, so that you know what services you need from providers and how to keep them working well. This will allow you to make informed decisions about what kind of support is required in the future. If a provider offers a specific service or product, then it might be worth considering whether this meets your needs rather than buying something else that does not meet those needs directly. For this purpose you can use different IP for different locations to get best advantages from expertise. You can also use IP from Saudi Arabia to check
any issue regarding IT management if your clients are based in UK or USA. You can also hire expertise from these locations too.
Because If there are any areas where an expert could help with advice or training then this would also be beneficial for both parties involved - especially if there are technical problems with one part of the system which could be fixed by someone who has experience with similar systems elsewhere.
If you are planning to run a start-up, it helps to have a basic understanding of IT management. Make sure your hardware and software are secure, use cloud storage for your data security and recovery, get IT support when you need it - both for advice and for technical issues. This is absolutely essential if you’re not an IT expert yourself.
Hey pupils! Welcome to the new tutorial on deep learning, where we are in the section on Python learning. In the previous lecture, we were discussing the tuple data type, which is a sub-class of sequences. In the present lecture, the discussion will be about the byte sequence and byte array. The whole discussion is cleared with the help of practical implementation in TensorFlow by using simple and easy codes. If you understand the concepts of list and tuple, then this lecture will be easy for you. Yet, before going into the details of this topic, you must know the highlights of the content discussed in this lecture:
What is the byte method in Python?
How can you use byte in TensorFlow?
What are some examples of bytes?
Give examples of error handling in bytes.
How can you convert integers into bytes?
What is a byte array?
What is the difference between bytes and byte array methods?
Moving towards our next sequence is the byte method which has interesting applications in Python programming. A byte is the collection or group of byte numbers and it can hold multiple values. The interesting thing about the byte is, these can not hold the negative numbers that are, the values in a byte can not have the minus sign with them. One must keep in mind that these have a range between 0 and 255 only and you can not store more or fewer values than this range. For example, if you want to add 267 or -56 in a byte, this is not possible in it. The main purpose of using this function is to convert an object into an immutable byte-represented object of which, the data and size are specified by the programmer.
To make sure you are getting the whole concept, let us practice it on TensorFlow. To start, have a look at the instructions:
Search for the “Anaconda Navigator” in your windows search panel.
In the environment section, search for the Jupyter Lab.
Launch the lab and wait for the browser to show you the local host on your browser.
Go to the new cell and start coding.
You have seen we made a byte with the different types of elements in it. Now, what if we made the byte with values that exceed its values? Let us check it with the help of the following code:
The byte is a method and to use it well, the syntax must be known. For using it, there must be three parameters that have to be decided before starting, the detail of syntax and the parameters is given next:
byte(src,enc,err)
Here, the three parameters are defined:
src=The object that has to be converted. It is the source object and has superficial characteristics.
enc= it is the encoding that is used only when the case object used in the formula is in the form of a string.
err=If the error occurs during the conversion of the string is not done properly in the step mentioned before then, the logic given here will be used to overcome this error.
Now, using the information given above, we are going to discuss the example to elaborate on the whole process. The bytes when displayed on the output have a small be with them to show it is a byte. Just look at the code below and we are going to tell you the detail after that.
msg = "We are learning Python"
string = bytes(msg, 'utf-8')
print(string)
Here, in the first line, the message is declared and stored in the variable with the name ‘msg’.
The byte function is used in the second line and as the two parameters, we are using the message declared first as the source and the encoding technique is the utf-8.
The result of this function is then stored in the variable ‘string’.
The results are printed at the end. The small b at the start of this message indicates that it is a byte and single quotation marks are the indication that our result is a string.
Here, utf-8 is the indication of the Unicode transformation format, and it is encoding the string into an 8-bit character. So, in conclusion, we can say that a byte is used to convert the string message into an 8-bit character string. The application of the byte function is at a higher level of programming.
Now moving towards the next example, let us check for a relatively large code. This code gives us a demonstration of how we can use different cases of coding in a single piece of code and we will use here the empty byte, number-to-byte conversion, and list-to-byte conversion using single lines.
num = 4
list = [23,76,23,78,34]
#conversion with no argument
print ("Byte conversion with no arguments : ", (bytes()))
# conversion of number into string
print ("The integer conversion results in : ", (bytes(num)))
# conversion of list into string
print ("The iterable conversion results in : " , (bytes(list)))
The number is converted into bytes as expected, and when we try the same method for the list, where a group of numbers are to be converted into bytes, this function is capable of doing so. The output is strange for the non-programmers but the conversion is perfect here.
As we have mentioned earlier, the string is converted with the help of the byte function, but error correction is important in this case. There are some keywords that are suggested as error correction techniques. All of these will be discussed in the next section.
The second parameter of the byte tells us that we have to provide the encoding scheme, but what if the encoding process is not completed due to some error? The method parameter specifies the way to handle that error, and there is more than one way to handle it; therefore, here are the details of each way to handle the error for you. Keep in mind, coding is a vast field and the whole control is in the hand of programmers. Thus, not all errors are handled with the same kind of solution, so you must know all the ways.
The first error handler on the list is the "strict" keyword. It is used when the programmer wants to get the Unicode decoder error when the compiler is not able to convert the string into a byte.
The second error handler in the list is the keyword “ignore." What do you do when any procedure is not under your control and you are not able to do your duty? In the case of the compiler's workings, when it is faced with the same situation, it ignores the part with the error and moves towards the next line. In this way, the result obtained is not complete, but you get the answer to other parts of the code. It works great in many situations, and sometimes, you get interesting outputs.
The third one has a nice implementation of error handling. With the help of this handler, the error that occurred in the string will be replaced by a question mark, and then the compiler will move towards the next character. In short, the error will be gone, and instead of skipping the error, there will be a question mark that will indicate the error.
All the discussions above will be cleared up with the help of the code given in the next line. The error in all the problems is the same, but the outputs—or, in short, the way the compiler deals with the error—are changed.
#Declaring the variable with the string having the error in it.
MyString = 'PythonfÖrDeepLearning'
# using replace error Handling
print("Byte conversion with replace error : " +
str(bytes(MyString, 'ascii', errors='replace')))
# Giving ascii encoding and ignore error
print("Byte conversion with ignore error : " +
str(bytes(MyString, 'ascii', errors='ignore')))
#using strict error Handling
print("Byte conversion with strict error : " +
(bytes(MyString, 'ascii', errors='strict')))
Here, when we talk about the “strict” error handler, we get this error with the pink box because it is just like a simple error, as we are calling it, and we want strict action behind the error. Moreover, in the other two lines of code, the output is a little bit different, as the description tells us.
The conversion of bytes does not end here; instead, it has other conversion techniques as well. Python gives programmers the ease of converting integers into bytes, but it is, somehow, a little bit easier than string conversion because it is a pre-defined function and you just have to insert the values accordingly.
int.from_bytes(bytes, byteorder, *, signed=False)
In the syntax given above, three things are to be noticed;
It is the byte object that has to be converted into an integer.
This function determines the order in which the integer value is represented. The value of byte order can be "little," which stores the most significant bit at the end and the least significant bit at the beginning, or "big," which stores the MSB at the beginning and the LSB at the end. Big byte ordering computes an integer's value in base 256.
By default, the value of this parameter is false, and it indicates whether you want to get the 2’s complement of the value or not.
To understand the bytes well, you have to know first that Python is an object-oriented programming language; therefore, it works by creating objects from different pieces of code. While working with the byte function, an immutable byte object is formed. The size of this immutable sequence is just as large as an integer that ranges from 0 to 254, and it prints the ASCII characters. It is a Python built-in function that has many interesting applications in a simple manner. As with the other types of sequences, tuples also contain a number of items, but they can also be empty. The only conditions are that the data should be enclosed in parentheses and the elements should be separated with commas. Another important piece of information about this data type is that it cannot be changed once you have declared it.
As the name of this data type resembles the previous one, both structure and information are also similar. Byte arrays also have the parentheses representation, and you can use different data types in them, but the only difference between the byte array and the simple byte in the sequence is that the former is immutable, and you can change the size of the byte array after you declare it in Python. It makes the byte arrays more useful than the simple bytes in the sequence.
The reason why we are discussing both of these data types here is, there is only a slight difference between the byte and the byte array. You can modify the byteArray and that is not possible in the byte. So, have a look at the code below where we are modifying the array declared by
ourselves.
MyArray=[99,5,1,34,89]
print('The byteArray is: ', MyArray)
#Modifying the ByteArray
MyArray[2]=56
print('The modified array is: ',MyArray)
But for this, you must keep in mind that you can only use values between 0 and 255. All the other conditions are the same as the bytes.
Hence, today we have seen a piece of great information about a special type of method that converts different types of data into bytes in a specific manner. We have seen the details of methods that must be known to a Python programmer. The whole discussion was put into TensorFlow in the form of codes, and we get the outputs as expected. The next lecture is also related to this, so stay with us for more information.
Hello everyone, I hope you all are doing great. Today, we are going to share the second chapter of Section-III in our Raspberry Pi programming course. The previous guide covered how to interface an LDR Sensor with Raspberry Pi 4. This tutorial will cover the basics of hooking up a soil humidity sensor to a Raspberry Pi 4 to get accurate readings. Next, we'll write a Python script to collect the data from the sensors and display it on a Serial monitor.
Are you aware that you can utilize a Raspberry Pi 4 to track the water absorbed by the soil around your houseplants or garden? This helpful guide will show you how to install a soil humidity sensor that will send you a text message when your plant needs watering. A Pi 4, a soil humidity sensor, and a few low-priced components are required. All right, let's get going!
Today, we are going to interface Soil Moisture with Raspberry Pi 4. We will design a simple irrigation system, where we will measure the moisture of the soil and depending on its value, will turn ON or OFF the water pump. We will also use a 20x4 LCD to display values/instructions.
One way to assess soil conditions is with a soil moisture sensor. The electromagnetic signal that the sensor emits travels through the soil. The sensor then evaluates the moisture level based on the signal's reception.
We can use soil moisture sensor has numerous purposes. Saving water is one of them. Adjustments to the watering system can be made based on readings from the sensor that measures the soil's moisture level. This could cut down on both water consumption and waste. Plant health can be enhanced by employing a soil moisture monitor, another perk. We can use this sensor to set off a relay to begin watering the plant if the soil moisture level drops off a given threshold.
The two exposed wires on the fork-shaped probe function as a variable resistor whose resistance changes with the soil's moisture level.
The above figure demonstrates how to use a soil moisture sensor to detect moisture levels. When water is poured into the soil, the voltage of the sensor immediately reduces from 5V to 0V. The module has a potentiometer(blue) that adjusts how sensitively the digital pin changes state from low to high when water is introduced into the soil.
There are typically two components that make up a soil moisture sensor.
Two exposed conductors on a fork-shaped probe are put wherever moisture levels need to be determined. As was previously mentioned, its a variable resistor whose resistance changes as a function of soil moisture.
The sensor also has an electronic module that is interfaced with the microcontroller. The module produces a voltage proportional to the probe's resistance and makes it available through an Analog Output pin. The same signal is then sent to a Digital Output pin on an LM393 High Accuracy Comparator.
The module features a potentiometer (DO) for the fine-tuning of digital output sensitivity. It can be used to establish a threshold i.e. at which threshold the module will output a LOW signal and a HIGH otherwise.
In addition to the IC, the module has two LEDs. When the component is activated, the Power LED will light up, and the Condition LED will light up if the moisture level is above the setpoint.
Four pins are included on the FC-28 soil moisture sensor.
Among the various uses of Moisture Sensors, I am sharing a few here:
As with most things involving the Raspberry Pi, connecting a soil humidity sensor is child's play. we need to connect the soil moisture sensor with Pi 4 GPIO header. This connection requires three wires.
We can now start coding our project because all the pieces are in place. Now is the time to begin.
Here's our hardware setup having soil Moisture Sensor with RPi4:
Here's the Pin's Mapping:
VCC -> 5V
GND -> GND
DATA-> GPIO4
After the sensor has been hooked up, testing it requires the creation of some code. The following code can be copied and pasted into a text editor, then saved as a .py file.
import RPi.GPIO as GPIO
import time
#GPIO SETUP
channel = 4
GPIO.setmode(GPIO.BCM)
GPIO.setup(channel, GPIO.IN)
def callback(channel):
if GPIO.input(channel):
print ("Water Detected!")
else:
print ("Water Detected!")
GPIO.add_event_detect(channel, GPIO.BOTH, bouncetime=300)
GPIO.add_event_callback(channel, callback)
while True:
time.sleep(0)
The below output should be observed if the sensor is operating correctly:
So, there's been a moisture detection! You can change the code to perform any action you like. Once the humidity level is detected, you could activate a motorized or audible alarm, for instance. In the next tutorial, we will Interface a Sharp IR Sensor with RPi4. Stay tuned. Have a good day.
Hello friends, I hope you all are doing great. Today, I am going to share the 6th lecture in the Raspberry Pi 4 Programming series. We're glad you could join us for another lesson in our comprehensive Raspberry Pi programming guide. In today's guide, I'll show you how to interface a 16x2 LCD screen with Raspberry Pi 4.
So, let's get started:
Today, we are going to interface a 16x2 LCD screen with Raspberry Pi 4. At first, we will print the "Hello World" text on the LCD, and in the last section, we will implement the scrolling and blinking of text on the LCD.
We will need the following components for today's project:
The header pins of 16x2 monitors are not pre-soldered. Normally a male header pin is soldered to the LCD pin holes.
We can perform 2 types of communication modes in LCDs, named:
In 8-Bit mode, all 8 data pins are used to send data, while in 4-Bit mode, the last 4 pins(D4-D7) are used for data transmission.
LCDs employ two distinct registers:
You can use the RS pin on LCD to alter the register. If RS is High, we are accessing the data register and if it's Low, we are accessing the command register.
The LCD's command register keeps track of the user's command. Pre-display data is saved in the data register. In order to manipulate the display, one must first load the instruction register with commands and then load the data registers to display the data. If you're working on a Raspberry Pi project and want to avoid learning low-level commands, you can use the Liquid Crystal Library instead.
The screen's brightness can be adjusted from Pin 3, normally a potentiometer is placed at Pin 3 to adjust the brightness. You can also use a resistor if you don't have a potentiometer. If a resistor is used, try one between 5k-10k ohms. You should experiment with a few different values to get the optimal resistance.
LCD works on the principle of light transmission from one layer to the next via molecules. These units vibrate and align themselves in a way that the polarized sheet gets at an angle of 90 degrees, allowing light to pass through. In other words, these molecules inspect the information on every pixel. Every single pixel uses the light absorption technique to display the digits. It is necessary to adjust the molecular orientation to the incident light angle in order to show the value.
The 16x2 LCD screen can easily be connected to the Raspberry Pi 4. There will be a lot of cables to connect because LCD has 16 pins, but nothing too complicated. Here's the schematic of the pin connections between RPi4 and LCD:
Having done so, the screen should power up and establish a connection with the RPi.
The newest Raspbian release has all the necessary packages loaded out of the box to allow for GPIO communication. But we need to install the Liquid Crystal Library to work on the LCD. Let's do that:
git clone https://github.com/pimylifeup/Adafruit_Python_CharLCD.git
cd ./Adafruit_Python_CharLCD
sudo python setup.py install
After the installation, you can use the Adafruit library from any Python program on the Pi. Just paste this line into the beginning of your Python file to make use of the library.
import Adafruit_CharLCD as LCD
The Adafruit LCD library makes it simple to display data from Raspberry Pi to LCD screen. The library package also has several working examples of utilizing the LCD. Before running any of these examples, make sure the pin parameters at the top of the program reflect your setup. My Circuit should yield the following results.
lcd_rs = 25
lcd_en = 24
lcd_d4 = 23
lcd_d5 = 17
lcd_d6 = 18
lcd_d7 = 22
lcd_backlight = 4
lcd_columns = 16
lcd_rows = 2
cd ~/Adafruit_Python_CharLCD/examples/
sudo nano char_lcd.py
Change the values in this section to match the ones described above for the pin configuration. To save the code, hit CTRL+X+Y on your keyboard. To execute this code, open a terminal and type Python followed by the name of the file (including the extension).
python char_lcd.py
In this session, I'll go over the fundamental Python methods for interacting with the screen. To initialize the pins, it is necessary to invoke the following class. Before calling the class, make sure all the parameters have been defined.
lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, lcd_columns, lcd_rows, lcd_backlight)
After that, you can adjust the screen to your liking. In this short guide, I'll give you a taste of what you can do with the Adafruit library.
The Ardafruit CharLCD.py file in the Adafruit CharLCD folder of the Adafruit Python CharLCD folder will list all the accessible methods.
sudo nano ~/Adafruit_Python_CharLCD/Adafruit_CharLCD/Ardafruit_CharLCD.py
My simple script for displaying user-entered text is included below.
#!/usr/bin/python
# Example using a character LCD connected to a Raspberry Pi
import time
import Adafruit_CharLCD as LCD
# Raspberry Pi pin setup
lcd_rs = 25
lcd_en = 24
lcd_d4 = 23
lcd_d5 = 17
lcd_d6 = 18
lcd_d7 = 22
lcd_backlight = 2
# Define LCD column and row size for 16x2 LCD.
lcd_columns = 16
lcd_rows = 2
lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, lcd_columns, lcd_rows, lcd_backlight)
lcd.message('Hello\nworld!')
# Wait 5 seconds
time.sleep(5.0)
LCD.clear()
text = raw_input("Type your name in the terminal ")
LCD.message(text)
# Wait 5 seconds
time.sleep(5.0)
LCD.clear()
lcd.message('Goodbye\nWorld!')
time.sleep(5.0)
LCD.clear()
If everything's fine, you will get something printed on your screen, as shown in the below figure:
If your Python script isn't producing any output on the screen, it's probably due to incorrectly configured pins.
This guide walked you through connecting the Pi 4 to a 16x2 LCD. You can accomplish so much more with this sleek screen. You may set up a script to run at boot time and show useful information like the IP address, time, temperature, and more.
You can also incorporate a wide variety of interesting sensors with this screen. A temperature sensor like the DS18B20 would be ideally suited for use with the screen. Refresh the screen every few seconds to reflect the current temperature.
Please let me know how successful you were in putting up a Pi 4 with LCD 16x2 display with the help of this tutorial. In the next tutorial, we will interface Keypad 4x4 with Raspberry Pi 4. Till then, take care. Have fun !!!
We're glad you could join us for another lesson in our comprehensive Raspberry Pi programming guide. I will show you how to install and connect the RFID card chip to your Raspberry Pi through step-by-step instructions.
Modern security systems would only be complete using radio frequency (RFID) devices. To control who can enter a facility or which rooms they can access, RFID chips and card readers are employed. The RFID card's unique identification number can be read wirelessly with a wall-mounted RFID reader. A door will only unlock and allow entry if the RFID card's unique identification number matches a list of approved cards.
It's fun to tinker with this circuit, and it may be used in many other applications, from opening locks to taking attendance. The MFRC522 microcontroller underpins the RFID RC522, a cheap RFID (Radio-frequency identification) reader/writer. The RFID tags can connect with this microcontroller using an electromagnetic field it generates at 13.56MHz and sends to them via the SPI protocol. If you want to use your RFID RC522 with tags, you must ensure that they are 13.56MHz compatible. We'll walk you through the wiring of the RC522 and the creation of Python programs to communicate with the chip, allowing you to read and write RFID tags. Adding a 16x2 LCD to the Raspberry Pi is a simple extension of this tutorial, and it can be helpful if you need to show the user some information or provide a visual prompt.
Where To Buy? | ||||
---|---|---|---|---|
No. | Components | Distributor | Link To Buy | |
1 | Breadboard | Amazon | Buy Now | |
2 | Jumper Wires | Amazon | Buy Now | |
3 | Raspberry Pi 4 | Amazon | Buy Now |
Raspberry Pi
Micro SD Card
Power Supply
RC522 RFID Reader
Breadboard
Breadboard Wire
An RFID reader reads the tag's data when a Rfid card is attached to a specific object. An RFID tag communicates with a reader via radio waves.
In theory, RFID is comparable to bar codes because it uses radio frequency identification. While a reader's line of sight to the RFID tag is preferable, it is not required to be directly scanned by the reader. You can only read an RFID tag up to three feet away from the reader. The RFID tech quickly scans many objects, making it possible to identify a specific product rapidly and effortlessly, even if it is sandwiched between several other things.
Major components of Cards and tags include an integrated circuit (IC) that stores the unique identification value and a copper that acts as the antenna.
Inside the Rfid reader is another copper wire coil. This coil produces a magnetic field when current flows through it. Magnetic flux creates a current inside the wire coil when the card is brought close to the reader. This current can power the card's internal integrated circuit. The reader then takes in the card's serial number. A card reader will send the card's serial number to a central processing unit (CPU) like a Raspberry Pi for further processing.
When you buy an RFID RC522 Reader, you may discover that 90% of them do not have the header pins pre-installed. Due to a lack of pins, you'll have to solder them yourself; however, this is a relatively easy task, even for amateurs. Assuming the header pins that came with your RC522 are too large, you may snap them in half to reduce them to a single column of eight.
Start by inserting the header pins into the RC522 from the top. The circuit may be easily placed on top of the connector pins by inserting the large side of the pins onto a breadboard. The breadboard's secure holding of the pins will make soldering them to the RFID circuit much simpler.
Solder each pin individually by carefully heating your soldering iron and applying it to the pins. Remember that heating the junction slightly before to solder application increases the solder's adhesion and decreases the likelihood of generating a cold joint. When using solder, we advise you to be conservative. When you've finished soldering the header pins onto your RFID circuit, you'll be ready to move on with the guide.
There are eight different connectors on the RFID RC522. Except for the IRQ, we need to connect all these to the GPIO pins on our Raspberry Pi.
This guide shows how to connect an RFID RC522 to a Breadboard and then to the Raspberry Pi's GPIO Pins, although you could also wire the components straight to the Pi.
Simply connecting 7 of the Raspberry Pi's GPIO pins to the RFID RC522 reader is all needed to get it up and to run. Refer to the GPIO pin locations detailed in our tutorial and the table below when deciding how to wire your RC522.
SDA connects to Pin 24.
SCK connects to Pin 23.
MOSI connects to Pin 19.
MISO connects to Pin 21.
GND connects to Pin 6.
RST connects to Pin 22.
3.3v connects to Pin 1.
We need to adjust the Raspberry Pi's settings before we can use the RFID RC522. Inconveniently, our RFID reader circuit relies on the Raspberry Pi's SPI (Serial Peripheral Interface), which is disabled by default. Worry not, though, as it is easy to restore this interface; follow our instructions below to set up your RPi and Raspbian to use the SPI port. Launch the raspi-config utility by opening a terminal and typing the following command.
sudo raspi-config
A menu of choices will appear when you use this tool. You may read up on all of these options in the raspi-config documentation. Choose "5 Interfacing Options" using the arrow keys. Select this choice, and then hit the Enter key. Once "P4 SPI" is selected in the next screen, press Enter once more to confirm your selection. To continue, use the arrow keys to choose "Yes" and then press Enter when prompted to confirm that you want to activate the SPI Interface. For the raspi-config utility to finish enabling SPI, you'll have to be patient for a while.
The raspi-config tool's success in enabling the SPI interface will be shown by the display of the message "The SPI interface is enabled." Activating the SPI Interface requires a full reboot of the Raspberry Pi. Press Enter, and then ESC, to return to the terminal. If you want to restart the RPi, enter the following Unix instruction into the terminal.
sudo reboot
It is time to verify that Raspberry Pi has been activated now that it has rebooted. Checking if spi bcm2835 is available is as simple as running the following command.
lsmod | grep spi
If you get spi bcm2835, you're good to go with the rest of the tutorial. If you tried the preceding command and it didn't work, try the following three things. If the SPI component is not enabled, we can manually modify the boot config file by issuing the following code to our RPi.
sudo nano /boot/config.txt
You can use CTRL + W to search the configuration file for "dtparam=spi=on" If you think you have discovered it, look if it has a number in front of it. If there is, delete it because it disables the code. If you cannot find the line, add "dtparam=spi=on" to the very end of the file. To commit your modifications, use CTRL + X, followed by Y and Enter. You can double-check that the module has been activated by restarting your Raspberry Pi, as in Step 5.
After connecting our RFID circuit to the RPi, we can turn it on and start writing Python scripts to communicate with the chip. You'll learn how to read and write information to RFID chips by composing scripts like the ones we'll provide. These will serve as the foundation for future RFID RC522 tutorials and provide you with a fundamental understanding of how data is handled. The Raspberry Pi must be brought up to date with the most recent software versions before we can begin programming. Get the latest version of Raspbian for your Pi by running these two commands.
sudo apt update
sudo apt upgrade
Installing the python3-dev, python-pip, and git packages is the last thing to do before moving forward. To get your RFID reader set up with this guide, type the following command into your Raspberry Pi's terminal.
sudo apt install python3-dev python3-pip
Now that we have python "pip" installed on our Raspberry Pi, we can install the spidev Python library. An integral part of this guide, the spidev library allows the RPi to communicate with the RFID via the SPI. Run the following command to get spidev set up on your Raspberry Pi via pip. It's important to remember that we're using sudo to guarantee that the package gets installed for everyone's usage, not just the logged-in user.
sudo pip3 install spidev
After getting the spidev library up and running on our Raspberry Pi, we'll move on to setting up the MFRC522 library with pip. Two files, in particular, are used by us, both of which are part of the MFRC522 library:
This library, MFRC522.py, implements the RC522 interface for communicating with RFIDs via Raspberry Pi's SPI port.
Simplifying the MFRC522.py file so that you only need to work with a small subset of its many functions, SimpleMFRC522.py is a significant time saver.
Enter this command into your terminal to have pip setup the MFRC522 library on your Pi 4:
sudo pip3 install mfrc522
Now that the library has been transferred to the Pi, we can start writing code for the RFID RC522. First, we'll explore how to use the RC522 to program your RFID cards. Move on to the following part, where we will write our first Python code.
In this first Python script, we'll go over the steps needed to send information from the RC522 to RFID tags. This is made more accessible by the SimpleMFRC522 script, but we'll still break down the code's individual components for you. To begin, let's create a directory to hold the scripts we'll be using. Create the "pi-RFID" folder by using the following command.
mkdir ~/pi-rfid
To get started, navigate to the folder you just cloned and create the Write.py script in Python.
cd ~/pi-RFID
sudo nano Write.py
Add the following blocks of code to this file. This code prompts you for some text, which it then uses to update the RFID Tag.
#!/usr/bin/env python
import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522
The very first line of the code snippet instructs the terminal to use Python rather than another scripting language like Bash to parse and run the file. To guarantee that the GPIO Pins are reset when the script terminates, we must first import the RPi.GPIO package contains all the necessary functions for communicating with the GPIO Pins. The second import is our SimpleMFRC522 library, which will be used to communicate with the RFID RC522. Compared to the standard MFRC522 library, it dramatically simplifies working with the chip.
reader = SimpleMFRC522()
In this line, we make a new instance of the SimpleMFRC522 object, use its setup function, and save the result in our readers variable.
try:
text = input('New data:')
print("Now place your tag to write")
reader.write(text)
print("Written")
We enclose the following section of code with a try statement to ensure that any unforeseen problems are handled, and the code is cleaned up correctly. Python is whitespace sensitive; it uses tabs to distinguish between code sections, so keep them after trying. In this case, the second line reads a command-line input and stores it in a text variable using Python 3's input function.
The third line makes advantage of print() to prompt the user to set the RFID tag onto the reader. After that, on line 4, we utilize our scanner object to instruct the RFID Circuit to write the text field's contents to a certain sector of the RFID tag. On line 5, after successfully writing to the RFID tag, we call print() once more to inform the user.
finally:
GPIO.cleanup()
The script will terminate in the last two lines of code. The finally statement always follows the try statement. Thus the GPIO.cleanup() method is called after each iteration of the try block. These lines are essential because improper cleanup can disrupt the functionality of other programs. Upon completion, your script should be like the example given below.
The file can be saved by pressing CTRL Plus X, Y, then ENTER once you've double-checked the code and are convinced it's correct. Now that the script is written, we need to put it through some testing. Get an RFID tag ready before running the script for testing. When you're ready, open the terminal on your Raspberry Pi and enter the following command.
sudo python3 Write.py
In this situation, we're just going to type in "any word" because it's easy to remember and short. Press the Enter key when you have finished writing and are ready to send. After that, your RFID Tag can be placed directly above your RFID circuit. It will immediately update the tag with fresh information when it does. You'd see the word "Written" on the command prompt if it worked. Now that you have your Write.py script completed, we can move on to explaining how to read information from the RFID RC522.
We have successfully programmed our RC522 to print to RFID tags and can now move on to writing a script to retrieve the data from the tags. First, we'll make sure we're in the correct location by switching directories, and then we'll use nano to start drafting the Read.py script.
cd ~/pi-rfid
sudo nano Read.py
Incorporate the following code into this document. When an RFID tag is placed in the RFID reader, the script will wait until the tag's data has been read before displaying the results.
This file's first line of code instructs the operating system on how to proceed when the user clicks the "Run" button. If you don't specify that it's a Python file, it'll try to run it like any other script. An initial RPi.GPIO import is made. Importing this library ensures that the Raspberry Pi's GPIO pins are cleaned up after script termination, as it contains all the necessary functions. SimpleMFRC522 is the second import. With the assistance functions included in this script, reading and writing to an RFID RC522 is a breeze, whereas, with them, the scripts would quickly grow to be manageable.
This line is crucial because it invokes SimpleMFRC522's creation method, which returns an object that is subsequently stored in our reader variable.
try:
id, text = reader.read()
print(id)
print(text)
The following code section will be encapsulated in a try block to allow us to handle any unforeseen errors gracefully. Because Python is sensitive to whitespace, you must use the 'tabs' as displayed following try:
In this scenario, the second line of this code block initiates a call on our scanner object, instructing the circuits to begin scanning any Rfid card that is positioned on top of the reader. On the third and forth lines, we use print() to display the data we gleaned from the RFID Chip; this includes the tag's unique identifier and any text it may consist of.
finally:
GPIO.cleanup()
The script ends with the last two lines of code. No of what happens inside the try block, the final statement is always executed afterward. No matter what, the GPIO.cleanup() code will be executed thanks to this try statement. It's vitally important, as not doing so can disrupt the proper operation of other scripts that rely on the GPIO. Your completed Read.py script for the RFID RC522 should resemble the example below.
When you've double-checked your code and are satisfied with it, press Ctrl + X, then Y, and finally ENTER to save the file. The time has come to put our completed Read.py script to the test. Get ready to test the script by picking up any of the RFID tags. If you're all set, enter this command into the terminal on your Raspberry Pi.
sudo python3 Read.py
Now that the script is active, you can set your RFID Tag atop your RFID circuit. When the RFID tag is placed on top, the Python program will immediately begin reading the information from the tag and display the results on the screen. What a finished product might look like is shown below as an illustration.
To test whether your Raspberry Pi is properly connected on the RFID RC522 Circuit, run the Read.py script and see if it returns any data that matches the text you wrote to the card in the Write.py script.
Connecting an RC522 RFID module to a Pi 4 makes reading MIFARE chips and cards is now possible. This might be very useful in security systems and other applications where identifying an item or person is required without the user having to physically interact with the device by pressing buttons, switching, or activating any sensors. Eventually, you should be able to use this to decipher the UID encoded on your MIFARE tags. You should know that these cards can be duplicated and assigned a new unique identifier (UID) if you plan on employing this technique in a security system. To ensure the safety of your system, you must ensure that no one learns your UID or gains remote access to your devices. The contactless tags are convenient because they can be attached to a keychain, and the cards are convenient because they can be carried in a wallet. Both things can be concealed inside others to give them a hidden identifier that the Pi can access. With the help of our Pi 4-powered RFID attendance systems guide, you can learn how to set up your RFID Reader/Writer for use in checking attendance. Our exploration of the RFID chip and the scripts above will continue in subsequent guides. A door security system is one of the fantastic DIY Pi ideas we'll look into. The next lesson will teach you how to connect a 16x2 LCD screen to a Raspberry Pi 4.
No matter your company's industry, you need fleet maintenance software. It’s something you need if your engineering firm has a fleet of vehicles. Failing to get the necessary tools is a bit like driving blind -- not the best course of action by any stretch of the imagination.
If you’re not sold on the benefits of investing in fleet maintenance software, keep reading to learn more about four reasons you need it.
Fleet maintenance software will help your engineering firm with preventative maintenance. The software will make it easy to schedule maintenance so that your fleet of cars stays in good shape.
One of the worst things you can do is delay or ignore preventative maintenance. That will ultimately cost you in terms of downtime stemming from repairs. Preventative maintenance won’t eliminate the possibility of repairs, but it will reduce the odds of breakdowns . And breakdowns can become expensive if you also find yourself unable to use the company vehicles for business. Unplanned downtime is a no-no.
When your business invests in fleet maintenance software, you’ll also enjoy lower vehicle repair costs. Putting off maintenance means that small problems can morph into major issues that cost an arm and a leg to fix. So, it’s more cost-effective to invest in preventive maintenance than to postpone doing so and having to spend many times more to fund major repairs.
When considering the importance of your fleet, you can appreciate the need to ensure the vehicles are available and in good repair whenever they’re needed. You can increase uptime and reduce downtime by tackling issues as soon as they’re discovered so that they don’t worsen.
When you get one of the best fleet maintenance software applications, you’ll also benefit from better fuel efficiency. Proper maintenance and repairs will ensure your fleet of vehicles operates more efficiently, resulting in better fuel efficiency. You can also optimize routes so that drivers don’t take longer routes than necessary. And by keeping track of driver behavior, like speeding or hard braking, you can notify drivers of necessary changes. You can save a lot on fuel just by getting drivers to operate the fleet vehicles more responsibly.
Who has time to worry about their fleet of vehicles? You have other things to worry about such as operating your engineering firm. When you’re taking good care of your cars, you won’t be left worrying about them. Instead of having to make frequent arrangements to have your inoperational cars towed to automotive facilities for repairs, you’ll be able to use them for business purposes. They’ll spend more time on the road and less time out of commission.
That means you’ll have fewer headaches with your fleet of vehicles. Using a fleet maintenance software solution, you’ll be able to stay on top of things. And if things don’t get out of control, you’re less likely to have headaches over something going horribly wrong.
If your engineering firm has a fleet of vehicles, it’s essential to consider the benefits of fleet maintenance software. Protecting your assets is a must if you want them to remain in good repair over the long haul. Getting a fleet of vehicles requires a tangible investment. If you want to protect your investment, then investing in fleet maintenance software is a good idea.
Before settling on a platform, you’ll want to do research to find something that meets your company’s needs. When you find the right software, you’ll see up close and personal what the benefits of fleet maintenance software are all about.
Hey peeps! Welcome to another tutorial on data types in Python. Our purpose in Python education is to get a grip on the basic concepts so that we may work on deep learning easily. In the previous lecture, we read a lot about lists as we are working on the subtypes of the sequence data type. In the present lecture, you are going to understand more types of sequences. If you know the list well, this lecture will be a piece of cake for you. We will start the introductions in just a bit, but before that, there must be a quick review of the topics that you are going to understand:
How do you introduce the tuples in Python?
What are some important characteristics of a tuple that must be kept in mind when we are dealing with it?
How can you practically perform the tuples in TensorFlow?
How do you associate tuples with the list?
Can you delete, update, add, or delete the elements in a tuple? If yes, then how?
Which is the way to delete the tuple entirely?
All of these are important interview questions about the tuple and if you are dealing with these data types, you must know and perform these by yourself in TensorFlow. All the information about tuples will be discussed with you and you have to practice more and more in the code to understand the concepts.
For the concept of a list, we have given you the reference of an array. This time, we will be mentioning the name of the list for better understanding. If we talk about the topic of today, a tuple is also a group of items that are arranged when required in Python. The working and the definition of the tuple seem like a list because both of them are types of a single data type, which is the sequence. But there are some differences that make them ideal for different kinds of situations. The following points will make this more clear:
The tuple is represented by enclosing the data in parentheses.
A tuple is immutable, which means that once you declare the items in the tuple, you can not change them as you can in a list.
When you try to change the value of the element in the tuple, an error is shown on the screen, so while declaring the new tuple, you have to be very clear about what is on your mind and what you want to do with the tuple.
In a tuple, you can also use the function in the tuple and it becomes easy to perform different tasks through codes.
A single element in the tuple is necessary to build the tuple. In other words, unlike the strings, the tuple must contain at least one element in it.
In the tuple, any data type can be saved whether it is boolean, int, or string. Moreover, there is a possibility to add different types of data in a single tuple. So we can conclude that we can have a homogeneous or heterogeneous tuple according to our choice.
As we have mentioned, when using the tuple, we get the ordered list of objects, which means we get the specific order, and this order, once mentioned, can not be changed, unlike other data types of the sequence.
Not just the order, but the size, sequence, and entries are unchangeable, so during the initialization and declaration of the tuple, the concept must be clear about what you want from the particular tuple.
Another thing that must be kept in mind is, the tuple has the index form, and therefore, every element has a specific number of indexes. This is the reason, the elements are easily accessible, and hence, you can also have duplication in the tuple. The elements are recognized by the index number, and therefore, the compiler knows when which element is being called.
The length is the number of elements in the tuple, and we have read about the length function in the previous lecture. Similar to the list, a tuple can also be used in the length function, and the programmer gets the length of the tuple. Right now, this function is not looking very attractive because we are dealing with small tuples. But take the case in your mind when the tuple contains hundreds or thousands of elements and get the length of the tuple in just a few moments.
It is now time to go over some basic tuple-related code using TensorFlow. The steps for starting it are the same as those we always follow; have a look at these steps:
Open your Anaconda Navigator by browsing it from your window panel.
Search for the Jupyter lab in the environment section.
Wait for the PC to open the new tab in your browser.
Go to the new cell.
Start coding.
With the help of code, we will try to create a tuple, and then, by using the function on it we will try to retrieve the data from the tuple in different ways. So, have a look at the code given next and then guess the output in your mind.
print('Make a tuple with stationaries item')
myTuple=('pen', 'paper', 'eraser', 'pencil', 'sharpener', 'notebooks')
print('The tuple has following items: ',myTuple)
print()
print('print only the third item of the tuple:', myTuple[3])
print()
print('print the item by using the index: ',myTuple[1])
Now, have a look at the output. Is it exactly the same as you were expecting?
You can see how simple it is to get the item from the tuple when it is declared in the tuple. This is the same as what we did with the list. But what if we want more than one element from the tuple at the same time?
print('Make a tuple with fruits and prices in dollars')
myTuple=('strawberry','kiwi','banana','orange','apple', 2.5,3,12, 4,6)
print('The following items in the fruit shop are available: ',myTuple)
print()
print('print only the forth fruit of the fruit shop:', myTuple[-7])
print()
print('print the name of only fruits: ',myTuple[0:5])
Looking at the code, you will observe that the negative number is used in the index. This is the way to tell the compiler that we are counting from the end of the index. Moreover, the index on the end side starts at 1 instead of zero. Another point to notice is that the start and end limits are specified by separating them with the colon, and as a result, we get the whole tuple in the output.
A new concept that is to be shared is that when you are providing the limits to the tuple, you have to take care that the right numbers are being used because it will then not work properly. You must be thinking that the compiler will throw the error when you feed the wrong limits in the tuple, but instead, the output will be empty, and you will get the parentheses with nothing in them.
Another thing that must be mentioned here is that you can check whether the tuple has a specific element or not. For this, we get the help of a statement. We know that, until now, we have not learned about the statements, and therefore, we suggest just looking at the code and output to understand the concept.
print('Make a tuple with fruits and prices in dollars')
myTuple=('strawberry','kiwi','banana','orange','apple', 2.5,3,12, 4,6)
print('The following items in the fruit shop are available: ',myTuple)
if "apple" in myTuple:
print("Yes, 'apple' is in the present in the fruit shop")
This program searches for the elements specified in the “if condition” and then prints the result on the screen.
If you are reading this lecture from the beginning, you must be thinking we have mentioned again and again that a tuple is immutable and unchangeable. Yet, programmers have the logic and solutions to every problem, and if the programmers have specified the tuple and want some changes made to it, they can do so with the help of the list. It is one of the reasons why we have discussed the list before in this series. Have a look at the following code and output, and then we will discuss it in detail.
print('Make a tuple with fruits and prices in dollars')
myTuple=('strawberry','kiwi','banana','orange','apple', 2.5,3,12, 4,6)
print('The following items in the fruit shop are available: ',myTuple)
myList=list(myTuple)
print(myList)
myList[2]='pear'
print(myList)
myTuple=tuple(myList)
print(myTuple)
Copy this code and run it on your TensorFlow, you will get the following output:
First, look at the brackets carefully and check the output in a sequence with the points given next:
At the start, the string message is shown, which shows the main title of the tuple.
The name of the tuple here is “myTuple” and it contains the fruits’ names and prices.
To make the changes in the tuple, we have to use another approach, and we know the reason why. For this, we are using the list. It is possible to convert the list into a tuple and vice versa, and we are doing the same in this. We are just using the name of the data type as a function and inputting the name of the data type to be changed. So, we changed the tuple into a list and then made the changes according to our choice.
By using the index number and feeding the value into the list, the list is updated. This can be observed with the help of square brackets.
Once we have seen the updated list, we can now easily convert it into a tuple again.
The conversion is done with the same procedure, and we get the updated tuple.
This was a simple example, other operations such as the addition of the new element, deleting the elements from the tuple, removing the single elements from the tuple, etc. are done with the help of lists.
Now that you know all the ways to initiate, use, and update the tuple in detail, a last method for the tuple is ready for you. In some cases, when you do not want to use a particular tuple for any reason, such as if you are no longer using it, you can do so in just a simple step. This is used in the programs when long calculations and collections of data types are needed for a particular time and then there is no need for them anymore. So for this, we use the delete operation. The programmers have to simply use the del keyword before the name of the tuple to be, and the compiler has to do its job well. Have a look at the example given next:
Tuple = ("Artificial Intelligence", "Machine Learning", "Deep Learning")
print(Tuple)
del(Tuple)
print(Tuple)
So, when the compiler was on the second line, it showed us the results, but on the next line, when we deleted the declared tuple, the compiler was not able to show us the result because it had been removed from its memory.
So, it was an informative data types lecture in which we clarified many concepts about tuples. These are the data types that belong to the class of sequences. We read a lot about it and started the discussion with the introduction. The tuple characteristics were thoroughly discussed, and then, with these in mind, we tested the functions of the tuple using TensorFlow examples. We attempted similar examples and carefully observed the operation of tuples, which also involved the list. In the next lecture, you will know more about the data types in Python, so stay connected with us.
Hello my friends! I hope your doing very good. Today we are going to practice what we have learnt through the ladder logic tutorial series. We bring a new .project which is mostly exist in our daily life that is electrical door control. in garage for domestic and public garage, you should found automatic garage gate or door that is controlled by the PLC ladder logic program. So today we are going to implement the project including determining the input and output components, design the logic, programming and testing using the simulator.
Figure 1 shows the project’s components, inputs and outputs that are included in controlling the garage door. As you can see my friends, there are inputs like open, close, and stop requested by push buttons. Also, you can see sensors like the two limit switches on the bottom and on the top to prevent overload that might have occurred on the motors. Moving to the outputs, there are motor up and down directions, open, close, and ajar status indicators lamps. So what is the next step in our plan to achieve such job? Of course we need to list these inputs and outputs and give them addresses. Then we design the logic based on the user requirements and the safe operation.
Table 1 lists the inputs and outputs showing the name in the first column, the description In the second column, while the addresses are listed in the last column.
Component |
Description |
Address00 |
Open push button |
One of the inputs to request open operation |
I: 1 / 00 |
Close push button |
One of the inputs that enables user to shut down the door |
I: 1 / 01 |
Stop push button |
The push button to stop operation at any time |
I: 1 / 02 |
Limit switch 1 |
A sensor to stop opening operation beyond the opening limits |
I : 1 / 03 |
Limit switch 2 |
A sensor to stop closing operation beyond the closing limits |
I : 1 / 04 |
Shut down indicator |
One of the outputs that tells the shutdown operation is in progress using an Indicator lamp |
O: 2 / 04 |
Open door indicator |
One of the outputs that tells the opening door operation is in progress using an Indicator lamp |
O: 2 / 03 |
Ajar door status |
One of the outputs that tells the door is ajar using an Indicator lamp |
O: 2 / 02 |
Motor Up |
A relay that directs the door in opening direction |
O: 2 / 00 |
Motor Down |
A relay that directs the door in closing direction |
O: 2 / 01 |
After receiving the requirements of the client that tell how the door will be operated, managed, and controlled, we need to add the restrictions and safety conditions that secure the equipment like the motor, supply, sensing components. So the following lines state the operation and restrictions that need to be followed to achieve the designated task as follows:
The door opening and or closing shall be stopped at any time user / operator hit stop push button
The door shall open by requesting opening operation using the designated push button
The door shall close by requesting shut down operation using the designated push button
The indicator lamp of opening operation shall be lit while opening operation is in progress
The indicator lamp of closing operation shall be lit while shut down operation is in progress
The ajar status lamp shall be lit at any time the door is not fully opened or totally closed
The opening operation can not be requested while shut down process is in progress
The shut down operation can not be requested while opening operation is in progress
The opening operation can not proceed any further beyond the designated limit to avoid any overload on the motor
The shut down operation can not proceed any further beyond the designated limit to avoid any overload on the motor.
The ladder logic program of the project is shown by figure 2. It shows two rungs, one for opening process and second for the shut down operation. The program can be more lengthy but we professionally resumed it in only two main rungs. The first rung represents the door opening operation in which, open push button initiates the opening process and the latching is there to let the opening process continue till the limit switch LS1 contacted or the stop is requested by hitting the stop push button. In addition, security of the process has been considered by including the condition of not having a shutdown process in progress represented by O:2/1. On the other hand, the shut down process is represented by the second rung. The shut down process initiated by the shut down push button and latching the door closing relay for continuing the shut down process unless one of the restriction conditions is met. The restriction conditions of shut down are the limit switch LS2, the door opening in progress, or a stop has been requested by operator using the stop push button. Also, indicator of the process status are included to show the opening operation thanks to the door opening indicator and the shutdown indicator. But we missed the ajar status of the door so let us add one rung for that.
As you see guys, the third rung has been added to implement the ajar status. It is simply clear that when the opening is in progress without reaching to the fully open indicator, or the shut down process is in progress without reaching to the totally closed, the ajar lamp is energized. Now let us go testing what we have coded so far and see if it is correct or not. But first you guys should sit and list the test cases that you should try to make sure the system is going to perform correctly and safely as well.
In this test , we hit the opening door push button to request opening the door. As you see my friends, the door is opening as in figure 3 and the opening indicator is lit. also you can see the ajar indicator is lighted because the door is not reached the final opening position.
Figure 5 shows the state of the process after reaching the final position for opening the door. It is clear the process safely completed and the limit switch LS1 is gone green. Also the ajar status and opening indicators have been turned off.
In this test , we hit the door shut down push button to request closing the door. As you see my friends, the door is closing as in figure 6 and the closing indicator is lit. also you can see the ajar indicator is lighted because the door has not reached the final shut down position.
Figure 7 shows the state of the process after reaching to the final position for closing the door. It is clear the process safely completed and the limit switch LS2 is gone red. Also the ajar status and shut down indicators have been turned off.
In this test case we want to request opening .the door while it is shuting down and try to request shut down the door while it is opening to see is there any issue or not. Figure 8 shows what is going on when we requested opening the door while a shuting down process is inprogress. You can see guys in rung number one, the opening push button ,is pressed as circled and highlighted see I:1/0. However, the requested process has not performed due to the restriction that the shutdown process should not be in progress. Same thing when opening door is in progress, shut down requests are forbidden.