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.

Advance Counter Functions in PLC Ladder Logic

Hi, my friends. Welcome to share a new tutorial in our ladder logic programming series. Today we will discuss counters in ladder logic programming using an expert’s view. So let’s wear the glasses of an expert in ladder logic programming and look deeply into counters, the types of counters, their variables and bits. In addition, techniques of using counters to solve a different kinds of problems that need counting. And without questions like every time, we will enjoy practicing programming and simulating all about counters. So with no further delay, let’s jump into our tutorial and nail that counters.

Counters in real life

Tell me, guys, if you can imagine an industrial project or machine that does not need to count parts, products, or processing cycles. Actually, in most cases in industry and practical operations, you will find counters everywhere you visit production lines or operating machines. So now, what are the types of counters and what is inside or belongs to counters, their variables and bits? Also, what are the techniques for utilizing counters in ladder logic programming?

Counter Types

As regards functionality, counters can be divided into count up and count down, as shown in figure 1. Counter-up and down instruction blocks are shown in CTU and CTD. One is to count up, and the other is used to count down. They are different in functionality. However, they have the same variables, parameters, and data bits. So let’s discuss all this data belonging to counters.

Counter data bits

Figure 2 images the data of counters. On the left tree, you guys notice the counters in the data files and on the right, see many counters that you can use in your ladder logic program. Also, the main variables are the preset value and the accumulator value by which you tell the program the counter will count up or down to what value. Also, you should know the left side of the rung is the input to the counter to activate it and let it counts when the input is high. While the right side is the output data bit of the counter which is the enable EN bit that tells the counter block has run okay. And the done bit DN that informs the counter reached the desired preset value by turning into high when the accumulator variable ACCUM goes equal to the PRESET value.

How to use counters in PLC?

Figure 3 shows the best practice for utilizing counters and handling their logic. In the first rung, we used input I:1/0 to control the CTU counter set to count up to 10. So every time the input to the counter turns from low to high, the counter will count up by incrementing the ACCUM. Also, we have used the RES instruction to reset the counter at any time by having the input I:1/1. So by having the input I:1/1 turned to high, the counter’s accum will reset to zero. Now moving to the important part that provides the clue to process and handle counters. Starting from rung 3, the comparison instructions are used to check the ACCUM and control the outputs according to the logic we designed for. For example, in rung number 3, the EQU instruction compares the accumulator C5:1.ACC to zero to check if they are equal and if so, it energizes output O:20/0. In contrast, the NEQ compares instructions to check the inequality of the source C5:1.ACC and zero to decide the next state of output O:2/0. Furthermore, Runge 004 combines greater than GTR and less than instructions to check if the accumulator value is between two values and decide the state of the output on the right. Continuing further, the greater than or equal GTE and less than or equal LTE are used to check the accumulator as well but considering the boundary values.

Counter example with simulation

Figure 4 demonstrates an example of the counter in which input I:1/1 has been used to control the counter input, and input I:1/2 is used to reset the counter. Also, in the third runge, the done bit of the counter controls the state of output O:4/0.

Simulating counter example

Figure 5 shows the simulation of the counter’s example. It shows the counter counts up every transition from low to high of the input I:1/1. Also, it shows that the output’s state of O:4/0 has come to high when the counter’s accumulator has reached the value of the preset value.

Also, as you see, friends, when input I:1/2 has clicked, the counter accumulator has been reset to zero thanks to utilizing the reset instruction RES.

Example of using comparison instruction with counters

Figure 7 demonstrates how using the comparison instructions to handle counters by comparing the accumulator of the counters, checking its value and controlling outputs accordingly. For example, in rung 002, output O:4/0 will go high when the counter’s done bit goes high or when it counts to 10. Also, output O: 4/4 will be turned to high in rung 004 when the accumulator of the counter is something between 3 and 7 but not 3 and 7 themselves. To include boundaries 3 and 7, the comparison instruction less than or equal LTE and greater than or equal GTE are used as rung 005 to control O:4/7. Also in rung 005. The compare instruction EQ is used to decide the state of output Q:4/6. In the simulated running example, when the counter’s accumulator was equal to 3, outputs O:4/7 and O:4/6 turned to true based on the results of the comparison instructions.

Tracking the data table

Exploring the data files on the left part of the view, you can also see the values and states of the counter’s variables and data bits. The value PRE is 10; the accumulator variable ACC is 10. So, the done bit DN is true or 1. Also, the function of the counter with cunting up is shown as 1.

Small PLC project using counters

After showing how to use the comparison instructions and introducing the counter variables and data bits, it is time to do something with counters. And here it is in figure 9; you can see a funny example of singers. In that example, we use two counters, CTU and CTD, to count up and down. The program utilizes flag B3:0/1 to manage which counter will be activated. As you see in rung number 1, when b3:0/1 is false, the counter CTU will be active to count up. By the time the counter reaches 10, its done bit turns high to activate flag B3:0/1. Then, the counter CTD is active to count back down to zero. And finally, when the CTD counts down until reaching zero, the flag B3:0/1 has turned off using unlatch (U) instruction to repeat the process again and again. So let’s see some tests for the implemented code to check if it is correct or if something needs to be amended.

Figure 10 shows the counter CTU is counting up every chance the input I:0/1 turns from OFF to ON.

Figure 11 shows how the logic turns to activate CTD after counter CTU reaches its preset value by flipping flag B3:0/1.

Figure 12 shows that the process has returned to count up after the accumulator has reached zero.

Now, guys, we have nailed counters showing the variables and related data bits and techniques of utilizing the comparison instructions to handle the counters logically. Thanks, guys, for following me up here . I hope you have enjoyed learning and practicing the counters in ladder logic programming. I hope to meet again with an interesting tutorial of our series of ladder logic programming.

Advance Timer Functions in PLC Ladder Logic Programming

Believing in the essence of timers in ladder logic programming, we come today with a new tutorial in which we are going to show you all about timers, the types of timers, what’s inside timers’ block of parameters, variables, and bits. In addition, techniques for using timers will be explored, and for sure, we are going to practice what we learn using the simulator. So let’s get started with our tutorial.

Timers in ladder logic programming

Guys, this is not the first time we’ve talked about timers. However, this time we are going to look into timers deeply and use the glasses of practical approach. So figure 1 shows the most important types of timers in ladder logic from left to right: the on-delay, off-delay, and retentive timers. There are differences in functionality. However, they all have the same parameters, variables, and bits. For example, the on-delay timer (TON) works by starting counting by getting the high logic state of its input. And bit goes ON when and only when the counter reaches the preset value. While the off-delay timer (OFF-DELAY) employs starting with the high logic of its Done bit once it has a high logic of its input. And when its high input stat is gone and turns to low. It starts counting until reaching the preset value, and then the done bit goes off. On the other hand, the retentive timer keeps accumulating the time while the input is energized until it reaches the preset value, at then the Done bit goes on. You can see, my friends, how are different in functionality to help you get a way for every problem related to timers. Despite that variety in behavior, they have the same data, as you can see in each timer block. So now, what are these data, and how can we utilize them in ladder logic programming? that is what we are going to learn together in this tutorial.

Timer data in PLC

Well! Timer data can be demonstrated in figure 2. You can see guys in the tree view windows below; the data section shows the timers data in which there are dozens of timers you can use through long your program. But what does the data include? Well! The data has timer bits and variables, as shown on the right side of the window. The most important variables are the preset variable (PRE), in which we set the value of the time at which we require the timer to act ON. The other variable is the accumulator variable ACC that we use to know what the counted time is so far. The logic says the timer keeps increments accumulator until reaching the preset value. Okay, then what happens when the accumulator reaches the preset value? Exactly, the timer needs to indicate that he reaches the target.  There are so-called timer bits like the timing bit TT that reports the timer is timing, and the DONE bit that tells the accumulator has reached the preset value. And also the EN bit that shows the completion of execution of the timing instruction.

Most Common PLC Timer Types

Well, timers can be categorized based on their functionality and the way they work. For instance, the ON-DELAY timer starts timing when it gets a trigger signal which is the high state of its input. By reaching the preset value, the output will have been energized as long as the input is high. Please, guys, see the timing diagram in Figure 3 which depicts the timing diagram of the input and output of the ON-DELAY timer. It shows the timer contact goes on after counting the preset time value since it receives a high logic on its input coil.

The second but same important kind of timer is the OFF-DELAY timer. This timer starts energizing its contact or output from the moment it receives high logic input. Then after that input goes low, the output remains high in the logic state for as long as the preset value has been specified. Please, my friends, find the operation cleared in figure 4 below, which demonstrates the operation by the language of the time. In this example, the timer coil has been energized, and its contact goes high. And when the coil de-energized, the contact remained high for 5 seconds which is the preset amount of time of the timer.

The third timer we are going to show today is the retentive timer. So what does that timer do? Well, that timer accumulates the time whenever its coil is ON. The timing diagram is shown below in figure 5.  More details about the timing diagram of retentive timers, what figure 5 demonstrates. You can notice, my friends, as long as the input is high, the timer accumulator keeps accumulating the time until one reset signal appears, then it resets the time. But it returns back, accumulating the time whenever the input is true.

Now we will show some examples to let you understand how to employ the timer variables and bits as well. Figure 6 shows the timer block of an OFF-DELAY timer. You can see, guys, the timer’s name is T4:1, the time base is set to 00.1, and the preset value is set to 100, meaning it is designed to time for 10 seconds that can be determined by multiplying the time base to the preset value. Also, you can see that the first rung used input I:1/0 to enable the timer by energizing its coil. Rungs 1 to 3 show how you guys might use the timer bits. For example, in rung number 1, the enable bit of the timer is used to energize output O:2/0. Similarly, the timing bit TT of the timer is utilized to turn on output O:2/1 in rung 002. While the done bit DN energizes output O:2/2 as in rung 003.

Simulating one example

Here it is the simulation of one example to show how the timers bits and variables can set and used. In figure 7, the timer of type on-delay T4:4 is used and set to time for 10 seconds by setting the preset to 100 and the time base to one-tenth 0.1. the timer’s bits are used as you can see my friends to activate different outputs.

Example showing timers types

Another example demonstrated in figure 8 to show the on-delay and off-delay timers working together to fulfill the requested logic.

Retentive Timer example in Ladder Logic

Figure 10 shows an example to demonstrate the utilization of a retentive timer type. You can see the timer block of the retentive timer RTO and how it is accumulating the time whenever the input is high without resetting when the input is turned off.

Timers programming techniques

Going to one of the most important parts of our tutorial is how professionally you guys can use the timers to solve whatever problem you have. The techniques to use timers that come with experience. For example, figure 11 shows the cascading timing technique in which you can use multiple timers based on each other in a cascading way. You see, guys, how timer T4:2 depends on the Done bit of timer T4:1 in cascading approach. Why do we need to use two timers in such a way when we can use only one with a preset value equal to the sum of the two timers? That’s smart to be asked. But the answer also is intelligent, which tells us we might need to do some action in between. For example, when timer number one has done timing, we might energize one output, and after the second, we perform another action depending on the first timer.

Reset the timers in Ladder Logic

Figure 12 shows the technique to reset the timer by having one normal close contact in the way of its input to control energizing the timer coil. In that very example demonstrated by figure 12, the timer Done bit itself is used to reset the timer, meaning that when the time contact acted ON, it is the time to reset the timer and like that, we can guarantee the timer keeps repeating the process forever.

And at that point, I would like to thank all my friends for following me till the end of that tutorial, and I hope you have learnt some knowledge and enjoyed practicing one of the most important topics in ladder logic programming, Timers. For recapping have nailed the timers by demonstrating the variables and bits of the timers and the types and techniques of using the timers to flexibly and professionally can deal with different situations and solve any problems related to using the time.

Traffic Signal Control with PLC Ladder Logic Programming

The traffic light is one of the most important applications we see everyday everywhere we go back and forth. Controlling traffic signs was managed by people which was very problematic and headache on travelers and the officers as well. But nowadays, most traffic lights are controlled by automatic control systems. The brain that handles the complicated logic behind the traffic light control system is a PLC and one programmer like you guys has written its logic. So today we have come back to enjoy programming such a critical and large project by using ladder logic programming and for sure will apply the code and the logic we write into the simulator to check its correctness.  

Problem we try to solve

First of all, the scene we captured below by figure 1 shows two ways to cross a traffic signal, the biggest and most complicated traffic sign you might see anywhere you go. We need to go through the logic and requirements and then list these alongside with the restrictions for realizing the safety which is very critical and crucial right here for saving people and vehicles traveling in each way in  the cross traffic light. The complete project will be divided into two tasks to simplify the project and each task will be an exercise for you guys to do. So without any further delay let’s jump into our project’s exercises.

Project description

As you can see in figure 2, there are two faces of three traffic lights, one for each side way to control the cross traffic light. Each traffic light side has three indicators RED, green, and Ampere to represent the stop, ready-to-cross, and about-to-change that tells the car drivers and pedestrians when to stop and what time they can continue crossing. Each lamp has assigned to one output as you can see guys in the image. Our task is to control the timing of lighting each indicator to achieve the whole process. As we have mentioned earlier we are going to work the project into couple of milestones. So let we names two milestones in the first one we are going to control one way and will complement the work by adding the code to manage the two crossways by reaching that point we will have completed our mission. So let’s getting into the work.

The one way control Part 1

Table 1 below lists the required amount of time and the sequence of the lighting of each indicator for controlling one way of the cross traffic light control project. As listed in the table below, the red light is connected to output O:2/00 and it is required to light it for 12 seconds. Then the green light that is connected to output O:2/02 should be lit for 8 seconds and finally the Amber light for 4 seconds which is connected to output O:2/01. Remember my friends, we need to repeat the process forever.

RED

GREEN

AMBER

12 Sec.

8 Sec.

4 Sec

The ladder logic code 

Figure 3 shows the program of the first part to control one way. You notice guys the program is mainly based on utilizing timers. The idea is simply to start with an on-delay timer of the whole period which is 24 seconds. As it is clear the first rung energizes the timer T4: 0 to start timing for 24 seconds. Then by comparing the accumulating time, the second rung activate the green light for 8 seconds by using the comparing instruction LES in the way like keep energize the red light that connected to O:2/0 as long as the the accumulator of T4:0 which is is T4:0.acc less than 12 seconds. In the same way, in the period between 12 to 20 seconds the green light is activated for 8 seconds thanks to using the comparing instructions GRT and LES. And finally command the amper light to energize after 4 sec to the end. Notice my friend to let the process repeat forever, the timer is cleared or restarted by enabling the flag B3:1/0. Let us test the logic we have just implemented to see if it can work fulfilling the requirements or not.

Testing part 1 using simulator

The evaluation of the first part is depicted by figure 4. See guys the red sign is lit for 12 seconds and the green light follows for 8 seconds as shown in figure 5.

And figure 6 below depicts the ampere lighting for 4 seconds. Now you can see we have completed the first part.

But wait my friends as we can not proceed with the project and let it be working at this stage do you know why? Exactly, it is not safe because the control has not been programmed for the other way so the results would be sad as shown in figure 7.

The project second part

As we mentioned earlier, the project has been achieved by dividing it into two parts. In the first part that we have just demonstrated above including the ladder logic program and testing using our simulator. That very part, part one can control one way traffic but we have two running traffic lights that should be considered. From here we are going to show the second part of the project. Let us start with the requirements.

Part two the requirements

Table 2 below asks you guys to control both traffic ways to have the red light on one side for a 12 seconds period time in which you need to allow the green light of the other way to light for 8 seconds and then the Amber light will be permitted for the next 4 seconds. The same logic will be applied on the reverse side. On another word, side number one is red with green and amper of side number two. Also, red of side number two with green and amper of side number one. Let us see the ladder logic and description of the implemented logic in the following section.

Red = O:2/00

Green = O:2/02

Amber = O:2/01

Green = O:2/06

Amber = O:2/05

Red = O:2/04

8 Sec.

4 Sec.

8 Sec.

4 Sec.

Logic of the second part

For the length of the program” We have divided it into two pieces. The first one is shown in the figure 8. You can see guys, it is similar to utilize the timers and compare instructions to accomplish the project. Like part one but adding amendments to combine the second part requirements. in the third rung you notice my friends we have added just restriction to not letting the green and amber light of one side while the green or amber does in the other side and vise versa. So what we are doing in the first four rungs is to handle one way traffic signal with restricting the other side when it is needed. Now let us move to the second part of code.

Figure 9 demonstrates the control of the other side by adding the logic for the green of the other side as in rung 5 considering the restriction of the green and amber of the side one at that time. Then in rung 7, the control for the amber light of side 2 considers inhibiting the amber and green of the side one for avoiding the crash to happen. And at last the red light is energized for 12 seconds in which the green and amber of the other side are not prohibited. Now time to test our logic has come so let us go testing that program.

Testing the completed project

Here you can see friends the test of the completed project in figure 10. Notice that one side has the green light on and the other side shows the red is lighted. As a result, the side with green light on allows the vehicles to pass while the side with red sign lighted in bit cars from passing.

More testing to check the opposite scenario for checking the cross traffic logic. Figure 11 shows the other side amber sign is on while the red of the opposite side is on. Therefore, the cars are allowed with the side that has the amber light on. On the other hand, the side that has the red light is one prevent cars from passing.

My friends, I really appreciate you following up to that very point and hoping you have got to learn and enjoy practicing one of the most important projects that you might see in everywhere you go in your daily life. Please know one thing which is very important that, the code we have implemented just right here is not the only way to solve such project. There are dozens of way to code such a project so please try your way without hesitation and keep trying to increase your knowledge and boost professionally in ladder logic programming.  Thanks again guys and let us meet in another tutorial and project of the real life problem to learn and enjoy practicing ladder logic programming together.

Engineering Your Way to a Successful Project: Writing Tips and Tricks

Engineering projects are a crucial part of a student's engineering degree. Writing a project report is an essential part of any engineering project. The final step provides a summary of the project and its results. A good project report can help students get better grades and advance their career prospects. In this article, we will discuss the importance of engineering project writing and the steps involved in writing a successful project report.

What is Engineering Project Writing? 

Engineering project writing is a form of academic writing used to document an engineering project's progress. This type of report usually includes findings, conclusions, and recommendations. It should provide a clear and concise overview of the project and its impact on society. The report should be written in an organized and professional manner.

Why is Engineering Project Writing Important? 

Engineering project writing is important because it plays an essential role in the success of an engineering project. It provides detailed documentation of the project, its findings, and its results. This helps project managers and stakeholders to evaluate the success of the project. It also helps to demonstrate to potential employers and clients the skills and knowledge of the engineering team. 

https://codete.com/ provides comprehensive IT services and solutions that help companies innovate and increase their competitive advantage.

Steps in Writing an Engineering Project Report 

Writing an engineering project report can seem like a daunting task. However, following a few simple steps can make it easier and more effective. 

1. Gather the Necessary Information: Before you start writing your project report, it is important to gather all the necessary information. This includes details about the project, its goals, the team, its progress, and the final results. 

2. Outline the Report: Once you have all the necessary information, it is time to create an outline for the report. This will help you organize your thoughts and ensure that your report is structured and coherent. 

3. Write the Introduction: The introduction should provide a brief overview of the project and its purpose. It should include an explanation of the project's objectives, the team's involvement, and the results achieved. 

4. Write the Body: The body of the report should provide a detailed description of the project and its results. It should include information about the team, the methods used, the results achieved, and the conclusions. 

5. Write the Conclusion: The conclusion should provide a summary of the project and its results. It should also include recommendations for future action. 

6. Proofread and Edit: Once you have written the report, it is important to proofread and edit it. This will help ensure that the report is error-free and that it communicates the project's results effectively. 

Conclusion

Writing an engineering project report is essential to any engineering project. The final step provides a summary of the project and its results. A good project report can help students get better grades and advance their career prospects. By following the steps outlined above, you can create a successful engineering project report that will help you demonstrate your skills and knowledge. Encouraging students to use their engineering project writings to showcase their technical prowess is also a good idea. It will also help in the post-graduation job search. 

In the end, it is important to remember that engineering project reports should be clear, concise, and organized. With the right approach, you can create a report that will help you stand out from the crowd and advance your career prospects.

Set Up a Network Printer with Raspberry Pi 4

Thank you for being here for today's tutorial of our in-depth Raspberry Pi programming tutorial. The previous tutorial demonstrated the proper wiring of the photoresistor sensor to the GPIO pins. Finally, we learned how it might be included in a Python script for data collection and analysis needs. We also looked at the functions of each component in the circuit. However, I'll walk you through installing a Pi 4 Print Server in this guide. While installing the program is straightforward, setting it up so that a Windows network can locate the print server requires a little more effort. Rather than spending hundreds of dollars upgrading to a laser printer, you may easily upgrade your current USB printer to laser quality by installing a print server.

Because of this software, you no longer have to have the printer physically linked to a single computer, and you may place it wherever you choose and share it with as many computers as you like. In addition, it's a fantastic method of printer sharing that eliminates the need for a pricey tower computer to be on and active all the time. CUPS is the program we'll be using to make this happen. Common Unix Printing System, or CUPS, is the foundation of Linux printing applications. But, the program facilitates communication between your computer and printer. It would help if you visited available printing to verify that the CUPS printing software supports your printer model.

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

Components

  • Raspberry Pi 4

  • Wi-Fi

  • USB Printer

Pi Print Server Software Installation

Since the Raspberry Pi print server is included in the Debian Jessie distribution, setting it up is a breeze. In this lesson, I'll be using Raspbian, so if you're unfamiliar with it and would like to learn how to set it up, check out my guide on how to do so.

We must ensure the Raspberry Pi is up-to-date with the most recent software to get started. Just type in the appropriate instructions into the terminal to accomplish this.

sudo apt update

sudo apt upgrade

We can begin setting up the print software after the Pi 4 has been upgraded. Here, we will be setting up CUPS.

CUPS

CUPS, short for Common Unix Printing System, is a printing system designed for computers running UNIX-like operating systems. The software transforms the host computer into a print server. A CUPS-enabled server may receive print jobs from various client devices, sort them, and send them to the correct printer for output. Conveniently, this program can handle the administration of your printers, whether they're linked locally through USB or remotely via the network. Using the terminal, enter the following command to install the software. Considering HP has CUPS that support its open source project, HP printers, in particular. Even if your specific printer model isn't listed as being directly supported by CUPS, you may still be able to find a compatible generic driver online that will get the job done. These links will take you to a list of CUPS-compatible printers.

sudo apt install cups

We still have some work to do after CUPS's installation is complete. The first step is to include the pi user in the lpadmin set of users. With this group, the pi user can manage CUPS settings without logging in as the superuser.

sudo usermod -a -G lpadmin pi

To make sure it functions properly on your home network, there is one more thing we must do to CUPS: make it available to every computer on your network. At this time, Cups is configured to refuse connections from addresses outside the local network. By entering the following two commands, we can make it listen to all incoming connections:

sudo cupsctl --remote-any

sudo systemctl restart cups

After this, any machine on the network can send prints to the Pi 4 print server. The following command can be used if you need to know your Raspberry Pi's local IP Address.

hostname -I

If you know your Raspberry Pi's IP address, you can use it to access the website at the address below. Be sure to replace "192.168.1.105" with your IP address.

We'll examine how to configure SAMBA so that Windows can find the Raspberry Pi print server. Furthermore, we will demonstrate how to install a printer using the CUPS interface.

Pi 4 Print Server SAMBA Configuration

A proper SAMBA configuration is required if you use your print server in conjunction with Windows. To get SAMBA up and running with the CUPS print drivers, we'll have to install it and tweak its settings.

First, check that SAMBA is installed; to do so, we can use the terminal's built-in install command. Just by typing this into the terminal, we can accomplish our goal.

sudo apt install samba

Now that SAMBA is installed on our Pi 4, we can access its config file and make some changes. The following command will cause the file to be opened in the nano text editor:

Sudo nano /etc/samba/smb.conf

Once the file has been opened, it must be scrolled to the end. To do this quickly, press the Control key plus the V key. The following lines should be added or edited once you reach the very end of the file. The file already contained the "[printers]" and "[print$]" sections; all I had to do was update the values to reflect the following.

[printers]

comment = All Printers

browseable = no

path = /var/spool/samba

printable = yes

guest ok = yes

read only = yes

create mask = 0700

[print$]

comment = Printer Drivers

path = /var/lib/samba/printers

browseable = yes

read only = no

guest ok = no

To save the file, hit CTRL+X, Y, and ENTER. SAMBA needs to be restarted to pick up the updated settings. The following command, when entered into the terminal, will restart SAMBA.

sudo systemctl restart smbd

Installation of a Printer in CUPS

It's easy to set up a printer using CUPS, but first, we need to open the program's graphical user interface. For the IP address of your Raspberry Pi, enter "hostname" into the terminal.

hostname -I

To access the IP configuration page for your Raspberry Pi, type the following into your web browser and enter the IP address you just jotted down. Replace "192.168.1.105" with your IP address when entering this address.

The following homepage is what you should see. Here, we'll go to "Administration" on the main menu.

You'll be directed to Cups's control panel when you click here. On this page, select the "Add Printer" option.

The "Add Printer" screen has been brought up, allowing us to choose the printer we wish to configure Cups with. That printer is a Canon MG2500 series machine. When you've made your print choices, click the "Continue" button.

Ensure the printer is turned on and plugged into the Raspberry Pi through a USB connection if it does not appear here. If your Raspberry Pi still doesn't show up, try restarting it while ensuring your printer is on and connected.

Choose your printer's model from the dropdown menu here. CUPS will automatically identify the printer model and install the appropriate driver when possible. However, this may only sometimes work, so you may need to sift through the list to locate the proper driver manually. Once you've double-checked everything and are pleased, click the "Add Printer" button.

After completing the steps on this screen, the printer will have been added successfully. Here, you can give it a name and a summary that mean whatever you choose. If you have more than one printer in your residence, specifying its location will make your life easier. If you want other computers to be able to use the printer, you must also turn on "Share This Printer." If everything looks good, hit the "Continue" button.

After finishing the printer setup process, you will see the screen shown in the image below. Several of the printer's more nuanced settings are accessible through this panel—the number of pages printed, the quality of the printout, and so forth.

Having finished setting up our Raspberry Pi print server, we will now discuss how to add it to Windows. Having SAMBA set up earlier in the course should make this step less painless.

Setting up a Raspberry Pi as a Print Server in Windows

Installing a CUPS printer on Windows requires selecting the driver that will allow Windows to communicate with and comprehend the printer. Launching "My Computer" or "This PC" and then clicking "network" in the left-hand navigation pane is a quick method to get to Windows' network page, where you can get started. When you get there, you should see a screen like the one below, where your Raspberry Pi's hostname (in my instance, RASPBERRYPI) is displayed. If you double-click your Raspberry Pi's share, it may prompt you to log in. If entering anything other than "enter" fails to log you in, try "pi."

The printers used with your Pi 4 print server should now be displayed on the screen. Select the printer you wish to use by double-clicking on it.

You'll see the cautionary message below if you try to double-click this. Select "OK" to proceed with the tutorial.

Select your printer brand on the left, and then select your printer model from the available drivers for that brand on the right. If your printer isn't listed here, you can identify its model online and install the necessary drivers. For me, that meant tracking down the Canon MG2500 series. When you've decided which printer to use, you may move forward by clicking the "Ok" button.

The procedure will now initiate a link to your printer. Select "Printer" > "Set as Default Printer" to make this the system's default printer.

Now that the printer has been installed on your computer, you can use it with any application that supports printing. By printing a test page, you may verify that the printer is configured correctly.

If you're having trouble printing a file, check to see if you've picked the correct printer driver in CUPS and Windows. Ensure the printer is turned on as well; the Canon MG2500 series, for example, do not immediately restart when a print job is delivered. Adding Apple AirPrint capability to your Pi 4 print server is a great way to expand its capabilities.

The Raspberry Pi AirPrint Server Setup

Apple's AirPrint printing technology eliminates the requirement for users of Apple products to acquire and install the separate printing software. By adding AirPrint functionality, you may quickly and effortlessly print from your iOS smartphone to any nearby printer. You can run an AirPrint server from your Raspberry Pi, and Cups is the software that will power it. It will take care of talking to your printer on your Raspberry Pi's behalf.

The "Avahi daemon" must be set up before AirPrint may be used on your computer. The following command will install the package onto your Raspberry Pi.

sudo apt install avahi-daemon

Using this package, you can make Apple's Zeroconf design a reality. Bonjour has become widely used to refer to this type of network architecture. Using Bonjour, AirPrint can link disparate gadgets like an iPhone and a Raspberry Pi. Once you've selected the files you'd like to print, the Bonjour daemon will forward them to the designated printer.

Let's restart the machine to see whether the AirPrint server has worked appropriately, and everything is ready. Execute this command to force the Raspberry Pi to restart.

sudo reboot

After rebooting your Raspberry Pi, you can check to see if anything went wrong. This should get you to the point where you can print from any AirPrint-enabled device.

Display printer and print

Conclusion

Have you succeeded in following this guide and setting up a Pi 4 network print server? If you've followed these steps carefully, your Raspberry Pi should be ready to function as a network AirPrint server. We were able to accomplish this by putting the Avahi daemon in place. This daemon implements the bonjour protocol used by AirPrint. Feel free to leave a message below if you have any thoughts, suggestions, or problems you'd want to discuss. The following tutorial will review the steps for monitoring a patient's heart rate with a Raspberry Pi 4.

Interfacing a Light Sensor (LDR) with Raspberry Pi 4

Hello friends, I hope you all are doing great. Today, we are going to start Section-III of our Raspberry Pi 4 Programming Course. In this section, we will interface different Embedded Sensors with Raspberry Pi 4. Today's our first lecture in Section-III, so I am going to interface a simple LDR sensor with RPi4.

So, let's get started:

Components Required:

The following items are required to finish this Raspberry Pi photoresistor module guide. You don't need a breadboard to accomplish this, but having one would be helpful.

  • Raspberry pi 4
  • Breadboard
  • Photoresistor LDR
  • Jumper wires
  • 1uF Capacitor

What is a photoresist?

It is a common practice to employ photoresistors to determine the presence or absence of visible light or to quantify the amount of light hitting a particular surface. Their resistance is exceptionally high in the dark, reaching up to 1M ohm, but when subjected to light, the LDR sensor's resistance reduces rapidly, often to only a few ohms. Light-dependent resistors (LDRs) are nonlinear devices whose sensitivity shifts depending on the incident wavelength of light. To protect their ecosystems, some nations have outlawed the use of lead and cadmium in LDRs.

By analyzing the electromagnetic radiation in the "Infrared", "Visible" and "Ultraviolet" regions of the electromagnetic spectrum, Light Sensors can produce an output signal indicative of the brightness of the surrounding light. A passive device called a light sensor transforms this "light energy," which can come from either the visible or infrared regions of the spectrum, into an electrical signal. Because they convert the energy of light (photons) into a usable form of electricity, light sensors are also referred to as photoelectric devices or photo sensors (electrons).

There are two primary types of photoelectric devices: those that produce electricity when exposed to light (photovoltaics, photoemissive, etc.) and those that modify their electrical properties when exposed to light (photoresistors, photoconductors, etc.).

Light Dependent Resistor(LDR)

The light-dependent resistor (LDR) sensor is used to detect the intensity of light in the surroundings. The LDR is a device constructed from a sensitive semiconductor material i.e. cadmium sulfide, which undergoes a dramatic shift in electrical resistance when exposed to light, going from several 1000 Ohms in the dark to just a few Ohms, when illuminated.

Most photoresistive light sensors employ cadmium sulfide(CdS). However, other semiconductor substrate materials like lead sulfide (PbS), lead selenide (PbSe), and indium antimony (InSb) can detect light intensity as well. Since cadmium sulfide has a spectral response curve similar to the human eye's and can be modulated with a handheld torch, it is utilized to create photoconductive cells. The peak wavelength at which it is most sensitive is typically between 560-600nm (nanometers), making it part of the visible spectrum.

The Light Dependent Resistor Cell

The ORP12 cadmium sulfide photoconductive cell is the most widely used photoresistive light sensor. This photosensitive resistor's spectral response is concentrated around 610 nm in the yellow-to-orange part of the spectrum. When the cell is in the dark, its resistance is extremely high at around 10M's, but it drops to about 100's when illuminated (lit resistance). As the resistive path zigzags across the ceramic substrate, the dark resistance increases and the dark current drops. Because of its low price and wide range of possible applications, the CdS photocell is frequently used in auto-dimming systems, light- and dark-sensing controls for streetlights, and photographic exposure meters.

Below is an illustration of how a light-dependent resistor can be used as a light-sensitive switch.

This simple circuit for detecting light consists of a relay activated by exposure to sunlight. The photoresistor LDR and the resistor R1 make up a potential divider circuit. In the absence of light, the LDR's resistance rises into the Megaohm (M) range, and as a result, the transistor TR1 receives zero base bias, turning the relay off. The LDR's resistance drops in response to more light, elevating the base bias voltage at V1. When the base bias voltage of transistor TR1 reaches a certain threshold, as defined by the resistance R1 in a potential divider network, the transistor turns "ON," activating the relay, which controls some external circuitry. With a return to darkness, the LDR's resistance rises, reducing the transistor's base voltage and turning "OFF" the transistor and relay at a predetermined level of illumination established by the potentiometer circuit.

Changing the relay's "ON" or "OFF" point to a custom brightness is as simple as swapping out the fixed resistor R1 for a potentiometer VR1. The switching end of a simple circuit like the one depicted above may need to be more consistent owing to fluctuations in temperature or supply voltage. Using the LDR in a "Wheatstone Bridge" configuration and substituting an Operational Amplifier for the transistor makes it simple to construct a light-activated circuit with increased sensitivity.

Circuit Diagram of LDR with RPi4

To build the circuit of the LDR sensor with RPi4, follow these instructions. You can also refer to the below circuit diagram:

  1. To begin, attach Pin1 of RPi4 to the breadboard's positive rail.
  2. Then, attach pin 6 of RPi4 to the breadboard's ground rail.
  3. Next, place the LDR sensor on the board with one end connected to the power supply's positive rail.
  4. Connect the opposite end of the LDR sensor to the Pin4 of RPi4 using a jumper wire.

Now is the time to start writing Python code for LDR:

Python Code for LDR Sensor with Raspberry Pi 4

This project's code is simple and will let us know whether it's bright outside, partly cloudy, or overcast. The lack of analog inputs on the Pi is the primary limitation of this device. So far, we have only worked on the digital modules, but here we need an analog pin to get a reliable reading of the input resistance variation. So, we'll count how long the capacitor takes to recharge and then set the pin high. This is a quick but unreliable way to gauge the ambient light level.

Here I will quickly go over the code for the LDR sensor with Raspberry Pi. As a first step toward establishing a connection with the GPIO pins, we import the necessary GPIO package. The time package is also imported, allowing us to schedule script inactivity.

#!/user/local/bin/python

import RPi.GPIO as GPIO

import time

Next, we change the GPIO modes to GPIO.BOARD so that the pins used in the script match the hardware. One variable only needs to be set because there is just one input/output pin. If you use a specific GPIO pin, assign its number to this variable.

GPIO.setmode(GPIO.BOARD)

#define the pin that goes to the circuit

pin_to_circuit = 7

The following function we'll look at is RC time, and it takes a single input: the circuit's PIN. In this code, we set the value of a variable named count to zero, and then, when the pin is set to high, we return that number. Our pin is then configured as an output before being brought low. Then we let the program rest for ten milliseconds. When this is done, the pin is converted to an input, and a while loop is started. In this loop, the capacitor is charged until it is around 3/4 full, at which point the pin swings high. Once the pin is set to high, we send the count back to the primary method. This number can be used to toggle an LED, trigger an action, or be stored to compile data on brightness fluctuations.

def rc_time (pin_to_circuit):

    count = 0

    #Output on the pin for 

    GPIO.setup(pin_to_circuit, GPIO.OUT)

    GPIO.output(pin_to_circuit, GPIO.LOW)

    time.sleep(0.1)

    #Change the pin back to the input

    GPIO.setup(pin_to_circuit, GPIO.IN)

    #Count until the pin goes high

    while (GPIO.input(pin_to_circuit) == GPIO.LOW):

        count += 1

    return count

#Catch when the script is interrupted, clean it up correctly

Try:

    # Main loop

    while True:

        print(rc_time(pin_to_circuit))

except KeyboardInterrupt:

    pass

finally:

    GPIO.cleanup()

Executing the Program on Your Pi 4

Even though this is a trivial procedure, I'll run through it fast so you can get it up and work on your Pi without any hiccups. I am employing Raspbian, the operating system used in all the guides here. Read my Raspbian installation instructions if you need assistance. In most circumstances, all the necessary software will already be installed. Using git clone, the source code can be downloaded. Here's a command that will carry out your request.

git clone https://github.com/pimylifeup/Light_Sensor/

cd ./Light_Sensor

The code can also be copied and pasted, but only into a Python script. When working with Python code, my preferred text editor is nano.

sudo nano light_sensor.py

To save your changes and leave the file, press CTRL+X then Y. Finally, the following command will execute the code.

sudo python light_sensor.py

Hopefully, you've fixed the script and are now getting readings that accurately reflect the light levels on the sensor. Be bold about posting a comment if you need help.

Output

LDR Sensor Applications

A light sensor can be implemented in a variety of circuitry contexts. Some that sprang to mind when I was penning this guide are as follows:

An LDR can detect the onset of daylight, allowing for the activation of an alarm to rouse you from sleep. With a reliable program and sensor, you may set the alarm to increase in volume as daylight fades gradually. One way to keep tabs on your garden is to use a light sensor to measure how much sun each section of your garden is getting. This could be helpful knowledge if you're planting anything that needs a lot of sun or vice versa. Using the Room Monitor, you can ensure the lights in a particular room are switched off whenever no one is there. This might be set up to send you an alert if the light is found in an unexpected place.

Conclusion

This fantastic sensor has a wide variety of applications. However, if you need something more precise than a photocell, consider the Adafruit dynamic range sensor. You had no trouble installing this light sensor on your Raspberry Pi. Please comment below if you have any issues or suggestions or think I need to include something. In the next section, we'll see how to interface a Soil Moisture Sensor with Raspberry Pi 4. Till then, take care. Have fun!!!

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