Dual Compressor Operations using PLC Ladder Logic Programming

Hello, my friends, again we are back and enjoying one of the new tutorials in our ladder logic programming series. The tutorial we are here to present comes with a new project: dual compressors management using PLC. In that very project, you are going to learn how to divide the process between two actuators aiming to prolong the lifetime of the equipment and fulfill the processing requirements. as we used to do every tutorial, will go through the project. Understand the requirements, and design for the solution. And then code the ladder logic program of the solution and for sure enjoying simulating the code to validate the functionality of the proposed code. So without any more delay, let’s get started on our project.

What’s dual compressors project

The picture of the project shown in figure 1, can tell everything about the project including the sensors and actuators. The project utilizes two compressors to fill the tank with gas. Sometimes one compressor is enough, and some time needs to have both compressors work together to compensate for the heavy-duty demand. So now, which compressor will be in charge based on the demand and for prolonging the equipment’s lifetime? These kinds of problems are our mission to figure out a workable ladder logic program to handle the whole process. The image shows all details you need guys to complete the project. Inputs and outputs, switches, push buttons, indicating lamps to tell process status, screens and BCD Displays.

Project inputs and outputs address and description

Table 1 shows the inputs and outputs of the process, telling the addresses and the description of each component. The first column list the inputs or the outputs of the process, column 2 lists the dedicated address of the Ios, and the description of these Ios is told by the 3rd column. 

Item 

Address

Description

Run

O:02/02

Lamp indicator to show the process is running

C1

O:02/03

The lamp indicator shows compressor C1 is ON

C2

O:02/04

The lamp indicator shows that compressor C2 is running 

A, B, C

I:1/4 I:01/05 I:01/06

3 position selector switch to select which amount to display

start

I:01/01

Start the push button to commence the process

Stop 

I:01/00

Stop pushing a button to halt the process momentarily

BCD display

O:4

A BCD to 7-segment display

PE1

I:01/02

Pressure switch 1

PE2

I:01/03

Pressure switch 2 

M1

O:2/00

The compressor motor number 1

M2

O:2/01

The compressor motor number 2

The PSI

N/A

Display the current pressure in PSI

Flow %

N/A

Setting the flow percentage by regulating the valve 

The project coding

As I want you to learn how to apply the divide and conquer technique of programming, I’d like us to divide the project into parts, small, simple tasks. By combining them all, we get the whole process done. So now let’s start by running a single compressor and stop it based on user requests having the process status shown by indicators and displays that we have and listed in table 1 above.  Figure 2 shows the code for running in single actuator mode. So one compressor will take charge and start by hitting the start push button while it is stopped either by hitting the stop push button or by reaching the high-level pressure indicated by sensor I:1/2. Also, you notice my friends, the lamp indicators for showing the process status, like Run status and which compressor is in charge now.

Switching between the two compressors 

Realizing the dual operation concept in which we should use both compressors equally one for each cycle, figure 3 shows the ladder logic code to do so. You can see the project is getting bigger by adding more tasks. but let’s go through the line we have written so far, as shown in the figure below. Firstly we have latched the run status by hitting the start push button in the first runge. And the coil of the first compressor activates the indicator lamp of the first compressor as in the 2nd range. Similarly, the second compressor relay coil energizes its indicating lamp. In the fourth and fifth rungs, the formula is based on which the program can decide which compressor to run. Each compressor depends on its pressure switch. Compressor 1 works as long as the pressure measured by PE1 is within its limit, and compressor 2 works as long as the pressure measured by PE2 is within its limit to run. However, you notice, guys, there is one bit which is B3:0/0, which we have used to decide which compressor to choose to run each cycle. That is why it is XIC for one and XIO for the other compressor guy. But wait, how will we know the cycle ends, and a new cycle is to begin? Well! It’s the sixth runge that reads the one shot of the I:1/2 to change the status of B3:0/1 each cycle and, in turn, change the compressor. And notice, guys, the most intelligent runge, the last rung that flips the flag B3:0/0, which is responsible for flipping the operation from one compressor to the other. Now, the time to test all that we have done of coding comes to see if it is correct or needs to amend for correction. So let’s go test our ladder logic code.

Testing the dual compressor operation

Figure 4 shows the first case when we hit the start push button, compressor C1 started working. And it keeps working as long as the pressure PE1 reads is less than 40 PSI, as you can see in the figure below. Compressor C1 is running and sufficient to fulfill the process requirements. Also, my friends, see the control panel showing the status of the running compressor is ON, highlighted in yellow, while the other compressor guy is off as indicators tell.

In another case, figure 5 shows when both compressors are off because the operator hit to stop the push button to halt the process. See the indicators of both compressors are off, and the run process is ON, waiting to hit start to resume the process.

Now, time to start a new cycle, remembering the last time compressor C1 was working. Notice, guys, our code’s success in switching to the other compressor, C2. The flip flag in the last range turns on to flip the compressors from one to the other smartly. Also, the indicator panel shows the compressor C2 lamp is highlighted while the other guy’s light is turned off.

One last thing to consider, my friends, is when we run at a heavy demand of using the tank. One compressor won’t be enough to fulfill the heavy-duty process in this condition. Therefore, we need to have one case to run compressor C1, the other to switch to compressor C2, and the third case at heavy-duty we need to run both compressors C1 and C2 together to fulfill the heavy demand. Notice my friends in rungs 003 and 004, the change we have made is just adding a parallel branch to override the flag switch to give a chance for both compressors to work regardless of the flag when heavy duty is on that detected by PE2 pressure switch when it lowers than 95 PSI.

Testing the heavy-duty case

Figure 8 shows the case of running under high demand and reaching toe heavy-duty operating conditions. See how successfully our ladder logic program can run both compressors to fulfill such heavy-duty conditions. Also, please notice that the indicator lamp of compressors C1 and C2 are on when the heavy-duty flange is on because the PE2 marked pressure under 95 PSI, the lowest pressure based on the setting on I:1/03.

At last, I would like to thank you, my friends, for patiently following me until the end of this tutorial. Hoping you have got some benefits and learnt some new practices with the project we went through in this tutorial. Please stay safe, and let’s meet soon with another tutorial to enjoy learning and practicing ladder logic programming.

Bottle Line Assembly using PLC Ladder Logic Programming

Hello friends, we are going to learn and practice together one project from the industry. It is the bottle line production in which many processes are happening, including but not limited to filling, capping, and conveying from the start point where the bottles get in the line to the end point where the bottle gets out from the line. In the process, many concerns and restrictions must be addressed, like the bottle size, length, broken status, pretty full or empty, etc. So we have a lot to learn, program, and test right here in this project. Let’s jump into work and enjoy completing such an exciting project without further delay.

Bottle Line Assembly: Introduction

Figure 1 images the project we are going to do. Yes, it’s a massive project, with too many things we see to control. However, it’s not hard to be done because we grew up to be experts in ladder logic programming. Furthermore, we will apply the critical secret to make the large project easy, like a piece of cake that divide and conquer methodology. That can be happened by breaking down the whole project into small pieces and integrating these implement small pieces to have the entire process happen at the end of the day. Moving to the project itself, we can say we have two lines in the above line to describe the image shown below. The bottles are going to meet from left to right. The first sensor of proximity type sensor to check the presence of a bottle, and the next sensor of type limit switch to check the bottle size. The following sensor of type proximity is to check the excellent and broken bottles. Moving forward to the right, you can see guys at the filling station that can fill the small and large bottles. Then you will know the capping station. Also, we have a couple of motors being utilized to drive that project; the main engine in the first line, which is mounted at the left underneath the conveyor, moves the bottle forward from entry to the end. The second motor is mounted at the left of the second conveyor at the left that is used to move the output of the grinder of the broken bottles. The grinder motor on the following line properly grinds the broken bottle. The other engine installed at the third conveyor at the right is used to drive the final product conveyor. Also, you can see dozens of inputs and outputs, including sensors, switches, motors, valves, solenoids, and indicator lamps. The following section will list and describe these inputs and outputs in detail.

The inputs and outputs of the project

One of the most common and regular tasks you guys should do is tabulate the inputs and outputs in the project you develop. Table 1 below lists all the IOs in the project showing the names, addresses, and descriptions. I hope I have caught all of the IOs I listed in the table below; you can see, everyone, how important to have one table that lists all the inputs and outputs you need to use throughout the implementation process. The first step to start is to listen and write down the requirement and the philosophy of the logic of the process you will implement by listening to your client who requested that work from you. Feel free to ask them to confirm and validate the requirements once you have all requirements and narratives of the logic written down. You can go to the next step, designing the logic and breaking it down into small, simple parts. From there, you can start writing the ladder logic of each part and later integrate these parts to have the whole project done.

Name

Address

Description

Start

I:1/1

Commence the process

stop

I:1/0

Stop the process

Selector switch

I:1/2

Mode A operation


I:1/3

Mode B operation


I:1/4

Mode C operation 

Enter

I:1/5

To enter the setting value

Small bottle BCD

O:2/11

The digital counter of the small bottles

Large bottle BCD

O:2/12

The digital counter of the large bottles

Scrap parts BCD

O:2/13

The digital counter of the scraps

Boxes BCD

O:2/14

The digital counter of the boxes

Scrap conveyor

O:2/1

The scrap conveyor driver

Divert conveyor

O:2/2

The divert conveyor driver

Ls10

I:1/15

Scrap Boxes limit switch 

Grinder

O:2/3

The grinder driver

Divert gate

O:2/5


Scrap gate

O:2/4


The Main conveyor

O:2/0


Ls1

I:1/6

Limit switch to see bottle presence

Ls2

I:1/7

Limit switch to see scraps

Ls3

I:1/9

Limit switch to determine bottle size

LS5

I:1/10

Large bottle fill

LS6

I:1/11

Small bottle fill

LS7

I:1/12

Capping limit switch

LS8

I:1/13

The limit switch to detect scraping ready position

LS9

I:1/14

The limit switch to detect readily divert

Fill tube 

O:2/6

The fill tube valve

Cap Ram

O:2/9

The cap Ram





Bottle Line Project: Requirements

Because we plan to divide the project into small, simple parts, we also will present the requirements in parts. 

Part 1: start and stop the process of saving the bottle states 

In the first part, we are required to start the process by energizing the main conveyor motor, hitting the start push button, and stopping the process whenever the operator presses the stop push button. In addition, we need to save the states of the processed bottles, including the present state by using the LS1 limit switch, the bottle state (broken or good) status by using the LS 2 limit switch, and the size state (large or small) giving a hint that we can use bit shift left instruction. This requirement looks simple but wait, it’s just the start and also optimistically all parts of the project can be that simple by dividing your project into parts remembering the divide and conquer rule. So let’s do the first part.

The logic of the first part of the project

Figure 3 shows the simple ladder logic code of that part. The first rung is commonly known to latch the run status and the main conveyor by hitting start. But stops when pressing stop. The third rung uses the presence limit switch to call three-bit shift left instructions. In the first, the value of the reading of LS1 for existing status is saved in the 32 bits of the addresses b3:4 and b3:5. Similarly, the second BSL is to save the broken and good states, which is the readings of the LS2 in the 32 bits of B3:6 and B3:7. And in likewise the third BSL instruction saves the readings of the LS3 which is the size state of the bottles in the 32 bits in B3:8 and B3:9. Let’s simulate and show you guys how that works and what is the benefit of using BSL instruction?

The simulation and testing of part 1

Figure 4 shows the output of the execution of the part 1 simulation. You can notice, my friends, that the data files of the 32 bits in B3:4-B3:5 reflect the status of a bottle to LS1, and they are always 1’s because all bottles, regardless of the status, size, and case of the bottles. They are always there and seen by the sensor. For sensor LS2, it is a different story, as shown by the B3:6 and B3:7; the broken bottles show 1’s while the good ones show 0’s. Same for the LS3 that tells the size, the saved data in B3:8 and B3:9 shows when it is a large bottle by 1’s and small bottles by having the value 0’s. So you notice, my friends, we have completed the requirements of the first part, which seems simple, but it is essential because we now have the status of the bottles’ states, including presence, size, and excellent or broken bottles. We can now use the saved data to process the following requirements. So let’s do another part of the project.

Project part 2: Ladder Logic Program

This part of the project requires you guys to divert the long or large bottle to the diverter place on the right. Now it is time to use the data you saved in the first part of the project. Because you have the size of all incoming bottles, you can test the appropriate bit and command the solenoid to extend to open the divert gate when the bit is high. But wait a minute, which bit of the saved 32 bits do we need to do the test and decide? That’s such a brilliant question. Well, we need to count up from the position of the sensor LS2 that tells the bottle size until the point where the diverter is installed. By counting, we can see 20 bottles between the two positions. So if the data is located in B3:6 and B3:7, the bit we are looking for to use in testing is B3:7/4. So let’s try to see if that is correct or if we need to amend and correct that initial thinking that we thought.

Project part 2 

Figure 5 shows the minor modification we have added to fulfill what is requested in part 2. You can see, everyone, we have just added only one rung, which is the third one that says when the bit b3:7/4 is on, that means there is a bottle of an extended size that needs to be diverted. Therefore, the diverter solenoid is energized for that purpose. Ohh! We forgot to consider that we need to move the diverter converter to avoid the possible crash when another bottle comes over the previously processed one.

So when do we need to command the diverter conveyor motor to run for moving the conveyor? The answer is shown in figure 6; as you can notice, for everyone in rung number 4, It is a good idea to use the last bit, which offers a large bottle to move the conveyor to empty a slote to the incoming bottle. Therefore, we added one more rung to command the diverter conveyor motor when the last large-size bottle is presented. So now Let’s see the result of running this logic.

Simulation of part 2

Figure 7 depicts the results of testing the logic we have written so far up to part 2 of this exciting project. You notice how successfully the long-size bottles are rowed side by side. Yes, you can see the broken bottles are also included, which could be better, and that is what we will do in the next part. So let’s continue completing our project.

Project part 3

Now everyone, let’s move to a little bit harder part in which you must manage the scrap by activating the solenoid of the scrap gate to open when there is a broken bottle. Also we need to count the processed bottles, including small and good, large and sound, and scrap bottles. I know this time we asked many things to do but believe me, as you divide your projects into parts, as we do, it will be easy tasks. So now let’s see how to do the requirements for this part. Figure 8 shows the ladder; logic rungs for part 3. You can see guys in rung number 4 that we energized the gate when the bit b3:8/8 is ON. Why the eighth bit? Because the number of bottles between the sensor LS2 that detects broken bottles and the gate mounting point is eight bottles. The other four counting rungs from 5 to 8 are for measuring the small valid bottles, the large size bottles, and scraping bottles correspondingly. And at last, we summed the small and large broken bottles to get the total scrapped bottles. So let’s do one test for the code so far.

Simulation of part 3

Figure 9 shows the broken bottle has been diverted through the scraping gate, the large size redirected to the diverting gate, and the small valid bottles go onto the upper conveyor.

What’s next???

As you have seen in this tutorial, many tasks exist. We already have done a lot but still, have much to do together in this project. So following the tutorial, we will complete the filling bottle station and the capping station to deliver a complete project and production line. So be there and see you in the following tutorial very soon.

How to Properly Dispose of Solar Batteries: Everything You Need to Know

So you've installed a beautiful new solar energy system around your house or property. You're saving tons on your electric bill and never have to worry about blackouts, power surges, or planned outages—you control your power source now. Here's the problem: What do you do when you need to dispose of everything?

Eventually, you will need to replace the solar panels and the solar battery, which powers the whole system. Disposing of solar batteries isn't exactly simple, and it needs to be handled with the utmost care. But it is easy to navigate if you know the proper steps to take—and what to avoid. Here's our complete guide.

Disposing of the Battery

If you've recently purchased a solar energy system or portable solar generator, you know the current solar battery price . It's not low, but it has improved in recent years as technology evolves. Lithium batteries are rechargeable, but they don't last forever. 

Once your lithium battery dies or needs to be replaced, you should first call your local waste management authority. They will be able to direct you to the proper place to dispose of your solar battery safely.

Inquire About Recycling Alternatives

The lithium batteries often used for solar generators contain tons of materials that would adversely impact the environment if they were left to decompose in landfills. The National Library of Medicine warns about metals such as copper, nickel, and lead. Other concerning components include toxic and flammable organic chemicals that contain compounds like LiClO4, LiBF4, and LiPF6.

For this reason, you should ask the waste management authority about recycling options. Those chemicals must be disposed of properly, and many metals can be used elsewhere in other construction and manufacturing projects.

What Can Be Recycled?

Metals currently comprise about 13% of all that is thrown into the recycling . Still, if people took the time to learn how to recycle complicated objects such as lithium batteries, that number could rise even higher. Plenty of the materials used to make lithium batteries for solar generators can be recycled. Those that can be reused include:

  • Glass, which is the primary material used in the manufacturing of photovoltaic panels and can be found inside lithium batteries

  • Aluminum, which is 100% recyclable

  • Copper, nickel, and lead are all largely recyclable, and copper can be 100% recycled and reused.

Knowing what you can recycle is the first step to figuring out how to recycle it properly. 

The Cost of Not Recycling

As landfills rise, the cost to our environment grows. When items like lithium batteries containing dangerous compounds are thrown into landfills, they can decompose, and those compounds can render everything they touch toxic. 

The dangers of landfills include destroying natural animal habitats, producing toxic methane gas, contaminating water supplies, the production of ammonia, and more. Make sure to dispose of your battery safely.

Making the Smart Choice

You can make money from recycling your lithium battery, and you'll be helping save the environment in the process. There's no reason not to follow these steps.

Automatic Batch Mixing Tank with PLC Ladder Logic Programming

Hello friends, welcome back to our tutorials on PLC ladder logic programming. Today we will talk about batch process control and take one project from our factory to understand, implement, and simulate. So without any further delay, let’s jump into the tutorial by asking what is batch process is if it is different from other online processes. Well! The batch process is defined as a process that starts by operating continuously till the end of the cycle without any interaction with the users. For you guys, it’s cool to know that most of the processes you might meet in the industry of batch-type processing. Do you like me to give an example? Well! The Silo cement process is a batch process, and food and beverages manufacturing are also good examples of batch processes. So what do we have today of the batch process? It’s a batch-mixing process in which we mix liquids with a mixer. The process utilizes a couple of sensors and actuators to be performed, as we will see in the next pages. So let’s go further in our project.

Mixing batch process

Figure 1 shows a beautiful scene of the process that shows all components, including actuators, sensors, switches, and indicators. As you can see, friends, two pine lines supply the liquids to mix. For each line, a flowmeter switch tells the amount of liquid filled so far. It also shows one pump for each line to draw the liquid from the source to the mixing tank. Also, the liquids are mixed in the middle of the tank thanks to a mixer installed vertically in the middle of the tank. In addition, you guys notice the proximity switches installed on the top right of the tank to detect the level of the liquid .inside the tank to recognize two levels of the liquid. One is the low and the other for detecting the high liquid level inside the tank. Also, at the very bottom of the tank, you can see another pump installed underneath the tank at the center to drain the mixed liquid out from the tank. And also, the drainage pipe has a flowmeter switch to determine the amount taken out from the tank. On top of that, on the left, you see the control panel that helps operators start and stop. Set parameters of the process in addition to showing the process status throughout the process run, idle, stop status, the amount of liquid in the tank, and the amount of liquid drawn from each line. I know you are now gossiping ohh, that time we have a large project and too many things to control. No, no, brothers, it’s a simple process but let us go through the requirements and divide the work into parts and go do part by part together.

Mixing batch process operation

Every process has its logic or philosophy or the logical narrative that the client will tell or the customer. Your turn is to listen to him and ask for every details to make sure you have everything you need to start. Please validate your understanding and question your client about everything you need to start with a good understanding of the process and the requirements. The process between our hands to do today is nothing more than a batch process performed manually by the operator’s fingers. You will make it automated using PLC so that the operator will narrate to you what he does from the start to the end of the process cycle to complete the process. First, he starts by hitting the commencing button that starts the pumps P1 and P2 to draw liquid until the level of liquid in the tank reaches 90%, at which we should mark the tank as full and stop the pumps and the filling process. The next stage is to command the mixer to run for a while, which is decided by the client. In our project, we were told to run the mixer for 8 seconds. Afterward, the drainage pump runs to take out the mixed liques until the tanks are empty. At that time, we can repeat the process by hitting the start push button again for another cycle or continuously running cycle after cycle automatically. Also, you need to know the operator can stop the cycle at anytime. The indicator and BCD screen should tell the operator the current status and the amount of liquid input and output to and from the tank.

The process inputs and outputs

Table 1 lists all inputs and outputs of the mixing batch process. The first column shows the name of the Ios, the 2nd column presents the IO addresses, and the 3rd column informs a description of the IO.

Input/output

address

description

Input /output

address

Description

Flowmeter 1

I1/05

Flowmeter installed on pipe 1 to determine the amount input to the tank from that very liquid.

Pump 1

O:2/01

The pump that draws liquid from pimp line 1

Flowmeter 2

I1/06

Flowmeter installed on pipe 2 to determine the amount input to the tank from that very liquid.

Pump 2

O:2/02

The pump that draws liquid from pimp line 2

The Mixer 

O:2/00

The mixer contactor relay 

The high-level sensor

I:1/04

The level switch to detect the high level of the liquid

The low-level sensor

I:1/03

The level switch to detect the low level of the liquid

The input of liquid 1

I:1

The amount of liquid input through pipe 1 from the first liquid

The input of liquid 2

I:3

The amount of liquid input through pipe 2 from the second liquid

The output of liquid 1

O:2

The amount of liquid output through pipe 1 from the first liquid

The output of liquid 2

O:4

The amount of liquid output through pipe 2 from the first liquid

Thermostat

I:1/02

Temperature sensor 

Pump 3 

O:2/03

The pump to drainage the mixed liquid out from the tank

Flowmeter 3

I:1/07

The sensor detects the flow of the drained liquid

Heater 

O:2/04

Heater 

Run 

O:2/05

Run indicator

Idle

O:2/06

Idle indicator

Start

I:01/00

Start process switch

Stop

I:01:01

Stop process switch

full

O:02/07

The tank’s full status

Run

O:02/05

The process is in run status





 Batch Mixing Process with Ladder Logic

That can not be counted as a large-scale project. However, let’s deal with it as a large one. So, professionally will take it into parts to simplify our mission. The project will be divided into three small projects, So let us go through each part until we get the whole process done.

The filling process

In the filling part, we need to pump P1 by hitting the start push button until the level in the tank reaches full status when the liquid level becomes 90%. At then, pump P1 should be stopped. You see, guys, dividing the whole process into small, simple sub-processes make it easier to implement.

Implementation and testing

Figure 3 shows the ladder logic of the first part that controls the filling process. You see, guys, it simply latches the pump output O:2/1 by using the start push button and stops by either hitting the stop push button to stop the run or by reaching the full position by counting the generated pulses from input I:1/5 till it counts what is equivalent to 90% of the high level of the tank. So let us test that part and see if it is functioning well or if we need to amend the code we wrote.

Testing part 1 for the filling tank

Success is the result of testing part 1, as in figure 4. You see, guys, the tank kept filling by latching the pump P1. But when the counter accumulator reports 90% of the tank is full, the full flag stopped pump P1 as it is designed for that part. Now let’s move to the next part.

Emptying the tank

In this second part of the project, we are required to control the emptying process of the tank. The sequence is like when the full status of the tank level is reached, which is already achieved in part 2, the mixer should be activated for 8 seconds, and then the pump P2 will be energized to drain the tank till reaching to zero level of the tank at then the pump P2 will be stopped. So let us discuss the ladder code of that part. 

The ladder logic of the emptying process

Figure 2 shows the code we wrote to implement the draining process. We started displaying the code from rung three because rungs 1 and 2 are just like part 1 to fill the tank. In Runge 3,  we display the tank level by copying the counter accumulator value C5:1.ACC to the O:4 output of the BCD to 7 segment display. In Runge 4, we use timer T4:0 to count the 8 seconds during which the mixer will run, as in Runge 5. After the 8 seconds of mixing, pump P3 is energized to drain the mixed liquid as in runge 6. When you empty the tank, note down till reaching zero level as in Rung 7. At that time, pump P3 will have been stopped. I hope testing this stage goes okay, as we will check in the next section.

Testing the emptying process of the mixing batch process

As you see in figure 6, the emptying process is okay. The liquid is drained from the tank starting from the full position till reaching zero level position thanks to control of the drainage pump P3.

Figure 7 shows that the draining process continues till the liquid is drained from the tank.

The last part of having a continuous operation

After completing the whole batch process cycle, starting from filling the tank and ending with draining the liquid out from the tank, it is required to let the process run automatically, meaning the cycle repeats forever unless the operator requests a stop. Figure 8 shows the ladder logic code we added to automate the cycle. The amendment we have added in Rung 1 shows that to start the process by hitting the start push button; we added a flag B3:0/2 that indicates the end of the last cycle to start a new cycle automatically.  Also, we have added in rung 2 the code for the Idle process status indicator when there is no activity of either the mixer or pumps.

Testing the last stage

Figure 9 shows the idle status when there are no activities and the mixer and pumps are stopped.

I could not find a way to show you the continuity of the cycle, which is the target of the last part, because images can not do that. Instead, it should be through videos. So I hope you go through this tutorial and write the code or even your code and enjoy running the project on the simulator to see the cycle run autonomously. Thanks, my friends, for following me till that point on this tutorial, and I hope to meet again soon with a new exciting one.

Controlling 7-Segment Display with PLC Ladder Logic

Hi, my friends, and I hope you are doing great today! We have today one interesting topic that you have seen everywhere you go, but you might not notice it! That is what the so-called binary coded decimal (BCD) is. So what’s that? Well! When you are waiting for your turn at the front of a wicket in the bank. You see 7-segmented displays that show numbers in digits. So how do these counter displays work? The BCD is the idea behind how these displays work. Numbers can be represented in many formats. Some of these formats are readable for the public which is the decimal pr the digits 0, 1, 2, .., 9. On the other side, there is another number format which is not readable to general people. Still, it is essential for computation and computer processing like binary format and hexadecimal formats. Without going deeply into number format, we want to let you guys know that. The numbers are mostly displayed for people in digits or decimal format 0-9 but processed in binary by computer. So converting that binary format to decimal format is crucial in such an application. This tutorial shows you how plc can help perform as a BCD controller. 

BCD representation

As we have two formats to convert from to, figure 1 shows the digital format 0-9 that are displayed in the first column while the binary equivalent is represented by 4 bits A, B, C, and D. but we need to represent the 7 segment operation how it looks like and how it has been implemented in the past and in the present using the evolving development in computation and electronics. From there, we can jump to how the PLC can control the 7 segments and that kind of display.

The 7-segment display

Figure 2 images a 7-segment display that shows 7 LEDs a, b, c, d, e, e, and g. for displaying a digit from 0 to 9 we need to illuminate some of these lLEDs to shape the required digit.

For example, digit 1 can be formed by lit LEDs b and c while all other LEDs are off. Also, table 1 shows the states of the 7 LEDs for digits from 0 to 9.

Table 1: the equivalent states of the 7 segments for digits 0-9 

digit

a

b

c

D

e

F

g

0

1

1

1

1

1

1

0

1

0

1

1

0

0

0

0

2

1

1

0

1

1

0

1

3

1

1

1

1

0

0

1

4

0

1

1

0

0

1

1

5

1

0

1

1

0

1

1

6

1

0

1

1

1

1

1

7

1

1

1

0

0

0

0

8

1

1

1

1

1

1

1

9

1

1

1

0

0

1

1

Also, guys, Figure 4 Combines the digits, the equivalent binary inputs, and the outputs represented by the states of the 7 LEDs to form the number or the digit we need to display.

The logical circuit of the 7 segment 

The BCD to 7-segment decoder has been implemented by combining logic gates, as shown in figure 5.

This decoder is now available in the market as an integrated circuit IC as shown in figure 6. As you see, guys, the IC has the 4 binary inputs, and all the 7 LEDs, a, b, c, d, e, f, and g, come out as an output signal that will be connected to the 7-segment display to show the numbers or digits. So now it is the time for my friends to show how PLC can perform this piece of cake job by assigning 7 inputs from its input module to the 7 outputs that will be directed or connected to the 7-segment display. So let’s go doing this mission.

BCD to 7 segments using PLC

You can see, guys the project we are going to implement using ladder logic programming includes eight inputs and eight outputs. The requested digit can be formed by set the related inputs to high, and the outputs will be set accordingly. Then the outputs are connected to the 7 segments to display the requested digit.

The logic of the BCD to 7 segment project

First of all, guys, look at figure 8, which depicts how we design such a system. The inputs to the 7 segments IC will be the 4 binary bits A, B, C, and D, which are coming from the PLC outputs. These 4 bits will decide the states of the 7 outputs a, b, c, d, e, f, and g, which will be forwarded to the 7-segment display to display the target digit 0 to 9.

The logic is pretty simple my friends; it is straightforward because all that we need to do is to relay the inputs the user or the operator requested via the inputs switches of the PLC to the outputs of the PLC as shown in figure 9.

The ladder logic code of the project

Figure 10 shows the rungs of the ladder program of the BCD to 7-segment converter. As you see, guys, the code is very easy. It is nothing but assigning each input to its mate of the output for the eight bits that will be forwarded to the 7 segments to form the number or the requested digit.

Testing the BCD to 7-segment decoder by PLC

Figure 11 shows one of the tests to display digit 7. You can see, guys, that the output was 11100000, equivalent to the digit 7. That output will be forwarded as an input to the BCD to 7 segment IC. That results in setting the outputs a, b, c, d, e, f, and g and, in turn, displaying the digit 7 on the 7-segment screen.

Testing the hexadecimal format

The project can display the hexadecimal format also, as shown in Figure 12, which shows the Hexadecimal value FF that is equivalent to 11111111 in the binary format. So all the outputs are high, as shown in the results.

Finally, I would like to thank you all for following the tutorial until the end. I hope you enjoyed the idea and went step by step to code the project and practice simulating it as usual ti boost your capability of the PLC ladder logic programming.

How to Mine Cryptocurrency with Raspberry Pi 4?

Welcome to today's article on our comprehensive Raspberry Pi 4 programming guide. As we saw in the previous article, the Raspberry Pi 4 may power a single seven-segment display. In addition, we also interfaced a Raspberry Pi with 4 Seven-Segment Display Modules to display the time. However, this guide will show you how to construct a Raspberry Pi 4 crypto miner that uses very little electricity.

Cryptocurrencies have been the subject of widespread conversation for some time now. It's possible to use your computer to create them, and they can be used as currency. Because of this, the Raspberry Pi can also be used for Bitcoin mining. It's also possible to mine other cryptocurrencies. One drawback of mining is that the cost of electricity often exceeds the revenue it brings in. So, let's check out how to construct a solar-powered, money-making cryptocurrency miner with a Raspberry Pi.

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

Components

  • A pool account

  • Bitcoin Wallet

  • Raspberry Pi

  • Raspbian image SD card

  • USB Bitcoin miner

Mining for cryptocurrency: what exactly is that?

Crypto mining, the digital equivalent of the gold mining industry, involves a combination of complex mathematical calculations and blind luck. Mining is crucial for cryptocurrencies as it is the only way to update the distributed ledger (Blockchain).

Despite Bitcoin's popularity, there are other digital currencies available. All cryptocurrencies use blockchains to ensure that all transactions are legitimate and that users cannot spend the same cryptocurrency more than once.

Blockchain

To simplify things for the unfamiliar in the web3 environment, let's say that a blockchain is a distributed ledger that maintains track of all transactions made over it. Similar to how a bank keeps a record of who gave money to whom, how much was sent, and when it was sent, blockchain stores this unchangeable data within distributed blocks linked together via a network.

Users, known as miners or validator nodes, provide the network's computational power to verify all of the blockchain's transactions. This blog post will not delve further into smart contracts, which are computer programs that can be set up to run automatically on a blockchain if and only if specific criteria are met.

Bitcoin and Ethereum miners are sometimes pictured as a large server farm full of powerful graphics processing unit (GPU) or application-specific integrated circuit (ASIC) devices that work tirelessly to solve complex cryptographic puzzles issued by the blockchain in exchange for financial rewards. The consensus technique for validating submissions and awarding incentives varies from blockchain to blockchain.

Which Cryptocurrency is Ideal for Raspberry Pi Mining?

Raspberry Pi users can choose from several different coins to mine, but not all are profitable. The most profitable option is the one you should choose. The USB miner is crucial to mining since it dramatically boosts productivity. In mining, you have two primary options:

For anyone interested in beginning mining using a USB miner like NEWPAC, selecting a cryptocurrency that uses the SHA-256 algorithm is a must. Bitcoin (BTC), Bitcoin Cash (BCH), Bitcoin SV (BSV), and many others are just some of the cryptocurrencies that use the SHA-256 algorithm. However, Bitcoin is the most lucrative and should be explored first if you plan to mine using a Raspberry Pi.

The Raspberry Pi's central processing unit (CPU) can be used to begin mining in the absence of a dedicated USB miner. In such a scenario, you should go with Monero (XMR), the coin that can be mined with the least effort using a Raspberry Pi.

Can you make money mining Bitcoin in 2020 with a Raspberry Pi 4?

After calculating electricity and equipment costs, I found that bitcoin mining with a regular computer could have been more worthwhile. Most bitcoins are now mined using specialized computers called ASIC bitcoin miners; nevertheless, amateurs and enthusiasts still have some success mining by joining a mining pool. What if we set up a mining rig powered by a Raspberry Pi and solar panels and "deducted" the cost of the equipment? As the number of miners for Bitcoins increases, the difficulty of mining rises, and the rewards for miners decrease, the industry has become very competitive. Despite this discouraging information, I've decided to move on with this plan and shift my focus to alternative crypto assets.

Mining Pools

Since we are utilizing a Raspberry Pi rather than an ASIC bitcoin miner, individual crypto mining was not an option. Despite my best efforts, I could not locate any mining pools that supported the Raspberry Pi operating system among the many available for Windows and macOS. Since Linux miners are written for the x86 architecture, Raspberry Pi cannot participate in the mining process. Linux mining software that runs on x86 processors like those found on most personal computers is supported.

Please note that the purpose of this paper is to promote further study of blockchain technology and cryptocurrencies, not to create any of those assets. The techniques outlined here are workarounds that need to be endorsed by the developers. Instead, you can download the free software linked with your preferred mining pool and install it on your personal computer.

How to Use a Raspberry Pi to Mine Cryptocurrency

We'll first sign up for an account on minergate, a crypto mining pool with over 3.5 million users worldwide that supports Bitcoin, Gold, Zcash, Ethereum, Ethereum, and monero. Since Monero is the only crypto I have had success with, this guide will focus solely on that one.

  • Turn on your Raspberry Pi.

  • Press Ctrl-T or launch a Terminal window in Raspberry Pi OS using Desktop. Please use the standard login procedures while using Raspberry Pi Lite.

  • If you're already in the Terminal, you can install the updates and prerequisites immediately.

sudo apt-get update && sudo apt-get upgrade -y

sudo apt install git automake autoconf libcurl4-openssl-dev libjansson-dev libssl-dev libgmp-dev 

cd cpuminer-multi

  • Please use the below three commands to compile the mining code. This process will take a few minutes if you're using a Raspberry Pi 4.

sudo ./autogen.sh

sudo ./configure

sudo ./build.sh

  • Let's begin monero mining once we've installed and set up the mining program on our Raspberry Pi. To activate the miner, run the following line in the Terminal, substituting YOUR EMAIL with the address you used to create your minergate account.

./cpuminer -a cryptonight -o stratum+tcp://xmr.pool.minergate.com:45700 -u YOUR_EMAIL

The mining software will begin running, and if you're lucky, you'll see some 'accepted' shares marked with a "yes."

    Please log in to minegate/internal so we can inspect your Minergate Dashboard. This can be done on a PC or laptop using the Chromium web browser or on a Raspberry Pi using the Raspberry Pi Desktop interface. Find the Monero icon at the bottom of your screen. The ONLINE status will be displayed if Monero is connected and functioning correctly. Congratulations! You have started Monero mining!

    What are Monero's benefits?

    Now that we have a basic understanding of blockchain and cryptocurrencies, the issue of which currency is superior naturally emerges. The original cryptocurrency was Bitcoin, but there are now thousands of others, each with unique characteristics.

    Though Bitcoin transactions may be traced back to specific senders and recipients through their hash values, this is a significant drawback of the cryptocurrency.

    Monero is a cryptocurrency with unique rules in this regard. It's likewise mineable and based on a blockchain, but unlike bitcoin, the transactions here are anonymous and difficult to track. This is why most exchanges will not let you buy or sell Monero and why mining is the best option if you want some.

    Many more cryptocurrencies exist besides Bitcoin and Monero, such as the technically superior coins Ethereum and the humorous currency Dogecoin. The Raspberry Pi can be used to mine a large number of them.

    How to Automatically Start Crypto Mining with Your Raspberry Pi 4

    We'll utilize the Crontab approach to ensure that our cryptocurrency miner is always running on our Raspberry Pi.

    crontab -e

    If you haven't already, you'll see the message "no crontab for pi, Choose an editor" when you try to set the crontab.

    • Select 1 and press Enter.

    • Clicking here will launch a new crontab file; once it has opened, go to the bottom and add the following command, substituting YOUR EMAIL with the email you used to sign up for your Minergate account.

    @reboot sudo /cpuminer-multi/cpuminer -a cryptonight -o stratum+tcp://xmr.pool.minergate.com:45700 -u YOUR_EMAIL

    • To keep your crontab, hit Ctrl-X and then y.

    • Type "sudo reboot" into the Terminal to restart the Pi.

    How much Monero can Pi 4 mine? 

    After being powered on for almost 8 hours, my Raspberry Pi 4 has successfully calculated 357 good shares. Successful miners receive compensation when their shares are valued. If I do the math and get the appropriate answer, but my Pi is slower than another computer, I get a bad share. Only the first miner will be compensated if a miner submits a valid response before anyone else. Every invalid share is a penalty for the miner because of the possibility of fraud. I began to worry when my first four shares were flagged as invalid.

    357 good shares = 0.000001410642 Monero = 0.00015569 USD

    For 8 hours, I earned $0.000100, which is less than a penny. I was required to have at least 0.05 Monero (equivalent to about $5.811 USD) to make a withdrawal. (As of the date this article was published, the exchange rate was.) To attain the minimum withdrawal criterion of 0.05 Monero would take me 3,762 years at a rate of accumulating 0.000001410642 Monero per 8 hours.

    What We've Learned About Mining Cryptocurrency with a Raspberry Pi 4

    As was mentioned at the outset of this piece, the aim of this activity was education regarding bitcoin, not financial gain.

    • Mined cryptocurrency rewards are divided up based on hash rates and shares. My hash rate swung between 1.6 and 33.3 hashes per second. The pool averaged 10.27 MH/s, around 3 million times faster than my Pi. As a point of comparison, 1 MH/s equals 1,000,000 hashes/ sec.

    • Additionally, a tiny commission is added to your transactions by the Minergate. Choose a Pay Per Share structure or one based on chance (with more significant potential gain).

    • Many 'time out' and send line failed' errors appeared on my Pi as I wrote this essay. On occasion, a Pi reboot was required, but on other occasions, the miner resumed operations without any more intervention.

    • Even though my Raspberry Pi wasn't a "money maker" in the cryptocurrency mining game, we still had a great time seeing it effectively compute and accumulate excellent shares.

    How lucrative is Raspberry Pi mining?

    A person can easily mine bitcoins at home with minimal equipment. A powered external USB hub may be the way to go if you want to avoid shelling out the cash for a desktop PC. Bitcoin mining can be facilitated and made more profitable by using a powered external USB hub. Raspberry Pi version B, compatible with most PCs, is also readily available and inexpensive. You can use Bitcoins to buy and sell on websites or keep them safe in a digital wallet

     when you have Bitcoins. 

    Remember that large commercial Bitcoin miners employing thousands of computers will be your main competition. Still, a Pi 4 mining system is a fantastic (and entertaining) method of earning Bitcoins with little work. Because of the high cost of maintaining the hardware, mining Bitcoin using a Pi 4 is not financially sound. For Bitcoin mining, you'll also need hardware that's up to the task.

    To be sure, a Pi 4 mining system can be a fantastic (and entertaining) method of earning Bitcoins without much effort on your part. However, even if you only make a few Satoshi, you'll still gain valuable experience and knowledge, so it's a good use of time. Be mindful of your monthly electricity costs, though.

    Although you might make a few dollars mining on a Raspberry Pi, you won't become filthy rich overnight. Your electric bill may skyrocket if you've amassed a sizable Raspberry Pi fleet for mining. You can generate a small profit with a solar panel designed for the Raspberry Pi. The revenues won't make you rich, though; mining Monero with a Pi 4 and 100H/s of hashing power will net you just $1 per year. Making an annual average of $20 from mining using a USB miner is possible with Bitcoin.

    Conclusion

    We have developed a cryptocurrency miner that generates no additional costs whatsoever. The hash rate is a severe drawback of this design. Bitcoin mining on the Pi 4  is only profitable if the values of cryptocurrencies are supposed to remain the same. The upfront investment in equipment is more than the yearly return on investment from mining. One's perspective could alter if one were to speculate on the possibility of dramatically increasing prices. Those who are just sitting on unused hardware are in the same boat. A little setup is not worthwhile. The following guide will teach you how to set up a fingerprint sensor on your Raspberry Pi 4.

    Large Format 3D Printing: A Revolution for Engineers

    The world of large format 3D printing is dominated by a few key players who have emerged as the pioneers in this rapidly growing industry. Below are some of the biggest large format 3D printing companies and how they stand to benefit from this revolution:

    1. Stratasys: Stratasys is a leading provider of large format 3D printing solutions, offering a range of industrial-grade printers that are capable of producing high-quality prototypes and end-use parts. With its powerful proprietary Fused Deposition Modeling (FDM) technology, Stratasys is well positioned to capitalize on the growing demand for large format 3D Printing solutions.

    2. HP: HP is one of the largest and most well-known technology companies in the world, and it has recently entered the large format 3D printing market with its HP Jet Fusion technology. With its proven track record in the technology industry, HP has the resources and expertise to quickly establish itself as a leader in the large format 3D printing market.

    3. Massivit3D: Massivit3D is a leading provider of large format 3D printing solutions for the Engineering, Visual Communications, Entertainment, Academia, Interior Design, and Architectural markets. Leveraging its proprietary Gel Dispensing Printing (GDP) technology, the company’s solutions enable rapid and cost-effective production of scale 1 models and parts.

    4. Carbon: Carbon is a leading provider of large format 3D printing solutions that use Digital Light Synthesis (DLS) technology to produce high-quality, end-use parts. With its cutting-edge technology and strong focus on customer satisfaction, Carbon is well positioned to continue to grow and expand its presence in the large format 3D printing market.

    These companies stand to benefit greatly from the continued growth of the large format 3D printing market as more and more engineers, manufacturers, and other businesses adopt this innovative technology. By providing high-quality, cost-effective solutions for large format 3D Printing, these companies are helping to drive the growth of the industry and revolutionize the way products are designed and manufactured.

    Engineers Stand To Benefit Massively


    Large format 3D printing has revolutionized the engineering world by allowing engineers to quickly and easily create prototypes, designs, and finished products. By streamlining the manufacturing process, engineers can now focus on developing the best designs and products possible, instead of being bogged down by the time-consuming task of building prototypes by hand.

    One of the biggest advantages of large format 3D printing is the ability to produce parts and prototypes at a much faster rate than traditional manufacturing methods. This means that engineers can test and refine their designs in a fraction of the time it would take using traditional methods. In addition, large format 3D printing can be performed on a much larger scale, making it easier to produce large or complex parts and prototypes that would be difficult or impossible to produce using traditional methods.

    Another advantage of large format 3D printing is its ability to produce high-quality, precise parts and prototypes. This is because 3D printing uses computer-aided design (CAD) software to create detailed, accurate models. This precision and accuracy is essential for engineers, who need to ensure that their designs are functional and fit for purpose.

    In addition, large format 3D printing is incredibly versatile and flexible. Engineers can print parts in a variety of materials, including plastic, metal, and composites, to produce prototypes that are representative of the final product. This means that they can test their designs in real-world conditions, which is essential for ensuring that their designs are robust and reliable.

    Finally, large format 3D printing is also cost-effective. Traditional manufacturing methods can be expensive, especially when it comes to producing large or complex parts. With 3D printing, engineers can produce prototypes and parts at a much lower cost, which means they can focus their resources on developing the best possible designs and products.

    But, the above are just advantages to the world of engineering on a macro-level. How does large format 3D printing help engineers specifically? Here are just several concise examples:

    • Design Verification: Large format 3D printing allows engineers to produce prototypes of their designs in a matter of hours. This enables engineers to quickly verify the design’s form, fit, and function, leading to faster product development cycles.

    • Reduced Costs: By producing prototypes in-house, engineers can significantly reduce the costs associated with traditional prototype development processes such as tooling, shipping, and storage.

    • Improved Accuracy: Large format 3D printing provides engineers with highly accurate and precise parts. This level of precision can lead to better-performing and longer-lasting products, as well as reduced production time and costs.

    • Material Options: Large format 3D printing technology offers a wide range of material options, including plastics, metals, ceramics, and composites. This diversity of materials enables engineers to choose the best material for their specific applications, leading to improved performance and durability.

    • Customization: Large format 3D printing allows engineers to produce highly customized and complex parts, which are not possible to produce through traditional manufacturing processes. This level of customization can lead to improved product performance and increased customer satisfaction.

    • Increased Productivity: Large format 3D printing can significantly increase the productivity of engineers, as it enables them to quickly produce and test prototypes, reducing the overall time required to bring a product to market.

    • Sustainability: Large format 3D printing is a more sustainable manufacturing method compared to traditional methods as it reduces waste and energy consumption. Additionally, it enables engineers to produce only the parts they need, reducing the overall carbon footprint associated with the production process.

    In conclusion, large format 3D printing is a powerful tool that can help engineers streamline their work. By allowing them to quickly and easily produce high-quality, precise parts and prototypes, engineers can focus on developing the best designs and products possible. Whether it's reducing time-to-market, improving product quality, or reducing costs, large format 3D printing is a valuable tool that should be considered by all engineers looking to improve their workflow.

    Interface 7-Segment Display with Raspberry Pi 4

    Thank you for being here for today's tutorial of our in-depth Raspberry Pi programming tutorial. The previous tutorial taught us how to install a PIR sensor on a Raspberry Pi 4 to create a motion detector. However, this tutorial will teach you how to connect a single seven-segment display to a Raspberry Pi 4. In the following sections, we will show you how to connect a Raspberry Pi to a 4-digit Seven-Segment Display Module so that the time can be shown on it.

    Seven-segment displays are a simple type of Display that use eight light-emitting diodes to show off decimal numbers. It's common to find it in gadgets like digital clocks, calculators, and electronic meters that show numbers. Raspberry Pi, built around an ARM chip, is widely acknowledged as an excellent Development Platform. Its strong processing power can do amazing things in the hands of electronics enthusiasts and students. If we can figure out how to have it talk to the outside world and process data via an output, then we'll have a real chance of accomplishing all this. We analyze the data by viewing it on an LCD screen or other Display. Numerous sensors can detect specific parameters in the physical world and convert them to the digital world. It would never make sense to utilize a PI LCD panel to display a minimal quantity of information. Here, a 7-Segment or 16x2-Alphanumeric LCD panel is the preferred method of presentation.

    There are few uses for a 7-segment display that don't need an LCD panel, even though a 16x2 LCD is preferable in most. If all you need to do is show some numbers, then an LCD, which has the downside of having a small character size, is excessive. Compared to a regular LCD screen, seven segments have the upper hand in dim environments and can be seen from wider angles. Let's get started.

    Where To Buy?
    No.ComponentsDistributorLink To Buy
    1BreadboardAmazonBuy Now
    2Jumper WiresAmazonBuy Now
    3Raspberry Pi 4AmazonBuy Now

    Components

    • Jumper wires

    • Seven segment display

    • 1KΩresistors

    • Breadboard

    The 7-Segment and 4-Digit Display Modules

    The seven segments of a 7 Segment Display are each lit up by an individual LED to show the digits. To show the number 5, for example, you would make the glow pins for segments a, f, g, c, and d on the 7-segment high. This particular 7-segment display is a Common Cathode version, although there is also a Common Anode version.

    One 7-Segment Display Interfacing with Pi 4

    The wiring diagram for connecting a 7-segment display to a Raspberry Pi is shown below. Here, 7-Segment Common Cathode has been utilized.

    So, we'll simulate an 8-bit PORT on PI using its eight GPIO pins. Here, GPIO12 is the Most Significant Bit (MSB), while GPIO13 is the Least Significant Bit (LSB) (Most Significant Bit).

    If we wish to show the number 1, we must activate both segments B and C. We must supply voltage to GPIO6 and GPIO16 to power segments B and C. Accordingly, the hexadecimal value of "PORT" is "06," and the byte value of "PORT" is "0b00000110." If we raise both pins to their highest positions, the number "1" will be shown.

    The value for every displayable digit has been recorded and saved in a Character String with the label 'DISPLAY .'We have then used the Function 'PORT' to call those values one at a time and display the relevant digit.

    Explanation of the Code

    Once everything is wired up according to the schematic, we can power up the PI and begin using PYTHON to write the program. Below is a function that allows us to program the GPIO pins on the PI, and we'll go over the few commands we'll be using in the PYTHON program to do so. We are also changing the name of the GPIO pins in the hardware from "GPIO" to "IO," which will be used throughout the code.

    import RPi.GPIO as IO

    The general-purpose input/output (GPIO) pins we need to use may be occupied with other tasks. If that's the case, the program's execution will be interrupted by warnings. The below command instructs the PI to continue running the software regardless of the warnings.

    IO.setwarnings(False)

    Pin numbers on the board and pin functions can be used to refer to PI's GPIOs. This GPIO5 is similar to the one labeled "PIN 29" on the board. Here we specify whether the number 29 or the number 5 will stand in for the pin.

    IO.setmode (IO.BCM)

    To use the LCD's data and control pins, we have assigned those functions to eight of the GPIO pins.

    IO.setup(13,IO.OUT)

    IO.setup(6,IO.OUT)

    IO.setup(16,IO.OUT)

    IO.setup(20,IO.OUT)

    IO.setup(21,IO.OUT)

    IO.setup(19,IO.OUT)

    IO.setup(26,IO.OUT)

    IO.setup(12,IO.OUT)

    If the condition between the brackets evaluates to true, the looped statements will be run once. The value of PIN13 would be HIGH if and only if bit0 of the 8-bit 'pin' is true. There are eight 'if else' conditions, one for each of bits 0 through 7, so that each LED in the seven-segment Display can be set to either the High or Low state, depending on the value of the corresponding bit.

    if(pin&0x01 == 0x01):

       IO.output(13,1)

    else:

       IO.output(13,0)

    As x increases from 0 to 9, the loop will be run 10 times for each command.

    for x in range(10):

    The following command can create an infinite loop, with which the statements included within the loop will be run repeatedly.

    While 1:

    All other commands and functions have been commented on in the following code.

    Single 7-segment Display complete code

    import RPi.GPIO as IO            # calling for the header file, which helps us use GPIO's of PI

    import time                              # calling for time to provide delays in the program

    DISPLAY = [0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x67]            # string of characters storing PORT values for each digit.

    IO.setwarnings(False)            # do not show any warnings.

    IO.setmode (IO.BCM)           # programming the GPIO by BCM pin numbers. (like PIN29 as‘GPIO5’)

    IO.setup(13,IO.OUT)             # initialize GPIO Pins as outputs

    IO.setup(6,IO.OUT)

    IO.setup(16,IO.OUT)

    IO.setup(20,IO.OUT)

    IO.setup(21,IO.OUT)

    IO.setup(19,IO.OUT)

    IO.setup(26,IO.OUT)

    IO.setup(12,IO.OUT)

    def PORT(pin):                    # assigning GPIO logic by taking the 'pin' value

        if(pin&0x01 == 0x01):

            IO.output(13,1)            # if  bit0 of 8bit 'pin' is true, pull PIN13 high

        else:

            IO.output(13,0)            # if  bit0 of 8bit 'pin' is false, pull PIN13 low

        if(pin&0x02 == 0x02):

            IO.output(6,1)             # if  bit1 of 8bit 'pin' is true, pull PIN6 high

        else:

            IO.output(6,0)            #if  bit1 of 8bit 'pin' is false, pull PIN6 low

        if(pin&0x04 == 0x04):

            IO.output(16,1)

        else:

            IO.output(16,0)

        if(pin&0x08 == 0x08):

            IO.output(20,1)

        else:

            IO.output(20,0)   

        if(pin&0x10 == 0x10):

            IO.output(21,1)

        else:

            IO.output(21,0)

        if(pin&0x20 == 0x20):

            IO.output(19,1)

        else:

            IO.output(19,0)

        if(pin&0x40 == 0x40):

            IO.output(26,1)

        else:

            IO.output(26,0)

        if(pin&0x80 == 0x80):

            IO.output(12,1)            # if  bit7 of 8bit 'pin' is true, pull PIN12 high

        else:

            IO.output(12,0)            # if  bit7 of 8bit 'pin' is false, pull PIN12 low

    While 1:

        for x in range(10):            # execute the loop ten times incrementing x value from zero to nine

            pin = DISPLAY[x]        # assigning value to 'pin' for each digit

            PORT(pin);                  # showing each digit on display 

            time.sleep(1)

    Output

    The process of displaying a single number character on a 7-segment display is complete. However, we'd need more than a single 7-segment display to express information with more than one digit. Therefore, we will use a 4-digit seven-segment display circuit for this session.

    Four individual Seven-Segment Displays have been linked up here. For a 4-digit 7-segment display, we know that each module will have 10 pins, so there will be 40 pins total. Soldering that many pins onto a dot board would be a hassle for anyone; thus, I recommend that anyone using a 7-segment display do so by purchasing a module or creating their PCB. See below for a diagram of the relevant connections:

    In the preceding diagrams, we can see that the A-lines of all four displays are linked together as one A, and the same is true for B, C.... up until DP, which is essential for understanding how the 4-digit seven-segment module functions. Put another way, if trigger A is activated, the state of all 4 A's should be high.

    Nonetheless, this never occurs. The four extra pins labeled D0 through D3 (D0, D1, D2, and D3) let us select which of the four displays is driven high. As an illustration, if I want my output to appear solely on the second Display, I would set D1 to high and leave D0, D2, and D3 at low. Using pins D0–D3 and A–DP, we can easily choose which displays should be on and which characters should be shown.

    Using a Pi 4  to interface with a 4-digit, 7-segment display module

    Let's check the many options for interfacing this 4-digit seven-segment Display with the Raspberry Pi. As can be seen in the diagram below, there are 16 pins on the 7-segment module. Even if your module's resources are limited, it will provide at least the following.

    • Segmented pins, either 7 or 8 segments (pins 1 to 8)

    • Pin holder to the ground (here pin 11)

    • A 4-digit code to unlock the door (pins 13 to 16)

    See below for the wiring diagram of a digital clock built with a Raspberry Pi and a 4-digit Seven-segment display module:

    You can also use the following table to ensure your connections are correct and follow the diagrams.

    Locating the module's pins is the first step in making electrical connections. Identifying the Raspberry Pi's GPIO pins can be tricky; I've included an image to help.

    Raspberry Pi programming

    Here, RPi is programmed in the Python programming language. The Raspberry Pi can be programmed in a wide variety of ways. Since Python 3 has become the de facto standard, we've opted to use that version as our integrated development environment (IDE). At the bottom of this guide, you'll find the whole Python code.

    We'll go over the PYTHON instructions we'll be using for this project: first, we'll import the library's GPIO file; next, using the below function, we'll be able to program the Pi 4's GPIO pins. We are also changing the name of the GPIO pins in the hardware from "GPIO" to "IO," which will be used throughout the code. We've brought in time and DateTime to get the current time from Rasp Pi.

    import RPi.GPIO as GPIO

    import time, DateTime

    The GPIO pins we're trying to use are already being used for something else. The program's execution will be interrupted with warnings if this is the case. The PI will be instructed to disregard the errors and continue with the software using the below command.

    IO.setwarnings(False)

    The physical pin number and the corresponding function number can refer to PI's GPIOs. As with 'PIN 29,' GPIO5 is a physical component on the circuit board. In this case, we specify whether the number "29" or "5" will stand in for the pin. GPIO. In BCM notation, GPIO5 pin 29 will be represented by a 5.

    IO.setmode (GPIO.BCM)

    As is customary, we'll start by setting the pins to their default values; in this case, both the segment and digit pins will be used as outputs. In our code, we organize the segment pins into arrays and set their values to zero by declaring them to be GPIO.OUT.

    segment8 = (26,19,13,6,5,11,9,10)

    for segment in segment8:

        GPIO.setup(segment, GPIO.OUT)

        GPIO.output(segment, 0)

    We do the same thing with the digital pins, but we set them to output and set them to zero by default.

    #Digit 1

        GPIO.setup(7, GPIO.OUT)

        GPIO.output(7, 0) #Off initially

        #Digit 2

        GPIO.setup(8, GPIO.OUT)

        GPIO.output(8, 0) #Off initially

        #Digit 3

        GPIO.setup(25, GPIO.OUT)

        GPIO.output(25, 0) #Off initially

        #Digit 4

        GPIO.setup(24, GPIO.OUT)

        GPIO.output(24, 0) #Off initially

    Numbers on a seven-segment display must be formed into arrays. To show a single digit, we need to toggle the on/off status of all but the dot pin of the 7-segment Display. For the numeral 5, for instance, we can use this setup:

    For all alphabets and numerals, there is an equivalent sequence number. You can write on your own or utilize the handy table provided.

    Using this information, we can create arrays for each digit in our Python code, as demonstrated below.

    null = [0,0,0,0,0,0,0]

    zero = [1,1,1,1,1,1,0]

    one = [0,1,1,0,0,0,0]

    two = [1,1,0,1,1,0,1]

    three = [1,1,1,1,0,0,1]

    four = [0,1,1,0,0,1,1]

    five = [1,0,1,1,0,1,1]

    six = [1,0,1,1,1,1,1]

    seven = [1,1,1,0,0,0,0]

    eight = [1,1,1,1,1,1,1]

    nine = [1,1,1,1,0,1,1]

    Let's bypass the function in the code that would otherwise be executed before entering the while loop and begin displaying characters on our 7-segment Display. If you hook up a Raspberry Pi to the internet, it will read the current time and divide it into four separate variables. For instance, when the time is 10.45, the values assigned to h1 and h2 will be 1 and 0, while m1 and m2 will be 4 and 5, respectively.

    now = DateTime.DateTime.now()

        hour = now.hour

        minute = now.minute

        h1 = hour/10

        h2 = hour % 10

        m1 = minute /10

        m2 = minute % 10

        print (h1,h2,m1,m2)

    These four numbers will be displayed on one of our four digits. The lines below can be used to convert a variable's value to a decimal. Here, we show the value in variables on the 7-segment Display by using the function print segment (variable) with the digit 1 set to the highest possible value. You may be asking why we turn off this digit and why there's a delay after that.

    GPIO.output(7, 1) #Turn on Digit One

    print_segment (h1) #Print h1 on segment

    time.sleep(delay_time)

    GPIO.output(7, 0) #Turn off Digit One

    This is because the user will only be able to see the full four-digit number if all four digits are shown at once, and we all know that this isn't possible.

    How, then, can we simultaneously show all four digits? With luck, our MPU is considerably quicker than the human eye. Therefore we offer one number at a time but exceptionally quickly. The MPU and segment display are given 2ms (variable delay time) to process each digit before we go on to the next. A human being cannot detect this 2ms lag; therefore, it appears as though all four digits illuminate simultaneously.

    Understanding how to use print segment(variable) is the final puzzle piece. Arrays that have been declared outside of this function are used within it. As a result, the value of any variable passed to this function must be inside the range (0-9) so that the character variable can use in a meaningful comparison. Here, we check the variable against the value 1. The same is true for all comparisons with numbers between zero and nine. Assigning each value from the arrays to the appropriate segment pins is what we do if a match is found.

    def print_segment(character):

        if character == 1:

            for i in range(7):

                GPIO.output(segment8[i], one[i])

    Show the time on a 4-digit 7-segment display.

    Use the provided schematic and code to connect your components and set up your Raspberry Pi. Once you've finished setting everything up, you can open the software and check the 7-segment Display to see the time. However, before doing this, you should check a few things.

    • If you want to be sure your Raspberry Pi isn't stuck in the past, you should update its time.

    • If you want to utilize a 7-segment display on your Raspberry Pi, you'll need to plug it into an adapter rather than a computer's USB connection because of the large amount of current it consumes.

    Complete code

    import RPi.GPIO as GPIO

    import time, DateTime

    now = datetime.datetime.now()

    GPIO.setmode(GPIO.BCM)

    GPIO.setwarnings(False)

     #GPIO ports for the 7seg pins

    segment8 =  (26,19,13,6,5,11,9,10)

    for segment in segment8:

        GPIO.setup(segment, GPIO.OUT)

        GPIO.output(segment, 0)

        #Digit 1

        GPIO.setup(7, GPIO.OUT)

        GPIO.output(7, 0) #Off initially

        #Digit 2

        GPIO.setup(8, GPIO.OUT)

        GPIO.output(8, 0) #Off initially

        #Digit 3

        GPIO.setup(25, GPIO.OUT)

        GPIO.output(25, 0) #Off initially

        #Digit 4

        GPIO.setup(24, GPIO.OUT)

        GPIO.output(24, 0) #Off initially

    null = [0,0,0,0,0,0,0]

    zero = [1,1,1,1,1,1,0]

    one = [0,1,1,0,0,0,0]

    two = [1,1,0,1,1,0,1]

    three = [1,1,1,1,0,0,1]

    four = [0,1,1,0,0,1,1]

    five = [1,0,1,1,0,1,1]

    six = [1,0,1,1,1,1,1]

    seven = [1,1,1,0,0,0,0]

    eight = [1,1,1,1,1,1,1]

    nine = [1,1,1,1,0,1,1]

    def print_segment(charector):

        if charector == 1:

            for i in range(7):

                GPIO.output(segment8[i], one[i])

        if charector == 2:

            for i in range(7):

                GPIO.output(segment8[i], two[i])

        if charector == 3:

            for i in range(7):

                GPIO.output(segment8[i], three[i])

        if charector == 4:

            for i in range(7):

                GPIO.output(segment8[i], four[i])

        if charector == 5:

            for i in range(7):

                GPIO.output(segment8[i], five[i])

        if charector == 6:

            for i in range(7):

                GPIO.output(segment8[i], six[i])

        if charector == 7:

            for i in range(7):

                GPIO.output(segment8[i], seven[i])

        if charector == 8:

            for i in range(7):

                GPIO.output(segment8[i], eight[i])

        if charector == 9:

            for i in range(7):

                GPIO.output(segment8[i], nine[i])

        if charector == 0:

            for i in range(7):

                GPIO.output(segment8[i], zero[i])               

        return;

    while 1:

        now = DateTime.DateTime.now()

        hour = now.hour

        minute = now.minute

        h1 = hour/10

        h2 = hour % 10

        m1 = minute /10

        m2 = minute % 10

        print (h1,h2,m1,m2)

        delay_time = 0.001 #delay to create the virtual effect

        GPIO.output(7, 1) #Turn on Digit One

        print_segment (h1) #Print h1 on segment

        time.sleep(delay_time)

        GPIO.output(7, 0) #Turn off Digit One

        GPIO.output(8, 1) #Turn on Digit One

        print_segment (h2) #Print h1 on segment

        GPIO.output(10, 1) #Display point On

        time.sleep(delay_time)

        GPIO.output(10, 0) #Display point Off

        GPIO.output(8, 0) #Turn off Digit One

        GPIO.output(25, 1) #Turn on Digit One

        print_segment (m1) #Print h1 on segment

        time.sleep(delay_time)

        GPIO.output(25, 0) #Turn off Digit One

        GPIO.output(24, 1) #Turn on Digit One

        print_segment (m2) #Print h1 on segment

        time.sleep(delay_time)

        GPIO.output(24, 0) #Turn off Digit One

        #time.sleep(1)

    Output

    A similar section should appear below if everything is functioning as it should.

    7-segment Display limitations

    Typically, only 16 hexadecimal digits can be shown on a seven-segment display. Some show the digits 0-9, whereas others can show more. Seven-segment displays can only show a maximum of 16 values due to a lack of input leads. However, LED technology does allow for more than this. Even with the help of integrated circuit technology, the possible permutations of the seven parts on the screen are very few.

    Conclusion

    This guide taught us how to connect a 7-segment screen to a Raspberry Pi 4. The seven-segment Display, which we learned is employed in digital timers, clocks, and other electrical gadgets, are a cheap, basic electrical circuit and reliable module. Seven-segment displays can either be "common-anode" (where the common point is the power input) or "common-cathode" (where the common end is grounded). After that, we coded some python scripts to show numbers on a single seven-segment model and the time across four such screens. Next, we'll see how to use a Raspberry Pi 4 as the basis for a low-power Bitcoin miner.

    Motion Detection with PIR Sensor & Raspberry Pi 4

    Hello friends, I hope you all are doing well. Today, I am going to share the 4th chapter of Section-III in our Raspberry Pi programming course. In the previous lecture, we studied the Interfacing of IR sensor with Raspberry Pi 4. In this guide, you'll learn how to interface a PIR sensor with Raspberry Pi to create a motion detector. A passive infrared (PIR) sensor is a straightforward yet effective tool for motion detection.

    As a bonus, a piezo speaker will play an audio clip whenever motion is detected. GPIO pins are required for both of these accessories. This tutorial is a great starting point for those who have never worked with electronic components and circuits.

    These sensors are used in traditional, old-generation security systems. In contrast, video is used in most of today's monitoring systems. So, let's get started:

    Project Description

    Today, we are going to design a security project, where we will sound an alarm using a piezo speaker, if any motion is detected by the PIR Sensor. We will use Raspberry Pi 4 for today's tutorial.

    Here's the video tutorial:


    Components Required

    Here's the list of components, used to design this motion detector:

    • Raspberry Pi 4.
    • PIR Sensor.
    • Piezo Speaker.
    • 100-ohm resistor.

    What is a PIR sensor?

    • Infrared motion detectors, also known as passive infrared (PIR) sensors, are a type of motion sensor that makes use of IR light to identify and locate the source of motion.
    • A Fresnel lens is mounted on top of the PIR sensor, which increases the sensor's field of view to 120 degrees.
    • The sensor can detect human movement within an 8-meter radius around it.

    • Anything, alive or otherwise, having a temperature greater than zero degrees Celsius emits infrared radiation.
    • The wavelength of infrared radiation is far greater than that of visible light, making it invisible to the human eye.
    • Passive infrared (PIR) sensors are specifically designed to detect these heat signatures.

    As their name implies, passive motion sensors don't put out any rays of their own but instead pick up the infrared radiations emitted by other objects, making them ideal for use in intruder alarm devices. However, active detectors may produce and detect infrared light at the same time.

    PIR Sensor Pinout

    The PIR motion sensor has three pins:

    1. Pin1 is Vcc: We need to provide +5V to this pin.
    2. Pin2 is the data Pin: It's a digital Pin and sends sensors' data.
    3. Pin3 is GND: We need to connect it to the ground.

    PIR Sensor Working Principle

    In PIR Sensor, crystals sensitive to infrared light are used as sensors. As its a passive IR sensor, the sensor doesn't emit any IR waves, instead, it waits for the infrared-emitting object.

    The IR sensing component consists of two subassemblies, A and B.

    When there is no motion, the two detectors pick up identical infrared readings, which cancel out one another. Sensing element A will pick up the presence of infrared light, when an infrared-emitting object, such as a dog, enters the sensor's field of vision. Since the intensity of the infrared light striking sensing element B is still relatively low, the resulting differential change is positive.

    As the object moves past the sensor, the intensity of the infrared light falling on sensing element B will be greater than that falling on sensing element A, resulting in a negative differential change. The BISS0001 logic chip onboard detects and amplifies this potential difference before outputting it as a digital signal.

    When the infrared detector detects movement, it sends a signal to the microcontroller through the data input, which goes HIGH.

    PIR Sensor Adjustments

    The Motion Sensor also has two potentiometers that may be adjusted to fine-tune the PIR sensitivity and the amount of time its output signal stays high after detecting motion.

    As shown in the above figure, the left potentiometer allows you to adjust the sensor's sensitivity. Distances between 3 to 8 meters are adjustable. The Potentiometer can be turned clockwise to enhance the detection range and counterclockwise to decrease it.

    The second Potentiometer controls the duration of the motion sensor's HIGH output. Times might be anything from 0.3s to 600s. The POT can be adjusted by turning it clockwise(to increase time) or counterclockwise (to decrease time).

    Circuit Diagram of PIR Sensor with Raspberry Pi 4

    We will design a simple Motion Detection Project using PIR Sensor & Piezo Speaker with Raspberry Pi 4. It's a simple security system where the PIR sensor will detect motion and Piezo Speaker will trigger the alarm.

    A piezo buzzer is an easy-to-use speaker that makes noise whenever an electric current passes through it. The buzzer will sound an audible alert when the motion is detected.

    Here's the circuit diagram of PIR Sensor with RPi4:

    Just follow these steps to build the circuit.

    1. Connect the Ground Pin to the breadboard's ground rail.
    2. Connect the breadboard's positive rail with the +5v Pin.
    3. One wire of the Piezo buzzer should be connected to Pin7 of RPi and the second wire to the ground.
    4. Connect Pin11 of RPi4 to the breadboard with a wire. Connect a resistor of 100 ohms to the wire's terminal. The PIR sensor's yellow wire should be connected to the other end of the resistor.
    5. The PIR sensor's red wire must be connected to the breadboard's 5V line, while the black wire must be connected to the ground rail.

    Python Code for PIR Sensor with RPi4

    We begin by importing the GPIO and time Python libraries, allowing us to communicate with the GPIO rail and halt the script. For our first two variables, which I have aptly dubbed "pins," we provide a reference to our physical ports. Our sensors' states will be kept in the now-valued state variable. If this value is zero, it is not turned on; if it is one, it is turned on. We'll change our GPIO mode to use the real PINs rather than the physical ones. Since each pin is given a unique number, this system is a tad simpler. We also configured our GPIO pins as inputs or outputs. To do things like detect motion, we'll plug in a PIR sensor. On the flip side, we need our piezo buzzer to function as an output.

    import RPi.GPIO as GPIO

    import time

    pir_sensor = 11

    piezo = 7

    GPIO.setmode(GPIO.BOARD)

    GPIO.setup(piezo,GPIO.OUT)

    GPIO.setup(pir_sensor, GPIO.IN)

    current_state = 0

    A while loop that never ends appears below. Due to the inherent permanence of the conditional statement, this loop can always be maintained. (You can still hit ctrl + c on the terminal to abort the script). To begin, we'll pause the script for 0.1 seconds. The next step is to retrieve the sensor's current state; if that state is 1 (for instance, the motion has been detected), the code within the if statement will be executed. If the value is not 1, we enter an infinite loop in which the sensor is repeatedly checked.

    The if statement executes code that sets the piezo buzzer's output high, causing it to sound. This will occur for a split second before the script silences the buzzer. As soon as that timer expires, the if statement will leave, and the sensor will be rechecked after another five seconds. We have also used a try, except, finally, block with a nested outer block. Since stopping the script will require using the keyboard, we have included this. Finally, we must verify our script is tidy by calling GPIO.cleanup(). With the help of the try, except finally, coding construct, we can accomplish this.

    try:

        while True:

            time.sleep(0.1)

            current_state = GPIO.input(pir_sensor)

            if current_state == 1:

                print("GPIO pin %s is %s" % (pir_sensor, current_state))

                GPIO.output(piezo,True)

                time.sleep(1)

                GPIO.output(piezo,False)

                time.sleep(5)

    except KeyboardInterrupt:

        pass

    finally:

        GPIO.cleanup()

    Running the Script

    After you have completed all of your changes to the script, you may run it and see how it performs. Put the following command into your keyboard to accomplish this.

    sudo python motion_sensor.py

    The piezo buzzer should activate and make a noise if the PIR sensor detects motion in its field of view. If it doesn't, it's probably because you connected wires to the incorrect pins or because of a bug in the program. The Raspberry Pi's terminal will show an error message if it's a coding mistake.

    Complete code

    #!/usr/bin/env python

    import RPi.GPIO as GPIO

    import time

    pir_sensor = 11

    piezo = 7

    GPIO.setmode(GPIO.BOARD)

    GPIO.setup(piezo,GPIO.OUT)

    GPIO.setup(pir_sensor, GPIO.IN)

    current_state = 0

    try:

        while True:

            time.sleep(0.1)

            current_state = GPIO.input(pir_sensor)

            if current_state == 1:

                print("GPIO pin %s is %s" % (pir_sensor, current_state))

                GPIO.output(piezo,True)

                time.sleep(1)

                GPIO.output(piezo,False)

                time.sleep(5)

    except KeyboardInterrupt:

        pass

    finally:

        GPIO.cleanup()

    Output

    Quiz: Send data to your phone using an LTE modem

    This section is meant to test your understanding of this programming series so far, so I am leaving it as some homework for you. Build the circuit and comment below what the output will be. I will give an idea of the circuit and Python code.

    The LTE modem

    Based on the success of GSM/EDGE and UMTS/HSPA, the Long-Term Evolution (LTE) standard was developed to ensure the continued development of wireless broadband communication. My LTE modem is a USB add-on for the Raspberry PI, giving it 3G or 4G (LTE) cellular data access. The modem is not used for cellular access in this project; instead, it is used to notify my phone of motion through text messages. The AT commands and serial connectivity allow me to command the modem and relay messages to my phone.

    Connection

    Step 1: Install the software

    Begin by loading the required software onto your Raspberry Pi. Enter the terminal of the Raspberry Pi:

    sudo apt install python3 python3-gpiozero python-serial -y

    Step 2: Set up the modem

    The TRM240 LTE modem requires a SIM card, which can be inserted here. To improve the modem's signal, attach the antenna to the top of the device.

    Third, link the cellular modem to the Pi.

    Plug the LTE modem into a free USB port on the Raspberry Pi and power it on. The /dev directory should now list four additional USB ports. Just type this into the terminal to verify:

    ls /dev/ttyUSB*

    These gadgets should now be visible to you.

    Sending AT commands to the device will be done through the ttyUSB2 port.

    Fourth, link up the sensor with the Pi.

    The sensor output pin should be connected to the 8-pin to the Raspberry Pi, and the VCC and GND pins should be connected to the appropriate pins on the Pi.

    Connect the LED lights:

    The cathode of the LED should be connected to a ground pin, the anode (longer leg) should be connected to a current-limiting resistor, and the other portion of the resistor should be connected to a GPIO pin to cause the indicator LEDs to illuminate when motion is detected. Input the green LED into the 40-pin connector and the red LED into the 38-pin connector on the board. This is a discretionary procedure. You can disable the LED sections in the sample code below if you don't want them to light up in response to the motion.

    Launch the program below

    from gpiozero import MotionSensor, LED

    from time import sleep, time

    from sys import exit

    import serial

    import threading

    # Raspberry Pi GPIO pin config

    sensor = MotionSensor(14)

    green = LED(21)

    red = LED(20)

    # Modem configuration

    device = '/dev/ttyUSB2'

    message = ''

    phone_number = ''

    sms_timeout = 120 # min seconds between SMS messages

    def setup():

        port.close()

        try:

            port.open()

        except serial.SerialException as e:

            print('Error opening device: ' + str(e))

            return False

        # Turn off echo mode

        port.write(b'ATE0 \r')

        if not check_response('OK', 10):

            print('Failed on ATE0')

            return False

        # Enter SMS text mode

        port.write(b'AT+CMGF=1 \r')

        if not check_response('OK', 6):

            print('Failed on CMGF')

            return False

        # Switch character set to 'international reference alphabet'

        # Note: this still doesn't support all characters

        port.write(b'AT+CSCS="IRA" \r')

        if not check_response('OK', 6):

            print('Failed on CSCS')

            return False

        return True

    def check_response(string, amount):

        result = ''

        try:

            result = port.read(amount).decode()

        except:

            return False

        if not string in result:

            try:

                # Write 'ESC' to exit SMS input mode, just in case

                port.write(b'\x1B \r')

            except:

                return False

        return string in result

    def send_sms():

        global currently_sending, last_msg_time

        currently_sending = True

        try:

            port.write('AT+CMGS="{}" \r'.format(phone_number).encode())

            if not check_response('>', 6):

                print('Failed on CMGS')

                currently_sending = False

                return

            # Write the message terminated by 'Ctrl+Z' or '1A' in ASCII

            port.write('{}\x1A \r'.format(message).encode())

            while True:

                result = port.readline().decode()

                if 'OK' in result:

                    print('> SMS sent successfully')

                    last_msg_time = time() 

                    currently_sending = False

                    return

                if 'ERROR' in result:

                    print('> Failed to send SMS [{}]'.format(result.rstrip()))

                    currently_sending = False

                    return

        except:

            # Initiate setup if the got while the program was running

            setup()

            currently_sending = False

    def on_motion():

        print('Motion detected!')

        green.off()

        red.on()

        if time() - last_msg_time > sms_timeout and not currently_sending:

            print('> Sending SMS...')

            threading.Thread(target=send_sms).start()

    def no_motion():

        green.on()

        red.off()

    print('* Setting up...')

    green.on()

    red.on()

    port = serial.Serial()

    port.port = device

    port.baudrate = 115200

    port.timeout = 2

    last_msg_time = 0

    currently_sending = False

    if not setup():

        print('* Retrying...')

        if not setup():

            print('* Try restarting the modem')

            exit(1)

    print('* Do not move, setting up the PIR sensor...')

    sensor.wait_for_no_motion()

    print('* Device ready! ', end='', flush=True)

    green.on()

    red.off()

    sensor.when_motion = on_motion

    sensor.when_no_motion = no_motion

    input('Press Enter or Ctrl+C to exit\n\n')

    As mentioned above, I will not give the output for this program; instead, let me know if you were successful.

    Conclusion

    This is a basic introduction to the PIR sensor and merely scratches the surface of its potential uses. Simple things like a counter (which adds up as people, cars, or other objects pass by) can trigger far more complex actions, such as turning on a Pi camera or running a new script. I'm hoping you've learned a lot from this Pi 4 motion sensor tutorial and that you've been able to put together a beautiful circuit and make it work with some code. Feel free to leave a remark below with your views, questions, or complaints. In the subsequent tutorial, we'll learn how to interface an ultrasonic sensor with Raspberry Pi 4. Till then, take care. Have fun!!!

    Heartbeat Monitoring System with ADS1115 & Raspberry Pi 4

    Hello friends, I hope you all are doing great. Welcome to the 11th lecture of Section-III in the Raspberry Pi 4 Programming Series. In the previous tutorial, we discussed the interfacing of the Fingerprint sensor with Raspberry Pi 4. Today, we are going to discuss another sensor named the Pulse rate sensor and will interface it with Raspberry Pi 4.

    The field of healthcare monitoring has long been seen as a potential use case for IoT i.e. examining the health instead of regular checkups and local doctors. Using sensors, your vital signs can be monitored and transmitted in real time, allowing a physician on the other side or even an AI to analyze the data and provide an accurate diagnosis. That does seem somewhat futuristic. However, we are making steady progress in that direction and will soon have an autonomous IoT robotic arm operating on us.

    Project Description

    In today's tutorial, we'll design a heart rate monitor to keep tabs on a patient's heart rate, using Pulse Rate Sensor and Raspberry Pi. We will display the data(ECG graph) in the Processing IDE.

    Components Required

    Here is all, you'll need to put together a Raspberry Pi-based patient monitoring system yourself:

    • Raspberry Pi 4
    • Pulse Sensor
    • ADS1115 ADC board
    • Jumper wires

    Pulse Rate Sensor

    • The Pulse Rate sensor is used to measure the heartbeat of a person, it has an LED, a Light Photo sensor(APDS-9008) and an op-amp(MCP6001) in its construction.
    • Pulse Rate Sensor gives an analog output and using that output one can easily design its ECG waveform.
    • The LED should be placed on the vein, normally it's placed at the tip of the finger. The LED throws a red/green light on the vein.
    • The Light sensor absorbs the reflected LED light and based on its intensity delivers the output.
    • The op-amp receives the output, amplifies it and forwards it to the microcontroller.
    • A simple circuit is embedded for noise reduction.

    A human vein is positioned directly in front of the sensor's LED. The tip of your finger or the inside of your ear can serve this purpose, but it must be positioned directly over a vein.

    Heart Rate Sensor Pinout

    The sensor outputs three wires:

    • Signal (S).
    • Vcc (3–5 V).
    • GND.

    We'll use the 3.3V pin on the Raspberry Pi 4 to power up the sensor.

    ADS1115 Module

    • ADS115 is used to convert the analog signal into a serial signal and transmit it using I2C Protocol.
    • The 16-bit ADC ADS1115 has four analog signal channels.
    • This chip's I2C interface allows for serial data exchange with a host microcontroller or computer.

    We will use ADS115 to transmit the analog signal from Heart Rate Sensor to Raspberry Pi 4, as the Pi can't read analog signals. Both ADS1015 and ADS1115 are high-precision, low-power analog-to-digital converters. These chips are commonly used with the Raspberry Pi because they operate at 3V3.

    Any value from 8-860 samples/sec can be entered into ADS1115's sampling rate field. The shorter time an ADC needs to capture and transform an analog signal, the higher its sampling rate. A gain amplifier is included in the chip and can boost low-voltage signals by a factor of two to sixteen.

    Here's the pinout diagram of ADS1115:

    Here's the ADS1115's functional block diagram shown below:

    A multiplexer takes the analog signals from the inputs and routes them to a programmable gain amplifier. An I2C bus transmits the results of the ADC's conversion of the amplified signal to a microcontroller.

    Circuit Diagram of Pulse Rate Sensor with Raspberry Pi 4

    • As discussed above, the pulse rate sensor provides analog output, so we need to use ADS1112 to convert the analog signal into an I2C signal, which is then fed to the Raspberry Pi board.
    • Here's the circuit diagram of Raspberry Pi Interfacing with Pulse Rate Sensor:
    • Here's our hardware setup with RPi4, ADS1115 and Pulse Rate sensor:

    Here are the pin connections of the above circuit:

    • Pulse Rate Sensor's Signal Pin ===> A0 of ADS1115.
    • 3.3V from Raspberry Pi ====> pulse sensor's Vcc pin.
    • Connect the pulse sensor's GND pin to the Pi's GND.
    • Connect RPI's Ground to the Ground of the ADC Module
    • Connect the ADC module's supply voltage to the RPI's +5V.
    • Connect the ADC module's SCL and SDA to the RPI's SCL and SDA

    Installing Modules in Raspberry Pi

    Since the Analog-to-digital module uses I2C for communication, and we'll be using UART for serial communication, we'll need to activate UART and I2C on the Raspberry Pi by running raspi-config in the terminal.

    To proceed, click the Interfacing Options button.

    Select I2C and hit Enter.

    Now, click the Yes button and hit Enter.

    Now, select Ok to proceed.

     Pressing the Enter key after selecting Serial will activate the serial port.

     Select "no" and hit "enter" to turn off the serial login shell.

    To activate the serial, click Yes and then hit Enter.

     Choose ok and hit enter to continue.

     Click Finish and hit Enter to confirm.

     When prompted, type "Yes" and hit enter to reboot.

    Now proceed to install the i2c packages.

    sudo apt-get install -y python-smbus

    sudo apt-get install -y i2c-tools

    To determine which device is currently connected and to obtain its I2C address, run the following command:

    sudo i2cdetect -y 1

    Follow the below lines to install the Python library for the ADC module.

    sudo apt-get update

    sudo apt-get install build-essential python-dev python-smbus git

    cd ~

    git clone https://github.com/adafruit/Adafruit_Python_ADS1x15.git

    cd Adafruit_Python_ADS1x15

    sudo python setup.py install

    Processing Installation in Raspberry Pi 4

    Now, use the following command to add Processing to your current installation:

    curl https://processing.org/download/install-arm.sh | sudo sh

    We can now access Processing from the Raspberry Pi's main menu:

    We'll use Python and processing codes for the pulse sensor to get the job done.  

    Python Code for Heart Rate Monitor

    This code uses I2C communication to connect an ADC module that provides analogue pulse sensor output. Once the pulse sensor's analogue raw production is obtained, the sensor's higher maximum and minimum peak are located. Then calculate the beats per minute by subtracting the times of two extremes. Additionally, the BPM and raw analogue output are transmitted to a serial port, which is then read by the processing IDE. The complete python code for the heartbeat sensor on the Raspberry Pi is provided below.

    While developing this code, we used several modules that we imported at the outset for various applications.

    import Adafruit_ADS1x15

    import serial

    import time

    We now have variables upon which to perform analyses and take appropriate measures. Also, we made a serial object.

    rate = [0]*10

    amp = 100

    GAIN = 2/3

    curState = 0

    statechanged = 0

    ser = serial.serial("/dev/ttys0",9600)

    Now we use this chunk of code to transmit information to the processor.

    def send_to_prcessing(prefix,data):

    ser.write(prefix)

    ser.write(str(data))

    ser.write("\n")

    Now we have a pre-programmed function to read the pulse sensor and calculate the heart rate.

    def read_pulse();

    firstBeat=True

    seecondBeat=False

    ssamplecounter=0

    lastBeatTime=0

    lastTime=int(time.time()*1000)

    th = 525

    P = 512

    T = 512

    IBI=600

    pulse=False

    adc=Adafruit_ADS1x15.ADS1015()

    while True:

      signal=adc.read_adc(0,gain=GAIN)

      curTime=int(time.time()*1000)

      send_to_pressing("S",signal)

      samplecounter += curTime - lastTime

      lastTime=curTime

      N=samplecounter-lastBeatTime

      if signal>th and signal>P:

      P=signal

      if signal(IBI/5.0)*3.0:

      if signal

      T=signal

    The complete Python script for this post is provided for you at the end.

    Raspberry Pi Heartbeat Value Graphical Display Code Written with Processing

    As we saw above, the python code sends a loopback signal to the serial port of raspberry, and the processing code receives that signal. Now we can see the unprocessed analogue input and the beats per minute. Also, the BPM value will be displayed alongside the analogue-value-based graph. We've loaded a few crucial library modules into the processing code.

    import processing.serial.*;

    PFont font;

    serial port

    A few factors have been taken into account after this.

    char letter;

    string words="";

    int sensor;

    int IBI;

    int BPM;

    int[] RawY;

    int[] scaledY;

    int[] rate;

    float offset;

    color eggshell=color(255,2)

    int pulsewindowwidth;

    int pulsewindowheight;

    int zoom_val=70;

    long beat_rec_time;

    Then, we set up the serial port and the default graph in the setup method.

    void setup()

    {

    size(500,400); // stage size

    PulseWindowWidth=Width -20;

    PulseWindowHeight=height -70;

    frameRate(100);

    textAlign(CENTER);

    rectMode(CENTER);

    ellipseMode(CENTER);

    RawY=new int[PulseWindowWidth];

    scaledY=new int[PulseWindowHeight];

    We have parsed the received information at this point in the serialEvent method.

    void serialEvent(serial port)

    {

    string inData=port.readstringuntil('\n');

    inData=trim(inData);

    if(inData.charAt(0)=='S'){

    inData=inData.substring(1);

    sensor=int(intData);

    }

    if (inData.charAt(0)=='B'){

    inData=inData.substring(1);

    BPM=int(inData);

    beat_rec_time=millis()/1000;

    }

    if (inData.charAt(0)=='Q'){

    inData=inData.substring(1);

    IBI=int(inData);

    }

    }

    We've plotted the graph by mapping the incoming numbers to the graph's dimensions in the draw function.

    void draw()

    {

    background(0);

    nostroke();

    fill(eggshell); // color for the window background

    rect(250,height/2,PulseWindowWidth,PulseWindowHeight);

    RawY[RawY.length=1]=(1023=sensor)=212;

    offset=map((float)zoom_val/100.0,0.5,1,100,0);

    stroke(250,0,0);

    nofill();

    beginshape();

    endshape();

    if(millis()/1000>=beat_rec_time=5)

    {

    BPM=0;

    IBI=0;

    }

    The following lines of code are required to display the BPM over the graph.

    fill(255,0,0);

    textsize(24);

    text("Pulse Sensor Graph",width/2,25);

    fill(0,0,255);

    textsize(18);

    text("IBI:" + IBI + "ms",width -70, height -10);

    text("BPM:" + BPM, 50, height-10);

    textsize(12);

    text("zoom:" + zoom_val + "%", width -50,50);

    Here, the code also includes a zoom function, allowing the user to selectively enlarge or reduce the size of the shown plot. The pulse plot can be panned around by pressing - to zoom out and + to zoom in. To adjust the setting, we must first click anywhere on the graph and then use the minus and plus buttons.


    void Keytyped() 

    {

    if(key == '+')

    {

    zoom_val++;

    printIn(zoom_val);

    }

    else if(key == '-')

    {

    zoom_val--;


    printIn(zoom_val);

    }

    if(zoom_val>100)

    zoom_val=100;

    else if(zoom_val<=0)

    zoom_val=0;

    }

    Thus, using a Raspberry Pi, one may monitor a patient's heart rate and graph the results. This serial data can also be sent to IoT platforms like ThingSpeak for global data sharing if necessary.

    Complete Code

    import Adafruit_ADS1x15

    import serial

    import time

    rate = [0]*10

    amp = 100

    GAIN = 2/3  

    curState = 0

    stateChanged = 0

    ser = serial.Serial ("/dev/ttyS0", 9600)

    def send_to_prcessing(prefix, data):

            ser.write(prefix)

            ser.write(str(data))

            ser.write("\n")

    def read_pulse():

        firstBeat = True

        secondBeat = False

        sampleCounter = 0

        lastBeatTime = 0

        lastTime = int(time.time()*1000)

        th = 525

        P = 512

        T = 512

        IBI = 600

        Pulse = False

        adc = Adafruit_ADS1x15.ADS1015()  

        while True:

            

            Signal = adc.read_adc(0, gain=GAIN)   

            curTime = int(time.time()*1000)

            send_to_prcessing("S",Signal)

            sampleCounter += curTime - lastTime

            lastTime = curTime

            N = sampleCounter - lastBeatTime

            if Signal > th and  Signal > P:          

                P = Signal

         

            if Signal < th and N > (IBI/5.0)*3.0 :  

                if Signal < T :                      

                  T = Signal                                                 

            

            if N > 250 :                              

                if  (Signal > th) and  (Pulse == False) and  (N > (IBI/5.0)*3.0)  :       

                  Pulse = 1;                       

                  IBI = sampleCounter - lastBeatTime

                  lastBeatTime = sampleCounter       

                  if secondBeat :                     

                    secondBeat = 0;               

                    for i in range(0,10):             

                      rate[i] = IBI                      

                  if firstBeat :                        

                    firstBeat = 0                  

                    secondBeat = 1                  

                    continue                              

                  runningTotal = 0;               

                  for i in range(0,9):            

                    rate[i] = rate[i+1]       

                    runningTotal += rate[i]      

                  rate[9] = IBI;                  

                  runningTotal += rate[9]        

                  runningTotal /= 10;             

                  BPM = 60000/runningTotal       

                  print("BPM:" + str(BPM))

                  send_to_prcessing("B", BPM)

                  send_to_prcessing("Q", IBI)

            if Signal < th and Pulse == 1 :                    

                amp = P - T                   

                th = amp/2 + T

                T = th

                P = th

                Pulse = 0 

                

            if N > 2500 :

                th = 512

                T = th                  

                P = th                                              

                lastBeatTime = sampleCounter

                firstBeat = 0                     

                secondBeat = 0                   

                print("no beats found")

            time.sleep(0.005)

    read_pulse()

    Output

    Conclusion

    By collecting data from a wide variety of sources and transmitting it across a global network of the internet as well as other communication devices that are, in turn, linked to cloud services, the system improves the quality of care provided to patients. It allows doctors to respond to medical emergencies more quickly. In the suggested system, a doctor can do a checkup on a patient at any time, from any location. If the patient's value rises over the level, they should see a doctor, and an urgent message will be sent to them through email. Paralyzed patients and those ordered strict bed rest can benefit from this method since it allows their doctors to keep an eye on them from afar using a Raspberry Pi camera. More sensors can be integrated into the system, and the Internet of Things can be expanded so that everything can be accessed instantly. The model can be improved upon and made available as a mobile application so that users anywhere in the world can access it with minimal effort. In the following lesson, we will learn how to connect a PIR sensor to a Raspberry Pi 4.

    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