Interfacing of DHT11 with Raspberry Pi Pico

Hello readers, I hope you all are enjoying our Raspberry Pi Pico programming series. In our previous tutorials, we learned how to access Raspberry Pi Pico’s GPIO pins for both input as well as output operations. For demonstration, we used LED as an output component and a push button as an input component.

Now let’s learn how to interface sensor modules with the Raspberry Pi Pico module. So, in this tutorial, we will learn how to interface the DHT11 sensor with the Raspberry Pi Pico module and fetch the observed data (from its surrounding) using the MicroPython programming language.

Before writing the code for interfacing and fetching the data from the respective sensor, let’s first have a look at the working operation, features and properties of the DHT sensor.

Fig. 1 Raspberry Pi Pico and DHT11 modules

DHT11 Sensor

 

The DHT11 sensor (also known as a temperature and humidity sensor) is a sensor module that measures humidity and temperature in its immediate environment. The ambient temperature and humidity of a given area are monitored by this sensor module. The sensor is made up of an NTC (negative temperature co-efficient) temperature sensor and a resistive type humidity sensor. An 8-bit microcontroller is also built into the sensor module. The microcontroller converts analogue to digital and outputs a digital signal through the single wire protocol.

The following are some of the DHT11 sensor's technical specifications:

Table:1 DHT11 technical specifications

DHT11 sensors can also be used to create a wired sensor system with up to 20 meters of cable.

A DHT sensor is mostly used in weather monitoring systems and for research purposes. Although we have satellites to provide the status of weather conditions but, the data provided by satellites represent a larger area. In the case of research applications, the satellite provided data is not sufficient so in such applications, we need to use sensor modules like DHT.

DHT11 Vs DHT22

To measure temperature and humidity, two DHT modules (DHT11 and DHT22) are available in the market. Both of the DHT11 and DHt22 modules, serves the same purpose, but they have different specifications. The DHT22 sensor, for example, has a wider range of humidity and temperature sensitivity. The temperature sensitivity of DHT22 ranges from -40 to 80°C with +-0.5°C tolerance and on the other hand, the temperature sensitivity of the DHT11 sensor ranges from 0 to 50°C with +-2°C tolerance.

Similarly, the humidity sensitivity of the DHT22 sensor ranges from 0 to100% with +-2% tolerance and for DHT11 the humidity sensitivity rages between 20 to 90% with +-5% tolerance. Similarly other properties like resolution, sampling time etc are better in the DHT22 sensor module than in DHT11. But the only disadvantage or drawback of the DHT22 sensor module is its cost. The DHT22 is costlier than DHT11 sensor module. So you can use any of the modules as per your requirements and resources.

Software and Hardware components required

The software and hardware components required to interface the DHT sensor with the Raspberry Pi Pico board are:

  • Raspberry Pi Pico development board
  • DHT11 sensor
  • A resistor (10K)
  • Connecting wires
  • Breadboard
  • Data cable
  • Thonny IDE

Fig. Required Components (hardware)

DHT11 Pin-out

DHT11 is a three pin module and the pins include ‘+Ve’ for 3.3V, ‘-Ve’ for ground and the third one is ‘OUT’ for data output.

Fig. 3 DHT11 Pin-out

Interfacing DHT11 with Raspberry Pi Pico module

The connection for interfacing the DHT11 and Pico modules are shown in table 1. There are basically three pins in DHT11 sensor as discussed earlier. Two pins are to power up the DHT11 module i.e., VCC and ground and these two pins are connected to the 3.3V and GND pins of the Pico board. The third pin i.e., ‘OUT’ is used to provide data input to the Raspberry Pi Pico board. The data (‘OUT’) pin can be connected to any of the GPIO pins of the pico board. So here we are using GPIO_0 pin for data input.

Table 2 Interfacing DHT11 with Raspberry Pi Pico

Fig. 4 Interfacing DHT11 with Pico board circuit

Programming

The development environment we are using is Thonny IDE, to program the Raspberry Pi Pico board for accessing the dual core feature with MicroPython programming language.

So, before writing the MicroPython program user need to install the respective development environment to compile and upload the MicroPython program into the Pico board.

We already published a tutorial on how to install and access Thonny IDE for Raspberry Pi Pico programming using MicroPython programming language. Follow our previous tutorial, to install Thonny IDE for raspberry pi pico programming.

Let’s write the MicroPython program to interface the DHT sensor with the Raspberry Pi Pico module and fetch the temperature and humidity data observed with the DHT11 sensor.

  • The first task while writing the MicroPython code for the DHT11 interfacing is importing the necessary classes and modules. Firstly we are importing the Pin class from the machine The Pin class is used to access the Raspberry Pi Pico’s GPIO pins to interface the data pin of DHT11 sensor module.
  • Next we are importing the utime module to add delay when required.
  • The third module we are importing is the dht module which is responsible for reading the temperature and humidity data from the sensor module.

Fig. 5 importing necessary library files

  • Next we are declaring a ‘pin’ object. This object represents the GPIO pin number to which the data pin of DHT11 is to be connected and also the mode of the GPIO pin. Here we are using GPIO_0 of the Pico board and the pin is configured at imput.

Fig. 6 declaring the ‘pin’ object

  • We are using a while loop to continuously read and print the sensor reading (temperature and humidity).
  • The sampling rate of DHT11 sensor is 1 second. So before reading the data from DHT sensor a minimum delay of 1 second is required. Here we are adding a delay of 2 second.
  • The temperature observed using ‘dht_input.temperaure’ The respective data is store inside ‘temp’ variable and then printed using print() command.
  • Similarly, for humidity the data is observed using ‘dht_input.humidity’ The respective data is stored inside ‘humidity’ variable and printed using the print() command.

Fig. 7 Main loop

Main program (main.py)

# importing necessary library files

from machine import Pin

import utime

from dht import DHT11, InvalidChecksum

while True:

utime.sleep(2) # adding delay of 2 seconds

pin = Pin(0, Pin.OUT, Pin.PULL_DOWN) # declaring pin object

dht_input = DHT11(pin) # defing the sensor pin

temp = (dht_input.temperature) # reading temperature

humidity = (dht_input.humidity) # reading humidity

print("temp(°C): {}".format(dht_input.temperature))

print("humidity(%): {}".format(dht_input.humidity))

You can use the above code as it is. But before compiling the code make sure you have uploaded the dht.py library file to your system/Raspberry pi pico module.

To upload the dht.py file into your system/pico board, go to File >> New, as shown below:

Fig. 8 create a new program

  • Paste the below attached code into the new program and save the program to similar location where the main program is saved.

DHT library (dht.py)

import array

import micropython

import utime

from machine import Pin

from micropython import const

class InvalidChecksum(Exception):

pass

class InvalidPulseCount(Exception):

pass

MAX_UNCHANGED = const(100)

MIN_INTERVAL_US = const(200000)

HIGH_LEVEL = const(50)

EXPECTED_PULSES = const(84)

class DHT11:

_temperature: float

_humidity: float

def __init__(self, pin):

self._pin = pin

self._last_measure = utime.ticks_us()

self._temperature = -1

self._humidity = -1

def measure(self):

current_ticks = utime.ticks_us()

if utime.ticks_diff(current_ticks, self._last_measure) < MIN_INTERVAL_US and (

self._temperature > -1 or self._humidity > -1

):

# Less than a second since last read, which is too soon according

# to the datasheet

return

self._send_init_signal()

pulses = self._capture_pulses()

buffer = self._convert_pulses_to_buffer(pulses)

self._verify_checksum(buffer)

self._humidity = buffer[0] + buffer[1] / 10

self._temperature = buffer[2] + buffer[3] / 10

self._last_measure = utime.ticks_us()

@property

def humidity(self):

self.measure()

return self._humidity

@property

def temperature(self):

self.measure()

return self._temperature

def _send_init_signal(self):

self._pin.init(Pin.OUT, Pin.PULL_DOWN)

self._pin.value(1)

utime.sleep_ms(50)

self._pin.value(0)

utime.sleep_ms(18)

@micropython.native

def _capture_pulses(self):

pin = self._pin

pin.init(Pin.IN, Pin.PULL_UP)

val = 1

idx = 0

transitions = bytearray(EXPECTED_PULSES)

unchanged = 0

timestamp = utime.ticks_us()

while unchanged < MAX_UNCHANGED:

if val != pin.value():

if idx >= EXPECTED_PULSES:

raise InvalidPulseCount(

"Got more than {} pulses".format(EXPECTED_PULSES)

)

now = utime.ticks_us()

transitions[idx] = now - timestamp

timestamp = now

idx += 1

val = 1 - val

unchanged = 0

else:

unchanged += 1

pin.init(Pin.OUT, Pin.PULL_DOWN)

if idx != EXPECTED_PULSES:

raise InvalidPulseCount(

"Expected {} but got {} pulses".format(EXPECTED_PULSES, idx)

)

return transitions[4:]

def _convert_pulses_to_buffer(self, pulses):

"""Convert a list of 80 pulses into a 5 byte buffer

The resulting 5 bytes in the buffer will be:

0: Integral relative humidity data

1: Decimal relative humidity data

2: Integral temperature data

3: Decimal temperature data

4: Checksum

"""

# Convert the pulses to 40 bits

binary = 0

for idx in range(0, len(pulses), 2):

binary = binary << 1 | int(pulses[idx] > HIGH_LEVEL)

# Split into 5 bytes

buffer = array.array("B")

for shift in range(4, -1, -1):

buffer.append(binary >> shift * 8 & 0xFF)

return buffer

def _verify_checksum(self, buffer):

# Calculate checksum

checksum = 0

for buf in buffer[0:4]:

checksum += buf

if checksum & 0xFF != buffer[4]:

raise InvalidChecksum()

Once both the main.py and dht.py are saved successfully we are ready to run the program. Click on the Run icon to test the interfacing setup and check the respective results.

Results

To see the sensor reading (temperature and humidity) observed with DHT11 sensor and Pico module we can either interface some peripheral device like LCD display or OLEDs. But for now we are just printing the sensor reading on Shell. We will create another tutorial for interfacing a peripheral display device with Raspberry Pi Pico module.

The sensor readings observed with DHT11 sensor are printed on the Shell. Image of the observed temperature and humidity values is attached below:

Fig. 9 DHT11 output

Conclusion

In this tutorial, we learned how to interface a peripheral sensor with the Raspberry Pi Pico module to observe temperature and humidity and display the data on Shell. This concludes the tutorial. I hope you found this of some help and also hope to see you soon with a new tutorial on the Raspberry Pi Pico programming series.

Raspberry Pi Pico Dual Core Programming with MicroPython

Hello readers, I hope your all are doing great. We know that a Raspberry Pi Pico module comes with multiple inbuilt features for example onboard memory, processing units, GPIOs or General Purpose Input Outputs (used to control and receive inputs from various electronic peripherals) etc.

In our previous tutorials, we discussed how to access GPIO pins of the Raspberry Pi Pico module for both input as well as output operations.

In this tutorial, we are going to discuss another important feature of the Raspberry Pi Pico module (RP2040) which is Dual Core Processor. The Pico board features with 133MHz ARM Cortex-M0+, Dual Core Processor. This dual-core feature makes the Pico module capable of multiple thread execution or multithreading.

Now before writing the MicroPython program let’s first understand the concept of the dual-core processor in the Raspberry Pi Pico module.

Fig. 1 raspberry Pi Pico dual-core programming

Raspberry Pi Pico Dual Core

A core is the basic unit of any processor which is responsible for executing program instructions. A multi core processor comes with the features of executing multiple tasks at a time. Multithreading is the ability of a processing unit to provide multiple threads of execution simultaneously (operating system supported). In multithreading, threads share their resources with each other. So this dual-core processor feature results in increased processing speed.

Raspberry Pi Pico (RP2040) module is having two processing cores, Core0 and Core1. In the default mode of Raspberry Pi Pico program execution, Core_0 executes all the tasks and Core1 remains idle or on standby mode. Using both the cores of RP2040 provides us with two threads of execution and hence a more powerful project with better processing speed.

Both core0 and core1 execute their assigned tasks independent of each other while sharing all the resources like memory space and program code with each other. Sharing the memory location between two cores can create race conditions and hence can cause trouble when mutual memory accessing is not assured. On the other hand, sharing program code with each other (core0 and core1) may sound troublesome but practically it is not. The reason is fetching code is a read instruction that does not create a race condition.

Core0 and Core1 communication

Fig. 2 Core_0 and Core_1 communication

As we mentioned above, sharing memory space with two cores simultaneously can cause race conditions. So, to make the cores to communicate with each other the Raspberry Pi Pico module is featured with two individual ‘First In First Out’ (FIFO) structures. Each core can access only one FIFO structure so both core have their own FIFO structure to write codes which helps in avoiding race condition or writing to the same memory location simultaneously.

You can follow the given link for detailed study on Raspberry Pi Pico: https://www.theengineeringprojects.com/2022/04/getting-started-with-raspberry-pi-pico.html

Software and Hardware components required

  • Raspberry Pi Pico development board
  • Thonny IDE
  • Data cable
  • Connecting wires
  • Breadboard
  • LEDs

Programming

The development environment we are using is Thonny IDE, to program the Raspberry Pi Pico board for accessing the dual core feature with MicroPython programming language.

So, before writing the MicroPython program user need to install the respective development environment.

We already published a tutorial on how to install and access Thonny IDE for Raspberry Pi Pico programming using MicroPython programming language. You can find the details at the given link address: https://www.theengineeringprojects.com/2022/04/installing-thonny-ide-for-raspberry-pi-pico-programming.html

Now let’ write a MicroPython program with Thonny IDE to access raspberry Pi Pico’s both cores:

In this example code we using just a simple “print()” commands to print the messages from each core for testing purpose.

  • The first task while writing a code is importing necessary libraries. Here we are importing three libraries, “machine”, “utime” and “_thread”.
  • utime library provides the access to internal clock of raspberry Pi Pico module which is further used to add delay when required.
  • _thread library is responsible for implementing the threading function provided by “Raspberry Pi Pico” community.
  • As we are using a dual core processor and accessing both the cores simultaneously means we are using two threads (one thread from each core). This _thread module allows a user to work with multiple threads and also allow them to share global data space.
  • For more details on _thread module follow the given link: https://docs.python.org/3.5/library/_thread.html#module-_thread

Fig. 3 Importing necessary libraries

  • Semaphores or Simple locks are provided with “_thread” module which is responsible for synchronization between multiple threads. The allocate_lock() function provided with _thread module is responsible for returning a new lock object.
  • Here we are declaring a “spLock”

Fig. 4 declaring thread lock object

  • Next, we are creating a function where we are assigning the task to core_1.
  • The “spLock.acquire()” function “acquires the thread lock without any optional argument”. The reason for using the this “acquire()” function is to make sure that only one thread of execution is acquiring the lock at a time until the lock is released for other thread. Here we using the “print()” command as a task assigned or to be executed by core_1 along with a delay of 0.5sec or 500us.
  • Next, is the release() command, which is used to release the lock acquired earlier. So that other threads can execute their respective tasks.
  • The task assigned to core_1 will be executed continuously because it is written in “while loop”.

Fig. 5 Task for Core_1

  • The function core1_task() defined earlier which is containing the task assigned to core_1 will be passed as an argument inside start_new_thread() function. As per the official documentation from python.org, this function is responsible for “starting a new thread and returning its identifier”. The thread will execute the assigned function (as an argument). The tread will automatically exit when the function returns. We can even assign more than one argument in this “-thread.start_new_thread()” function.

Fig. 6 Core_1 thread

  • As we mentioned earlier, Raspberry Pi Pico uses core_0 as default a core for processing purpose. So here we do no need to use the _thread.start_new_thread() function to start a new thread for Core_0. Core_0 will automatically start a thread for code execution. But we still need to call the acquire(a lock) and then release functions, just to ensure only thread is acquiring the lock at a time. Here again we are using the print() command to print a message from core_0 like we did in case of Core_1.

Fig. 7 Task for default core (core_0)

Code

The MicroPython code with thonny IDE for Raspberry Pi Pico is written below:

import machine

import utime # access internal clock of raspberry Pi Pico

import _thread # to access threading function

spLock = _thread.allocate_lock() # creating semaphore

def core1_task():

while True:

spLock.acquire() # acquiring semaphore lock

print( "message from core_1")

utime.sleep(0.5) # 0.5 sec or 500us delay

spLock.release()

_thread.start_new_thread(core1_task, ())

while True:

spLock.acquire()

print( "message from Core_0 ")

utime.sleep( 0.5)

spLock.release()

  • Copy the above code and paste in your Thonny IDE window.
  • Save the code either on Raspberry Pi Pico or your computer and once it is successfully saved click on the ‘Run’ icon to run the code.
  • Now go to Shell section to check the result. If the Shell is not enabled then go to View >> Shell and check ‘Shell’.
  • Now in the shell section you should see the message printed from both the cores.

Fig. 8 Enabling Shell

Result

The result obtained from the above code is attached below. Where we can see the messages received or executed by both the cores as per the instructions provided in the micropython code.

Fig. 9 output printed on shell

Let’s take another example where we will interface some peripheral LEDs and will toggle those LEDs using different threads of execution or cores.

  • Most of the instructions are similar to the previous example with some additional ones. Here we are importing one more library ‘Pin’ (along with the previous ones) to access the GPIO pins of raspberry Pi Pico module.

Fig.10 importing necessary libraries

Fig. 11 declaring led objects

  • Next task is assigning the task for each core. Core_1 is assigned to make the led_1 (GPIO_14) to toggle along with printing the given message.

Fig. 12 Toggling LED with core_1

  • Core_0, which is the default one is assigned to make the led_0 (i.e., GPIO_15) toggle with a delay of 0.5sec. Rest of the programming instructions are similar to the previous example code so we are not explaining them again.

Fig. 13 toggling LED with core_0

Code

from machine import Pin

import utime # access internal clock of raspberry Pi Pico

import _thread # to access threading function

# declaring led object

led_0 = Pin( 14, Pin.OUT ) # led object for core_0

led_1 = Pin( 15, Pin.OUT ) # led object for core_1

spLock = _thread.allocate_lock() # creating semaphore lock

def core1_task():

while True:

spLock.acquire() # acquiring semaphore lock

print( " message from core_1" )

led_1.value( 1)

utime.sleep( 0.5) # 0.5 sec or 500us delay

led_1.value(0)

spLock.release()

_thread.start_new_thread( core1_task, () )

while True:

spLock.acquire()

print( "message from Core_0" )

led_0.value(1)

utime.sleep( 0.5)

led_0.value(0)

spLock.release()

Result

In the results attached below we can that two LEDs are attached with raspberry Pi Pico boar. Green (GPIO14) and Red (GPIO15) LEDs represent the output of Core_1 and Core_0 respectively.

Fig. 14 Core_1 output (GPIO 14)

Fig. 15 Core_0 Output (GPIO15)

Conclusion

In this tutorial, we learned how to access both the cores of the raspberry pi Pico module and to execute task or control peripherals with individual cores. We also learned the concept of threading and multithreading.

This concludes the tutorial. I hope you found this of some help and also hope to see you soon with a new tutorial on raspberry Pi Pico programming.

How to Use a Raspberry pi as a VPN Server

Welcome to the next tutorial of our Raspberry Pi programming course. Our previous tutorial taught us how to use a raspberry pi as a DNS server. We also looked at the benefit of this DNS server. This tutorial will teach us to set up Raspberry pi as a VPN server.

This is an excellent method for increasing your network security and getting access to your local area network from the world wide web, but setting up your VPN server might be a challenge. Pi VPN uses a guided install to turn your Raspberry into a low-cost, high-performance VPN server.

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

What is Pi VPN?

It is an OpenVPN server optimized for all Raspberry platforms above pi 2. It allows you to access your home network over the internet safely and securely. Smart devices and your network can be connected via a "bridge" created by connecting a Raspberry Pi to your router.

A virtual private network (VPN) is a secure option if you frequently use your router to forward traffic. Anyone can gain access to your network through any of the ports you forward. For maximum network security, use Pi VPN, which only exposes a single port and employs industry-standard encryption algorithms.

How can we choose a VPN service provider?

Selecting a virtual private network service is critical before you begin this project. It would be best to bear in mind cybersecurity, bandwidth, and delay when making this decision.

Ensure that your Virtual private network supplier doesn't record how you use their services. Nevertheless, speed and delay are critical here.

As a result, we've decided to go with IPVanish in this project. When it comes to network latency and network bandwidth, IPVanish is among the best.

Preparation for Pi VPN

The Raspberry Pi can get the best out of the device with a wired or wireless connection.

Use the Interfacing settings menu to turn on the secure shell service in RPi Settings. The configuration tool can be launched from the Pi menu or with the following command:

Activate the secure shell server and then restart your Pi

You can disconnect your display and switch off your desktop once your Pi hooks to your local network via a secure shell. It's simple to use a program like Putty or the terminal on your Mac to access your RPi.

Connect to the Raspberry Pi

You will not have to use a monitor to manage your Pi virtual private network server. A Raspberry Pi can be accessed from another device using SSH.

Use the ifconfig command to display your Raspberry IP address before unplugging it from the monitor.

If you configure your Raspberry Pi VPN server on Windows, you should use Putty.

Login to the RPi using the Internet protocol address noted earlier when Putty runs. Check to see if the secure shell is for the connection type. To save this connection to your profile, click the Save button.

You don't need a secure shell client if you're using a Macintosh or Linux computer to install Pi VPN. SSH is in your operating system's terminal, so you don't need to do anything extra.

A security key is saved on your Raspberry Pi the first time you access the raspberry pi. Accept the key and store it on your computer by pressing the Yes option on the screen.

Your password must be entered next. You'll be logged in as Raspberry Pi as long as you haven't changed the default password on your Raspberry

The prompt pi@hostname shows a successful login.

Update Raspbian for Pi VPN

Begin by obtaining a list of the most recent applications. Using the command: you can see if any installed programs are up to date.

Set a static IP address

When it comes to network services, you will have to locate your RPi, implying that you will set up a static Ip before you begin using the app. Also, modify your hostname at this point. When you get access, you'll notice a difference in the prompt. It's a simple way to distinguish between several Pis, but you can always change your hostname.

To establish a static Ip, you'll have to update the configuration file /etc/dhcpcd.conf. Before opening the file, know your router's Internet protocol address and Domain name system. This data is available using the ifconfig utility.

Take advantage of this command when you're ready to edit its config script:

To find an example of static IP configuration, look for the line with the label Sample static IP config inside the file. Simply remove the example comments and replace your Ip, routers, and gateway with your own to get started.

If you prefer a static IP address, remove the comment from it and replace it with the desired value.

Your custom values should be provided for static IP and DNS.

To alter your hostname, run the command below as superuser to open /etc/hostname in nano:

When finished, use Ctrl+X to close the editor. Then, press Yes to save the changes.

The /etc/hosts file must be edited in the same way. The file editing command is:

Change your hostname from 127.0.0.1 to whatever you've selected. Use the command below to force a reboot of your Raspberry Pi:

You should always change your connection's IP address after restarting your Raspberry Pi to reflect its new static address.

How can we figure out Raspbian’s firewall?

In Linux distributions, firewalls are embedded in kernels and will activate by default in Raspbian. The default setting for a new installation is to leave it unlocked.

There are no restrictions on inbound or outbound packets, and the firewall forwards any requests. Before securing the firewall, make sure it is entirely accessible.

Use iptables -L to see if your firewall protocols match. It's possible to return the firewall to its default settings using the following commands:

Choose an encryption

During configuring the Raspberry virtual private network, you will select the level of encryption. What you need to remember is the following:

  • Generally, 2048-bit encryption is the best for download and streaming. However, 4096-bit is ideal for emailing and browsing, giving better security.

Allowing 4096-bit is enticing for those who stream film or music; however, it will add a significant amount of overhead and slows down your connection significantly. For the most part, we use 2048-bit encryption, which is the industry standard.

Timing out during lengthy procedures

You'll inevitably stumble across a peculiarity in a secure shell. For more prolonged operations, if you are using SSH to communicate with the Raspberry, the connection is lost whenever the desktop hibernates. Any pi commands running stop working whenever a secure shell connection is lost; therefore, you must re-enter it.

A screen is an excellent tool for dealing with long SSH processes. One task might be the only focus of your screen sessions. Afterwards, you'll be able to join and disconnect at will and return to your session to see how it progresses.

Once Screen installs, you will need only a handful of commands to get the most out of it. Use apt to install screen utility as a starting point:

Once Screen installs, run it by typing the following command into your terminal window:

Even if nothing has changed, the commands you issue will continue to run even if you disconnect.

Whenever your Raspberry Pi connection stops, simply re-SSH in and type:

If only one secure shell session is open, you'll immediately get reconnected.

Installing Pi, the virtual private network

The Pi VPN works once you have your Raspberry working. It's the first step in a multi-part installation that will grant you access to Pi's virtual private network backend capability. Setting up an outgoing virtual private network tunnel connection for privacy will be done in the following steps.

Launch the installer

Configure the Pi VPN via a command-line utility called curl, which you download from the company's website. You don't even need a browser to use curl to download from the internet.

Pi VPN installs using the following command:

You can obtain the installation package and feed it into bash for execution using this command.

Instantly, the procedure of installation begins. It begins by scanning for any packages that need updating on your system. Your system should be the latest version

to proceed.

Launch the pi VPN installation after meeting a few pre-requisites.

The Pi VPN installer

To get the most out of your SSH session, you should use the Pi Virtual private network Installer. We can get started when the Screen changes colour to blue, and an installer notification appears.

Start by pressing Enter to begin the VPN setup procedure.

Static IP addresses are required, and in case you do not have any, you will get a notice. If you have not already done so, head back to the previous section and finish configuring a static IP address.

The Ip that Raspberry Virtual private network detects displays to you. Click the Yes if it is correct.

IP address conflicts display for your attention. Static IP addresses outside the dynamic host configuration protocol range are the safest method of avoiding conflicts with other devices on your network.

To continue, simply press the OK button.

Set the raspberry user, then click the OK to proceed with installing your preferred software.

If you want your Raspberry virtual private network server to get automatic security upgrades, you should select Yes when prompted. Because port forwarding makes your Pi vulnerable to the internet, Pi VPN must be updated.

Make sure you conduct frequent updates manually if you select "No."

After activating automatic updates, it's usual to see the console for some time. You can expect another installation attempt in the next few seconds.

You'll want to use the UDP protocol while setting up a Pi VPN for most circumstances. If you're going to use a VPN subscription service to establish a highly secure two-hop connection, stick with TCP instead of UDP.

The default port you're using for the virtual private network will come in handy later.

UDP uses port 1194 by default, whereas TCP uses port 443. Do not use port 443 when configuring the double-hop virtual private network because it will end up causing a conflict afterwards. Instead, we use TCP port 4430.

Set up an encryption

Select the encryption type you want at this point. Earlier, we explained why you might choose each option and why you should do so. If you're still undecided, refer back to what we discussed.

Using the space bar, choose the encryption you want to employ and press OK. Streaming video is only possible with 2048-bit encryption.

It may take some time to generate these keys. It will take significantly longer if you're encrypting at a high level. Wait for Pi VPN to produce your server keys.

Installing the final piece

The Raspberry Virtual private network setup procedure is nearly complete once the server key generates. After a few more stages, you'll be able to establish a connection.

If you do not have a domain Name system account, choose the public IP. In this case, we will need to input your hostname and domain name system account settings as usual if we are using a Dynamic domain name system.

You will need to select a domain name server provider for your virtual private network. Google is recommended to most people because it is free and straightforward. If you're concerned about DNS leakages, OpenDNS offers safe DNS solutions. If you plan to use Pi-hole to handle DNS requests, you may want to select Custom.

The installation will guide you through the process of adding additional users using the command line. Install a web app for managing users in the following phase. Additionally, pivpn add is an option.

Select Yes and restart your Raspberry Pi.

Setup of the Pi Virtual private network GUI

There is a Pi Virtual private network Graphical interface for Pi VPN. Using it simplifies the process of adding new devices and users.

When you add a new user to the VPN, a *.ovpn profile generates. In addition to creating a user account, you may efficiently utilize the Pi Virtual private network GUI to download the profiles.

If you don't want to utilize the Pi Virtual private network GUI, you can use the following to add or delete users.

Preparing to install the GUI for Pi VPN

Adding a repository is necessary if you want the Pi VPN GUI's required software to be easily accessible. Let me show you how.

Edit apt's source list with nano. The directive is:

Add the lines below to the sources. Make a list of everything you can find:

This will inform apt that Raspberry can install packages. Debian stretch repositories do not currently contain some of the required third-party software Pi Virtual private network GUI uses.

It's not good to include a link to a previous build in the sources.list script, even though we currently need it. Once additional software installs, it may interfere with it. Once these software packages install, you can delete the line in the sources.list you just added.

Next, save the changes and exit the Nano application. Then update with the command below:

Once the check is complete, use the following command to install any new or updated packages:

All you have to do now is tell apt about the new repository. The Pi VPN Graphical interface pre-requisites can now install using the command:

When prompted, select "YES" and allow the setup to begin. Before using the Pi Virtual private network GUI, you must change some config files.

Make sure all of your pre-requisite software install before running the apt update.

Updating the web configuration

The Pi Virtual private network GUI relies on an apache server to function effectively as a web application. However, we need to make a few adjustments before the Pi Virtual private network GUI start operating.

To begin, modify the user’s account under which apache executes. It runs as an unsupported account by default; therefore, we need to change it to the user pi. Use the following command to make changes to the Apache configuration file:

Find the line with $(APACHE RUN USER)

To exit and save, use Ctrl+X.

You'll also want to give yourself complete control over the /var directory, where Apache stores all of its web pages. Use the following command to grant pi complete control over the webroot directory:

Run the following command to move to the /var/www/HTML folder:

The raspberry pi should install the Pi Virtual private network Interface from that location.

Obtaining and installing the GUI for Pi VPN

After troubleshooting, downloading and installing the raspberry virtual private network graphical user interface is a breeze. You only need to use git to check out the project. You've already installed the git software if you've been following along.

Then run the following command from the HTML folder.

The command below will utilize git to copy the Pi Virtual private network GUI project folder into the directory of your apache server so that it is accessible as a web page. With a quick check-in of your browser, you can verify that the installation went smoothly.

Connect to Pi virtual private network GUI

You can now launch the Pi Virtual private network GUI from your internet browser and manage Pi Virtual private network users.

Use the Internet address that matches your setup and launch the Pi Virtual private network GUI from your internet browser.

Once a login screen appears, you've successfully connected to the network. For the time being, simply save a link to the Pi Virtual private network GUI for quick access. Setting up an outgoing VPN connection is the next step in protecting your online activity. If you don't want to utilize IPVanish, you may set up your router and add users without signing up for anything.

Establish outbound virtual private network connection

In the absence of an outbound Virtual private network, all traffic from all connected devices will use the public IP address of the local network to reach the worldwide web. The websites think that you are in the home network whenever you are connected. For example, you may wish to watch Netflix while away from home.

We recommend creating a "double-hop" connection with a VPN service outside the Pi virtual private network for the best results.

VPN connections with two hops allow for complete encryption whenever you access a site using HTTPS. Since the outgoing virtual private network server never notices the request source, the additional security offered by using two tunnels goes far beyond standard Virtual private network solutions.

If your Vpn service provider retains logs, they will not identify the devices from which each specific request was made. This additional layer of anonymity further obscures anything you do online.

Do not bother with this step if all you need is remote access to your local network via Pi's virtual private network. In contrast, if you're looking for safe and anonymous internet access for your mobile device, you can use an outgoing virtual private network connection and Raspberry virtual private network.

Outbound VPN with IPVanish

Due to its low latency, IPVanish is an excellent choice for establishing a double-hop virtual private network connection, requiring two separate virtual private network servers. Any OpenVPN profile-publishing VPN service will follow the same procedure.

Your VPN service's digital certificate and an autologin profile can be obtained below.

SSH onto your Raspberry Pi VPN server, then use wget to obtain the resources you need from the internet. Take a look at your Pi Virtual private network server and ensure it is online before using these instructions to obtain the data you require:

If you want to access the IPVanish server, you'll need to alter the uniform resource locator in the second field.

Make sure you rename the *.ovpn to use the OpenVPN service when connecting to IPVanish. Only profiles ending in *.conf can be connected to the network. Change the name of the file with the command below to outgoing.conf:

Establish the IPVanish connection

You can easily track two concurrent virtual private connections by renaming each interface.

The connection names will not change to or from between the two interfaces when renaming interfaces. To effectively configure your firewall, you must know the device's name.

If you go into the connection settings for each interface, you can modify the name. There is a *.config file for each OpenVPN connection linked with it. By altering the first few lines of each file, you can rename the network's graphical user interface.

To begin, run the command below to edit the Pi Virtual private network settings:

You should change the first line to:

Add a new line to the following:

Save your modifications by pressing Ctrl+X, then Y. /dev/tun-incoming will be created the next time the Pi Virtual private network is online.

Also, edit the OpenVPN outgoing configuration file.

Modify the first statement and add another at the start of the configuration file like before. In this case, the text should be as follows:

In addition, the outbound Virtual private network will need to be updated as well. Enter your name and password so that the Virtual private network can immediately connect to the server's cert you obtained in the previous stage.

To use the IPVanish server SSL certificate, make the necessary changes to the outgoing.conf file. Replace the word ca with:

Please use the following command to direct IPVanish to the password file we will create shortly: auth-user-pass

In addition, you must instruct your outbound virtual private network connection not to relay Local traffic. Your outgoing.conf file must have the following line added to it to allow access via Pi virtual private network to your home network:

Password files are now generated for use with IPVanish by OpenVPN.

Click Ctrl + X followed by the key to save the changes after entering your password and email address. You should encrypt the file because it holds your login details. With chmod, you can prevent anyone from accessing the password file in the OpenVPN configuration directory:

The root user can modify the password script file, which is the bare minimum level of protection required when keeping your login information in the clear text form.

Update the routing table of the Raspberry Pi

Your Rpi should be configured correctly for the outgoing Virtual private network to encrypt your internet connection. The static IP address of your Raspberry Pi must be substituted if it is different.

You'll need to update or generate the file below and add some lines. The command is as follows:

Include the following two lines in your script:

We require only one change to the routing table of your Raspberry Pi. We can use incoming and outbound VPN connections simultaneously when you save the adjustments and restart your Raspberry Pi computer.

Keep your DNS requests safe and secure

To ensure that your connection is genuinely safe, you must prevent DNS leaks. Using a Domain name server that isn't part of your virtual private network encrypted network results in a Domain name server leaks. For example, domain name server login and perform a man in the middle attack on your Virtual private network customers.

Forcing all incoming Virtual private network users to utilize the safe Domain name server from your outbound Vpn service provider is the solution.

OpenVPN config file is updated to change your domain name server without reinstalling the Pi Virtual private network. Use the following command to open the config file for editing:

The lines that send the Domain name server to your virtual private network clients are found by scrolling in the file.

When utilizing IPVanish, you need to replace these lines:

To identify the Domain name servers of a different Virtual private network, you'll need to research online. Save the file after editing it. As soon as the OpenVPN server starts up, your Virtual private network clients will connect automatically to secured servers provided by IPVanish.

Connect to IPVanish

OpenVPN should not connect automatically to the outbound virtual private network provider unless the connection is tested and verified. Type the following into the Run window:

The virtual private network connection status displays in the text on your screen. If you're having trouble connecting, double-check the outgoing configuration file and ensure your user information is in the password file on different lines. Hit Ctrl + C to exit the VPN once you've established a connection.

How can we connect to the virtual private network automatically?

After the connection is tested and found to be working, you should automate the startup for your VPN tunnel. You can connect to every connection using OpenVPN by its configuration file name.

This command will edit the OpenVPN global config file, which you'll need to begin.

Undo this line's comments.

Change it to:

Afterwards, save your modifications and reboot your Raspberry virtual private network server:

Pi VPN router settings

A virtual private network is a tunnel from the wide-area network to the local area network. Consequently, your router must be configured to accept specific connections. If you have a router that doesn't support port forwarding, you may have to perform this manually.

VPN port forwarding

If you didn't specify a port forward before, no Virtual private network clients would be able to access the network. We have to apply an exception to the security of our router's policies to allow these requests.

To access your router, copy its Internet address into your internet browser.

After logging in, go through the menus and select it from the list to enable port forwarding.

You'll have to remember the port number you previously chose in this process. Additionally, you'll need to know the static IP of your Raspberry Virtual private network server.

When you've completed port forwarding, click Save. VPN users can now access their accounts even if they are not in the local network.

Conclusion

This tutorial taught us to set up Raspberry pi as a virtual private network server. We also learned how to set up port forwarding and improve our network security. In the following tutorial, we will learn how to use a raspberry pi as a DNS server.

How to Use a Raspberry Pi as a DNS Server

Welcome to the next tutorial of our Raspberry Pi programming course. Our previous tutorial taught us to set up a free media server on Raspberry Pi. We also learned how to connect with different devices and stream media files. This tutorial will teach us how to use a Raspberry pi as a DNS server.

Prerequisites

You must have access to the following resources to follow this tutorial:

  • Raspbian Pi OS on Raspberry Pi (2-4).
  • Internet access is required.

There must be a unique identifier for every machine on the Internet to speak with each other Using IP addresses; clients can identify the servers they need to contact. However, no one is expected to remember the digits of an address; thus, DNS names are used instead. This DNS can be built on a Raspberry. It's a number-to-domain converter. Clients first need to get the internet address by querying Domain name servers. This can take up valuable time. As a result, it is possible to accelerate Internet connection by configuring a dedicated Domain name server.

What is a DNS server?

The DNS helps you navigate IP-based networks. You typically type in a domain name like www.example.org in your browser's address bar. Computers use iPv4 and IPv6 addresses to communicate across the Internet. However, the server must transform the memorable domain for the transmission to work. Domain name servers are utilized for name resolution. Using a cache first is necessary for this. It may not be necessary to look for the individual system's IP address in some cases.

As a result, DNS queries are routed to single or multiple servers. The internet service provider's DNS server is the first to be called upon most of the time. This DNS offers an optimum result by comparing the search with its database. Otherwise, a request is sent directly to one of the Thirteen Internet core nameservers. This database contains all of the URLs on the Internet.

Static IP addresses are rare among internet users, especially those who aren't the owners of their routers. This property goes hand in hand with the use of dynamic DNS. Internet service providers only assign IP addresses for up to 24 hours. This assignment is followed by a brief forced separation, network disconnection, and a new IP address assignment for the user. Since clients are rarely addressed from outside the home network and only make an HTTP request to the server– rather than vice versa – this usually is not an issue.

However, setting up a DNS server may be necessary for the following situations: Remote desktops and mini-game servers are two examples of this type of technology. As a result, dynamic DNS is employed. A DDNS server assigns a domain name to the domestic server, allowing it to be accessed. DynDNS is a good option if you want a web-based Domain name server that clients from anywhere in the world can access at any time.

What is the purpose of a DNS server?

For several reasons, users prefer to use Domain name servers instead of manually looking up external IP addresses. When you have a large family, numerous roommates, or an office, having your server is a no-brainer when everyone uses the same devices and shares the same network.

  • Speed: A website query may have to traverse numerous gateways and servers before reaching the user's browser. If connecting to the internet service provider's Domain name server is not required, this process can hasten the procedure.
  • Privacy: Queries must be directed to external servers to maintain the DNS functionality. Many people don't like the idea of having to follow a trail on the Internet. Much of the information is kept in your possession when using a dedicated domain name server.
  • Security: Control of Domain name server entries is available to everyone operating their server. Cyber crooks frequently try to tamper with Domain name server requests to return wrong IP addresses. Instead of displaying the intended webpage, a different one gets displayed. You can never be too careful with internet banking. Fraudsters can quickly gain control of your funds and bank account by entering your personal information on a replica of the bank's website.
  • Adblocking:Using several commercial servers to avoid advertisements blockers working around the web. Individual Domain name servers can also perform this task. Even your entire home network is untethered from the Internet.
  • Child filters:Setting up child filtering functions makes sense, like in adverts. Networks can use domain name servers to prohibit servers that deliver content inappropriate for minors.
  • Learning curve: Installing one's Domain name server is a popular approach for curious Internet users to learn more about how things work on the Internet. Wall outlets provide power, and online browsers provide content. However, like many other Raspberry projects, this one has a lot of potentials if anyone wants to get to the bottom of the technology.

How can we use a Raspberry to create a domain name server?

Step 1 - Update raspbian

To begin, use the commands below to update the software packages:

Step 2 - Installation of the DNSMasq package on Pi 4.

Once the DNSMasq tool installs, the Domain name server is configured. The Domain name server forwarder is configured with the aid of DNSMasq.

Several devices on the same network can use it to get their Domain name server queries answered. It also manages limited resources utilized while configuring the Domain name server on a Raspberry.

Step 3 – Configure DNSMasq

Increasing the DNS server's responsiveness is the goal of this stage.

Modify the dnsmasq.conf file by following the steps outlined below:

CTRL plus W will locate and delete any # symbol from the lines:

  • domain-needed ensures the Domain name server will not send out any wrong names. The local network is kept up to date by looking for names without a dot.
  • bogus-priv prohibits the server from relaying requests inside local Internet protocol ranges to extern servers. It serves as a safeguard to keep local IPs from being leaked to external services.
  • no-resolv instructs the Domain name server to utilize DNSMasq rather than /etc/resolv.conf when resolving addresses.

To remove the line displayed below, press CTRL followed by W to locate it.

Then, add these lines:

We will ensure the upstream is the Google Domain name server by completing the preceding steps.

If you want to increase the size of the cache to 1000, delete the # symbol and do the following:

It is possible to speed up response times by increasing the cache's capacity. Performance is also boosted by storing more domain name server responses.

Next, save the changes, then run the following command to reboot DNSMasq:

Use the following command to see if the DNS is up and running:

Step 4: Test the domain name server

Dig is used to verify the server's functionality. If you want to gather info about DNS servers, static IP, and other things, you can use dig in Linux.

For example:

The query execution time is shown in the preceding image.

Keep in mind that the server's response time of 1091 msec is all that matters here.

The time it takes to make a query is reduced since the address is saved in the cache. The image below makes this quite evident.

Keep in mind that the Request Time is all that matters.

Step 5 – Configure the domain name server on your device

Ifconfig is used to get the raspberry network address.

For example, our server Ip is 10.0.2.15.

The next step is to configure devices to use this Ip as their Domain name server. To make this happen on your Windows PC, follow these steps:

Press Windows key Plus R to access run, access the Control panel by typing control, and press Enter.

In the control panel, select Network and Internet.

Afterwards, click on the View networks option in the newly opened window that appears.

Choose adapter configuration from the left-hand menu of the new pane.

You may do this by right-clicking on the interface you're using, such as Wlan0 or Eth0, and selecting Preferences.

Right-click on TCP/IPv4 and choose Preferences once more.

Then choose those Domain name server addresses from the drop-down menu that appears inside the new window.

Using a Raspberry, you can maximize the speed of the network. Domain name server query response times can be sped up by storing IPs in a local cache.

Keeping a Domain name server safe is essential since it is a common target for fraudsters.

Ensure that the upgrades automatically keep it running smoothly. Use the following command to upgrade.

DNS Query Resolution by DNS Servers

Whenever you enter a web link into the browser's address bar, a Domain name server searches for the desired address. As a result, various Domain name servers are queried, and each of them performs a translation of the domain you entered. The following are the several servers that are contacted:

  • DNS Resolver: Converts the domain name to an IP address when a request is made. When looking for a specific website, this server conducts the heavy lifting of determining its location on the Internet.
  • Root Server: After receiving a request, the server tells Domain name server resolvers where to find information about the top-level domain server of the site. In another way, the .com part of your domain is known as the top-level domain.
  • TLD Server: As a result, the Domain name server resolvers query this server, which returns the actual authorized name server.
  • Authoritative Name Server: Lastly, the Domain name server makes a query to this server to get the unique IP of that website you are attempting to access.

You'll see the web page you were looking for after the Ip has been found in the internet browser. Even while it sounds complicated, the process is relatively simple and takes only a few seconds to get you back to the website of your choice.

Types of DNS attacks that are most common

A denial-of-service

A single denial of service assault can overwhelm a web server with just one machine and one internet connection. When it comes to overloading the high-capacity systems today, they don't work very well.

Domain name server amplification attack

Another sort of Cyberattack known as a DNS magnification is where attackers exploit open Domain name servers to overwhelm domain name server responses. As part of an attack, the intruder spoofs the user's Domain name server source address and sends another request to the open DNS. The Domain name server response is sent to the destination rather than the Domain name server.

Domain name server hijacking

Domain name server hijacking can take place in three ways:

  1. A registrar domain account can be hacked, and the DNS can be modified to one that the intruders have control over.
  2. Malicious people target you by changing the A record on the IP of your domain.
  3. The router is compromised when an intruder modifies the Domain name server that is automatically dragged down to every device whenever a user connects.

Domain name server tunnelling

Domain name server tunnelling uses the Domain name server protocol, which is used to determine the network id to transfer data.

When a client sends a domain name server request, the only info included is that which is necessary for the server and the client to communicate. By using Domain name server tunnelling, an extra set of data is routed over the network. Communication can proceed unhindered by filtering, firewall, or sniffing software.

As a result, it is challenging to identify and trace its origins. It is possible to establish command structure and control via Domain name server tunnelling. It is also capable of leaking data. When information travels via a Domain name server, it is often broken down into smaller bits and reconstructed.

poisoning of DNS and the poisoning of the cache

Web traffic can be redirected to infected sites using security holes in the domain name server protocol known as domain name server poisoning or server spoofing.

When you visit a website, your internet browser first asks for a local Domain name server for the Ip. The local domain name server will contact the root servers of the domain and authoritative name servers to obtain the address of your domain.

How can we avoid, identify, and respond to domain name server attacks?

  1. You should be familiar with your complete domain name server infrastructure. To begin, safeguarding a network necessitate familiarity with all of your company's DNS records. Occasionally, network administrators lack total visibility due to Domain name server silos, orphan zones, or shadow technologies.
  2. Domain name server responses and queries should be logged and monitored—first, spot anomalies by logging in and monitoring outgoing and incoming requests. An in-depth forensic investigation might be aided by collecting more responses.
  3. Secure your Domain name server recursive servers.Recursive servers can be protected from unauthorized access and modification with DNSSEC and other design changes.
  4. Secure your Domain name servers by limiting administrator privileges.

What are DNS servers used for?

For the Internet to function, a company's ICT department must support the DNS servers as a critical piece of infrastructure. A well-maintained authoritative Domain name server is required for this.

The most important thing to remember is that a server going offline is impossible with an adequately designed anycast Domain name server. It is possible to maintain each server at a time while providing a fast and reliable Domain name server by connecting geographically distributed endpoints with redundancy servers at every station.

Do you need a "perfect" domain name server? Yes, Outages to your external Domain name server can have a direct impact on the following departmental activities:

  • Primary websites
  • Marketing campaign website
  • Email server
  • Client support website
  • Online resource library
  • Webinar service
  • Instant message tool
  • IoT devices

This is an extensive list, but there are likely many more devices and programs that rely on the Domain name server to work correctly. Although outages and poor performance can harm your bottom line, the ROI is robust and measurable. As long as a Domain name server outage spares your team from having to meet with the above departments, the service will pay for itself.

Conclusion

This tutorial taught us how to use a raspberry pi as a DNS server. We also learned the possible attacks on a domain name server and how to prevent these attacks. In the following tutorial, we will learn how to use a raspberry pi as a VPN server.

How to Use a Raspberry Pi as A Media Server

Welcome to the next tutorial of our Raspberry Pi programming course. Our previous tutorial taught us to set up a webserver in raspberry pi. We also looked at configuring addclient and deploying apps to our repositories. This tutorial will teach us to set up a free media server on Raspberry Pi.

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

Using a Raspberry Pi as a multimedia server requires:

  • An operating system and miniDLNA program installed on your Raspberry Pi,
  • You can attach various cleanly formatted and fragmented hard disks to your Raspberry Pi for storing and streaming media files.
  • A basic understanding of how to use a computer, Client-server architecture skills, familiarity with Unix terminal and Secure shell, and a passion for computing and the media are a must!

Even if you lack some of the expertise mentioned above and experience, we can still attempt to accomplish this task, and you will gain new knowledge in the process!

This can be done in a variety of ways. It's a mix of free and paid options. While we're here, we'll learn how to use the DLNA protocol to run a public media server on a Raspberry Pi. Let's get right down to business right away.

What Exactly Is a Multimedia Server?

It's possible to store information in the form of files on a media server at a central location. It doesn't matter if it's a document, image, film, ebook, or scripting file stored on a conventional media server; everything it contains is a file. It merely allows you to store data in a more orderly fashion. Accessing data should necessitate you navigating it on your own.

A media server sits on top of the file server. Media items such as photos, music, and videos can be accessed with this application. In addition, it enables network playback. There's no need to worry about where the video files are kept. You don't have to do anything more than type in your questions and wait for the results to appear. For example, you can search for all the music by a particular artist or musician. These new features improve the media server's usability, manageability, and overall appeal.

What is DLNA?

Let's have a look at the DLNA, shall we? When it comes to digital living, DLNA (Digitized Living Network Alliance) is the acronym. SONY with Intel collaborated to create a multimedia transfer protocol standard. Its primary purpose is to set guidelines for media distribution via the Internet. Smart gadgets like android Tv, smartphones, and set-top boxes that can share multimedia content are all DLNA-compliant. Microsoft Media Player, VLC, and Plex will all be DLNA-enabled in the future.

Computers can now be used as multimedia servers thanks to the DLNA standard. A DLNA server and a DLNA client are necessary for DLNA to function. Media sharing is a server-to-client process that occurs at all times. Servers and clients cannot independently share material. Clients and servers are two terms you may hear used interchangeably. What do you think about their appearance? Any DLNA-enabled device can serve as a DLNA client. Smart devices that can stream media over the Internet are one example. Setting up a DLNA server does not necessitate a large server. Any of your friends can access it and set up their server with it. The Windows Player is capable of serving as a Digitized Living Network Alliance server. In addition, many NAS devices are equipped with DLNA server programs that allow users to view multimedia files stored on them. Free multimedia services can be built on the Raspberry Pi using the miniDLNA software.

How Do We Setup MiniDLNA on a Raspberry Pi?

Because of its small size, it can be run on any Raspberry model. Let us set up a miniDLNA service on our RPi and transfer multimedia files to external smart devices via the network.

A better grasp of the setup procedure is gained by splitting this topic into four primary subsections.

  1. Install miniDLNA on your Raspberry Pi.
  2. Create directories for the storage of databases and logs.
  3. Configuring of miniDLNA for media files to be picked up.
  4. Rebooting the miniDLNA service.

Install miniDLNA on your Raspberry Pi

Install miniDLNA:

It's as easy to set up as any other application. Let's do an apt installation.

Minidlna's DB and logs should be stored in this directory:

/mnt/data-ext4/ is where we'll create all of the directories we need for our demonstration purposes.

Adding the group and user to the minidlna directory ownership list:

Inside the minidlna folder, we can write to a folder instead of root, as shown by the permissions below. In general, it's not a good idea to offer complete access to everyone. s Instead, new users and groups are created, and the ownership is transferred to them. Therefore, the database and logs are stored in this folder.

Ownership can be changed with the command shown. In the chown command, the user and the group are permitted to access the folder.

MiniDLNA directories must have the necessary permissions set.

Minidlna folder ownership after the chown command is shown here.

Create directories for the storage of databases and logs

Set up an entirely new subdirectory named "Music" inside the "public" folder you just created. The 'public' folder has all permissions for all the users, so the sudo word isn't necessary anymore. This folder is owned by 'user' and group 'pi,' and no one else has to write access to this folder.

The write permissions of the Music directory need to be fixed:

You can use the same 'chown' command to make the Music folder owned by everyone and grant write access. Everyone acknowledges the file/directory because nobody and no group are users.

Organize multimedia content by creating a few additional folders:

Likewise, you can reorganize your multimedia files in any way you see fit by creating new folders. For demonstration, we will establish a couple of extra subdirectories.

Add a few extra subdirectories inside the /mnt/NTFS public folder. Then, add some audio and video files to each of these folders.

The miniDLNA configuration file should be set up as follows:

Now tell miniDLNA where to find the media files. Modify the configuration file in your preferred text editor.

The media directories should be configured at this point:

Make a list of all additional folders you've made to contain multimedia files in the line where you see 'media dir.' Just after the equal sign is a letter, ',' include the location of the files.

A: Audio

P: Picture

V: Video

PV: Pictures and Videos

Use the following steps to set up a database and log storage location:

Navigate a little farther down the page to specify where the DB and logs will get saved. Quit the editor and save the modifications you've just made.

Restart the minidlna service:

Restart your minidlna server for the modifications to be reflected in the database and take effect. If everything is okay, the program should be functioning. Please check the status of the server.

Allow only a limited number of users to watch at once:

Analyze the logs to confirm that everything is functioning as intended.

Just keep an eye out for warning logs. There are claims it can manage up to 8192 folders and subfolders. If you have a more extensive selection, you can change the value of your collection to make it more valuable.

/proc/sys/fs/inotify/max_user_watches. But, this will not survive a reboot.

Permanently limit the number of people who can watch a video:

To keep the value set indefinitely. Modify the document /etc/sysctl.conf.

At the very end, add the following sentence:

Restarting the minidlna service is as simple as configuring it to do so.

This can be accomplished in a variety of ways. Here's an easy one:

It's done. However, keep in mind that indexing and cataloging massive data will take longer. The cataloging process might take a little longer at times.

Use Plex to set up a media server for your home.

Download the Plex Media Server Package

Choose Plex Media Server from the menu button of the official website, then Linux from the left-hand platform drop-down, and select the Choose Distribution button there.

If you're looking for an ARMv7-based distribution, choose Ubuntu (16.04+) or Debian (8+), then save the image. Then follow the steps below to install.

Method 1:Using the WinSCP utility on a Windows Pc.

Installing WinSCP is as simple as going to the official website and downloading the software. Run the program you downloaded and installed after it has finished downloading and installation.

  1. First, go to the Session > New Site option.
  2. File Transfer Protocol: SFTP
  3. Enter the hostname
  4. Enter username
  5. Enter password
  6. Login

Once you've logged in, you should see the local Computer system files on your left side and the Raspberry Pi system files on the other side.

Locate the Plex Storage Server you already downloaded, right-click on it, and select Upload. On the raspberry home directory, the file will be stored there.

Method 2: Use a secure shell to access the wget command in raspberry pi.

Using a secure shell, you may download plex with the wget command from your Raspberry Pi. Direct access to the application file is required to download the entire package. Copy the link address of the application by right-clicking on it and selecting "Copy Link Address."

To download a specific package, run wget accompanied by the URL link and press return on your pi terminal.

The package is saved to the current working directory after downloading.

Install Plex on the Raspberry Pi

Connect to the Pi through a secure shell using PuTTY. You should be in the root directory. The program 'ls' output will reveal the file that was previously.

We'll now use the dpkg tool to complete the installation.

IMPORTANT: The filename must match exactly what appears in the secure shell terminal. The reference name of the command is just for illustrative purposes.

Press the return key then you'll be prompted for additional verification. Please accept them, and it'll be deployed as intended. Once the server has been set up, it may be found at:

Whenever you launch the service for the first time, it will prompt you to check in to the Plex account. Once you've entered your username and password, the page should reroute to the local server.

Setting up an external HDD for use with Plex

The OS makes it more difficult to mount a hard drive in headless mode. Using this method, you should be able to get everything you need to get this working.

Use the following command to make a new directory in the media directory:

To make a copy of your system's /etc/fstab, type the command:

To identify the external HDD, type the command:

The name may differ if you're looking for the sda2 (/dev/sda2).

Type the command below to obtain the partition Block ID:

There is a LABEL to identify this drive and its type as NTFS, which you can see by looking at the printout. You may also get it as ext4, depending on the format.

The following command is used to modify the /etc/fstab file:

Insert this line in the file:

This UUID is the one that we acquired when we checked the id of the block in the steps above. Ntfs or ext4 should be the file system on the attached drive.

Hit Ctrl + O to save the file, followed by Ctrl + X to quit; the file is saved.

Reboot the Pi while the HDD is still plugged, and then run the df program once more to make everything work as it should. A working /media/HDD mount is still required.

If something goes wrong during this stage, getting the server up and running again will be more challenging.

How can we upload media to the Plex server?

The Plex app can is found on the Internet by browsing the following address:

Then, click the settings button displayed below.

 

Navigate to MANAGE > LIBRARIES from the left menu. Libraries are now clearly visible. Select "Add Library" from the drop-down menu. You should now be able to select a media type from a new popup:

Click Next, then Browse for a Multimedia Folder to select the files you want to use. The hard drive will be as seen in the image below. To upload media, click Add and then choose the media directory from which you want to add it.

At this point, the service should begin searching for your files. Depending on the content and the volume of data in the folder, this could take a while to accomplish.

How can we stream on smart devices?

The server-side plex setup is now complete and operational. You can now choose from a variety of ways to consume your media.

  1. If you have a Smart TV, you can use the Plex client application for streaming. Get the plex application installed, and sign in. In your Wireless connection, the application will find the server for you. You can now begin streaming and listening to the files.
  2. You can download the mobile application from the google play store and log in with your details. The server on your local wireless network should be detected automatically by the application. Is it possible to begin viewing the media? However, it is required that you purchase either a plex pass or a one-time unlock the key to consume the multimedia files using your Android phone. If you expect to stream a lot, this is a good investment.
  3. If you have a desktop or laptop computer, you can access the application through the internet browser at:

You'll be able to watch movies, web series, and live TV through the client application and your local media files.

Conclusion

This tutorial taught us to set up a free media server on Raspberry Pi. It is now possible to stream and organize your media files attractive and portable manner. In the following tutorial, we will learn how to use a raspberry pi as a DNS server.

How to Setup a Web Server in Raspberry Pi 4?

Hello friends, I hope you all are doing great. Today, we are going to share the 2nd tutorial of Section-VIII in the Raspberry Pi Programming Course. In the previous tutorial, we interfaced a Barcode Scanner with Raspberry Pi 4. In today's tutorial, we will discuss how to set up a web server in raspberry pi. So, let's get started:

Components Required

We are going to use the following components, in today's project:

  • Ethernet cable
  • MicroSD card
  • Keyboard
  • Mouse
  • HDMI cable
  • Monitor

Expand FileSystem

When configuring a Raspberry Pi, select the expand FileSystem option to ensure that all of the Micro SD storage is allocated for the operating system and modify the default Pi passwords to protect your server from attackers.

On Your Raspberry Pi, Install a Web Server (Nginx)

Next, we will install the web server. As a result of its minimal memory footprint and compatibility with Node.js, We use Nginx as our web server. Apache or Lighttpd web servers could also be used.

  • Make sure your Pi is updated before you begin installing anything by executing the following commands:
  • Apt-get can then be used to install Nginx:
  • To start the server, enter the following command when the installation is complete:

Run ifconfig to discover the IP address of your Rpi. Your ethernet adapter's output will be found under eth0.

After discovering the IP addresses, you can direct your browser to it and expect to receive the default Welcome message for Nginx.

Web Access: Port Forwarding

If you don't intend to get access to your Raspberry Pi from elsewhere in your local area network, the following step is unnecessary. Those who wish to connect to their server from a different area should nevertheless be able to do so.

It is common for devices connected to a router in a domestic home networking environment to appear hidden from view. The external IP address of your network can only be used to access your router. Those devices can receive incoming traffic depending on your router's decision-making abilities.

As soon as you access a web page, the router understands that the response traffic is associated with that connection, and it will allow it through. It's possible to get around this by using a router that blocks incoming traffic that isn't part of a currently open connection (like whenever an external device tries to connect to a local device). This is a critical network safety precaution!

From the outside, how can you access your Pi's onboard network? What you need to do is to use port forwarding. Incoming connections on specific ports must be allowed to travel through the gateway and then sent to the specified device. Default by HTTP and SSH protocols use ports 80 and 22. Therefore, opening these ports in your router will enable users to access the web app and secure connections to manage the server.

Enable and forward a port on your gateway using the advanced configuration settings on the admin site. A simple search for "Forwarding," "Port Forwarding," or "Network Address Translation" will yield the results you need.

For Hypertext transfer protocol, one port must be opened, and a different port must be opened for secure shell protocol. The central concept is to have your Rasp Pi forward traffic addressed to the two ports: port 80 for Hypertext transfer protocol traffic and port 22 for Secure shell protocol traffic. Here's an illustration of what your router's setup page may look like if you applied this:

In case the IP address of your rasp pi is 192.168.1.16, you'll need to configure port forwarding. We use this address to forward all incoming connections to the Internet.

The external Internet address of your router can be found on Google by searching "what's my IP address."

Establish a Secure shell connection using the command below once you've left your router's network to confirm if forwarding is working.

Similarly, you may check for Hypertext transfer protocol forwarding by redirecting your web browser to the external IP address. However, it's essential to know that port forwarding lets anyone with knowledge of the external IP of your router access this port.

Static IPs aren't necessary with dynamic Domain name servers. It's a straightforward procedure. You can use your router to set up a dynamic Domain name server, or you can use a Raspberry Pi to do it.

How can we set up Dynamic DNS?

Install ddclient

Cloudflare's API is used to connect to the newest version of ddclient. After downloading directly from Sourceforge, we'll copy and paste the program.

ddclient configuration for Cloudflare

To configure the Cloudflare protocol, we need to set up ddclient. Cloudflare details like our address, API secret and time zone, and records will be required to make the changes.

The values procured are as such:

Using the asterisks marks, we will alter the script with the change above:

We will test to ensure that our hostname is updated correctly. Here is the command we'll use:

The following notice will appear on our screens:

Full-Stack JavaScript Framework Installation

This section will teach you how to run JavaScript in a full-stack environment on Nginx. Installing Node.js and MongoDB is required to perform this.

Installing Node.js on a Raspberry Pi has never been easier.

Once the installation is complete, use Node -v to see if it's working.

You can now install MongoDB simply by entering the command:

To maintain database integrity, you must stop the service on the Raspberry Pi before you can turn the raspberry pi off.

Deploy your application

Developing an application locally and later pushing any modifications to a BitBucket repository is possible. The pre-installed version of Git on Raspberry pi 4 makes it easy to download and run your most recent program code.

Scaffolding the Project

Let's create a Git repo and add some program code to it. We will start an application using the generator-angular-full stack, which scaffolds the server and client code.

This is how you get angular running on your computer:

A new directory is created for your application:

And then build the app:

Push the Code to the Repository.

The following instructions will walk you through setting up a BitBucket repository.

  1. To create a repository, you first need to visit the Bitbucket website and click the Create button.
  2. Select a repo for your workspace.
  3. Click on the Project menu or the "Create new project" button to begin a new task in your workflow.
  4. The uniform resource allocation of your repo will include the name you give it, so be creative! To minimize the size of the consistent resource allocation, make sure the name of your repo does not exceed 62 characters in length. A dash will be appended to the end of any non-alphanumeric characters in your repository name.
  5. If you don't want your repo to be accessible to the general public, you should set it to private.
  6. Do not include a README when you have files already existing in the repository. You can always use the default choice or choose one of the README alternatives.
  7. Choosing a version monitoring system is step seven. When in doubt, stick with Git as your default system.
  8. Create a new project by clicking the Create button.

Next, create a directory on your computer's hard drive:

As a result, the code can be committed and pushed:

The grunt-build-control tool is included with the generator to keep track of your builds. Add the BitBucket config to Gruntfile.js in the root folder of your app:

Create a folder for distribution by running the following command:

The code should be committed and pushed to your repository's build branch.

Create a secure shell Key

Your code is already on a server for your convenience. You will require a secure shell key for your Raspberry before using it on your BitBucket account for deployment. As a result, login to the Raspberry desktop and generate a public/private key from the terminal:

Afterward, launch the agent:

Also, provide the agent with the key:

Now you need to output the content of the public key:

Now copy and paste it into BitBucket.

Configure your BitBucket account by clicking on your profile image. Click on the Add keys tab under the SSH section of SECURITY.

Repository Cloning

A /var/www folder can serve as a place to store all of your application's code, but it's not a necessity.

To eliminate the need for sudo, you can make your Raspberry user the owner and www-data the group when you place the files inside the webroot:

Cloning your repo build branch and installing the required dependencies is now possible.

Now you may launch your application in production mode:

Open a web browser and type in the device's Internet protocol address to see if it works.

Nginx Reverse Proxy configuration

One final step must be taken before the application can be accessed from the outside world. Even though Nginx listens on port 80 to receive Hypertext transfer protocol requests for your Raspberry Pi, the Node app will be listening on another port. Configure Nginx to reverse proxy to recognize requests for your app and pass them forward to Node.

The sites-available subdirectory is where Nginx stores the configuration files for all of the applications it serves:

Download and modify the config file from here.

With Nginx set as a server proxy, the finished config file will look like the following:

Creating a symlink inside the sites-enabled directory where Nginx searches for activated configurations during runtime is required to enable this config.

To make these modifications effective, you must reload the service.

As a result of the server "name my-app.dev" command you specified earlier, your app is now available to receive hypertext transfer protocol traffic addressed to the my-app.dev domain. You must now figure out how to make the traffic you transmit from outside this domain name resemble this domain name as your final challenge. The host file eliminates the need to purchase a domain and link it to your Internet address.

The external Internet address of your router should be entered on the workbench from which you intend to visit the site, and the host my-app.dev should be entered in the same place. The correct domain name will be included in the Host hypertext transfer protocol header in any HTTP communication you send to my-app.dev.

Output

If you want to keep the servers running, you can install pm2 on your Raspberry Pi, and In the event of an error, you can erase the MicroSD card and start over.

What are the advantages of the Raspberry pi webserver?

A JavaScript application can be accessed beyond your network since deployment is possible on your new home development server.

Managing the equipment you use for development while working from far is a huge benefit.

What are the applications of a webserver?

PI Server Applications' responsibility is to gather, store, and retrieve mathematical and text data.

Engineers can analyze and evaluate the entire plant with the help of this Software. It all begins with the PI Server Applications. Numbers and strings are all handled by computers in the same way: collected, stored, and retrieved. Additionally, the PI Information Archive serves as a data provider for Windows-based apps used by researchers, engineering teams, and other plant staff to access the plant data contained in the Archive's database. In most cases, the PI Servers Application runs on a network of computers running different software packages.

The following are some examples of PI Server Applications:

  • Core Subsystem
  • PI-Data Archives
  • Point Database Subsystems
  • Update Managers
  • Snapshot Subsystems
  • Subroutines
  • PI-Network Managers
  • Performance Equations Schedulers

Conclusion

This tutorial taught us to set up a webserver in our Raspberry pi. We also learned how to configure and create a repository for our app and deploy it. However, In the following tutorial, we will learn how to use a raspberry pi as a media server.

Interfacing Servo Motor with Raspberry Pi Pico using MicroPython

Hello readers, I hope you all are doing great. In our previous tutorial, we discussed the implementation of pulse width modulation (PWM) in Raspberry Pi Pico using the MicroPyton programming example. We also implemented the LED brightness control program to demonstrate an application of the pulse width modulation technique.

In this tutorial, we are going to implement another application of pulse width modulation technique which is ‘Direction and position control of a servo motor’ with Raspberry Pi Pico module and MicroPython programming language.

Later in this tutorial, we will also discuss how to control the position of a servo motor with push buttons (to be used as control inputs) and also to use LEDs for indication purposes.

What is Servo Motor?

Before interfacing the servo motor with the Raspberry Pi Pico module, let’s first understand the behavior of a servo motor and how it is different from a DC electric motor.

There are several applications for electric motors in which the motor must only rotate at a specific angle. We need a special type of motor with a special arrangement that causes the motor to rotate at a specific angle for a given electric signal (input) in such applications, or we can call it an angular precision motor. The Servo motor is used in these types of applications.

A servo motor is a low-cost, high-power output device that can only rotate 180 degrees (90 degrees in each direction) and can control the angle of rotation anywhere within that 180-degree range.

Fig. 1 Servo motor

Technically speaking, a servo motor is a linear or rotary actuator that can control acceleration, linear or angular position, and velocity with precision. It consists of a motor and a position feedback sensor. It also requires a sophisticated controller, which is often a dedicated module designed specifically for use with servo motors.

The main feature of using a servo motor is that it has angular precision, which makes the motor capable of rotating as far as we want it to before stopping and waiting for the next input signal from the microcontroller (or Raspberry Pi Pico in this project). Unlike a standard DC electric motor, the servo motor starts turning as soon as the power supply is applied to it and continues to rotate until the power is turned off. On the other hand, we cannot restrict the rotational progress of the DC motor, but we can control its speed of rotation and turn it on and off or we can say that the DC motor does not have angular precision. Small servo motors are available there in numerous Arduino launcher kits (beginners) since they are simple to use in small electronic projects and applications.

A servo motor is mostly used in obstacle detector/avoidance robots and robotic arms.

Software and Hardware Components Required

  • Raspberry Pi Pico Module
  • Latest version of Python
  • Latest version of Thonny IDE should be installed on your system
  • MicroPython setup installed in Raspberry Pi Pico
  • Breadboard
  • LED
  • Resistor (330 ohm)
  • USB cable

We have already published tutorials on how to download and install the above mentioned software components.

Follow the given link for a detailed study of Raspberry Pi Pico: https://www.theengineeringprojects.com/2022/04/getting-started-with-raspberry-pi-pico.html

Controlling servo motor with Raspberry Pi Pico

A servo motor is controlled by sending a PWM or pulse width modulated signal. A servo motor can only turn for a total of 180 degree movement (90 degree in either direction).

Pulse width modulation technique is used to control the amount of power delivered to the load for a particular time. The pulse width modulated signal sent to the motor specifies the position of the shaft, and to turn the rotor into a desired position depending on the duration of the pulse sent through the control wire.

The major factors affecting the behavior of pulse width modulation are frequency and duty cycle. Frequency defines the number of cycles per second or it is the reciprocal of total time ‘T’.

Frequency = 1/ T

Where, T= ON time + Off time

The duty cycle determines the time for which the output pulse from the Raspberry Pi Pico is high.

Duty Cycle = ON time/ T

Interfacing Servo Motor with Raspberry Pi Pico module

Fig. Interfacing servo motor with raspberry pi pico

Connections:

Servo motor consists of three wires; red, brown and yellow. Two wires are for VCC and ground and the third one is the data or control pin. The servo motor we are using operates at 5V dc supply so the red wire of the motor is connected to the VBUS pin of raspberry Pi Pico board. The interfacing of servo motor with raspberry Pi Pico module is shown in Table1.

Table 1 Raspberry Pi Pico and servo motor interfacing

Programming Raspberry Pi Pico with MicroPython

To program Raspberry Pi Pico board there are various development environments available (like uPyCraft IDE, Visual Studio Code, Thonny IDE ect.) and multiple programming languages as well.

In this tutorial, we are going to use Thonny IDE to program the Raspberry Pi Pico board.

Installing Thonny IDE for Raspberry Pi Pico Programming:

We have already published a tutorial on installing Thonny IDe for Raspberry Pi Pico Programming on our website. Follow the given link to install the IDE: https://www.theengineeringprojects.com/2022/04/installing-thonny-ide-for-raspberry-pi-pico-programming.html

Steps to write a program for LED brightness conrtol are:

  • Open the Thonny IDE once it is successfully installed.
  • Select “for all users” option.
  • Connect the Raspberry Pi Pico development board with your system (laptop or desktop).
  • To create a new project; go to Files >> New.

Fig. 4 New Project

  • Connect the Raspberry Pi Pico board with laptop/desktop using USB cable.
  • Click on the ‘MicoPython(Raspberry Pi Pico)’ option from lower right corner in-order to select the interpreter for raspberry Pi Pico programming using MicroPython programming language. We already selected the one from lower right corner menu from the Thonny IDE window.

Fig. 5 Select Interpreter

  • Select interpreter ‘MicroPython (Raspberry Pi Pico)’ for Raspberry Pi Pico programming.

Image: 6 MicroPython for raspberry Pi Pico programming

  • You should see this MicroPython Version details in Shell section (to ensure that Thonny is ready to program your Raspberry Pi Pico board) as shown below:

Image: 7 Ready to program

Writing the MicroPython program for servo motor

  • The first task is importing the library file necessary for servo motor interfacing and PWM implementation to control the direction of rotation.
  • So here we are importing two libraries from machine i.e., ‘Pin’ and ‘PWM’ to access the GPIO pins and implement pulse width modulation respectively. The third library is ‘time’ to add delay if required.

Fig. 8 Importing libraries

  • Next we are defining a ‘pwm’ object where we are configuring the GPIO_1 as PWM pin.

Fig. 9 object declaration

  • Another important factor in PWM programming is the modulation frequency. We are setting the modulation frequency at 50 Hz.

Fig. 10 PWM frequency

  • The position of a servo motor can vary from 0 to 180 degrees. Here the servo motor position is represented in microseconds where 1000 to 9000us are representing 0 to 180 degree angular position.

Fig. 11 Changing angular position continuously

Save and test the program

    1. Click on the ‘save’ icon to save the servo motor interfacing program.

Fig. 13 Save the program

  1. After clicking on the ‘Save’ icon, an option ‘Where to save to?’ will pop-up. You can select any of the ‘Raspberry Pi Pico’ option.

Fig. 14 Save the program

  1. Run the program once it is successfully saved and compiled without any bug.

Fig. 15 Run the saved program

MicroPython Code

from machine import Pin, PWM

import time

# declaring pwm object for servo motor pin i.e., GPIO_1

pwm = PWM(Pin(0))

# setting PWM frequency at 50Hz

pwm.freq(50)

while True:

for position in range(1000, 9000, 50): # changing angular position

pwm.duty_u16(position)

time.sleep(0.1) # delay

for position in range(9000, 1000, -50):

pwm.duty_u16(position)

time.sleep(0.1) # delay

 

Result

Fig. 16 Raspberry Pi Pico and servo motor

That’s all about interfacing and controlling a servo motor with Raspberry Pi Pico module and pulse width modulation.

So far in raspberry Pi Pico programming series, we discussed and demonstrated the interfacing of output devices with raspberry Pi Pico board.

Now let’s take another example, where we are going to control the direction of rotation of a servo motor using push buttons which are acting as control inputs and we are also using LEDs (outputs) as indicators for various positions.

Push Buttons as Control Inputs with Raspberry Pi Pico

GPIO stands for General Purpose Input Output which means a GPIO pin can be configured both either as an input or an output pin. In raspberry Pi Pico (RP2040) module we have 30 GPIO pins and hence any of them can be used either as input or output pin.

Push button is used as an input component to trigger some event or an interrupt in microcontrollers. So here in this example, we are using some push button as control inputs to control the direction of rotation in a servo motor.

Push button operates in two logic states, Digital High and Digital Low. A push button can be connected with raspberry Pi Pico either in pull-up or in pull-down mode. In pull-down mode, when the button is presses the GPIO input will be in logic high and otherwise the input will be logic zero. On the other hand in pull-up mode the GPIO input will be in logic low state when the button is pressed and vice versa.

Hardware Components required:

  • Push buttons
  • Resistor (10K)

Interfacing push button with Raspberry Pi Pico

A schematic is attached below representing the interfacing of a push button with raspberry pi Pico:

Fig. 17 Push button interfacing

MicroPython Program

Most of the programming instructions will remain similar to the previous example with some additional instruction to interface LEDs and Push buttons and assigning their respective task.

  • Initially, we are declaring some led objects assigning various ‘output’ pins for LED interfacing.

Fig. 18 led object declaration

  • So far, we were configuring raspberry Pi Pico’s GPIO pins as output pins. Now, we will declare some ‘button_x’ objects where we will be configuring GPIO pins as input. Here we are declaring three push button objects.

Fig. 19 Push button object Declaration

  • We are defining some variables to store the status of push buttons.
  • Some conditional statements are used to change the position of the servo motor. The first push button is responsible for changing the shaft position for 0 to 90 degrees (1000 to 5000 microseconds) and the LED represented by object ‘led13’ will start to blink as an indicator.

Fig. 20 Push Button 1

  • The second push button will make the servo motor shaft to rotate from 90 to 180 degrees.

Fig. 21 Push button 2

  • The third push button will make the motor shaft to move from 0 to 180 degree back and forth and all the LEDs will along with the shaft movement in respective directions.

Fig. 22 Push button 3

Fig. 23 Interfacing push button, servo motor and LEDs with Pico board

Fig. 24

MicroPython Code

from time import sleep

from machine import Pin, PWM

# declaring pwm object for servo motor

pwm = PWM(Pin(0)) # PWM pin for Servo motor

# declaring led object

led1 = Pin(5, Pin.OUT)

led2 = Pin(6, Pin.OUT)

led3 = Pin(8, Pin.OUT)

led4 = Pin(9, Pin.OUT)

led5 = Pin(10, Pin.OUT)

led6 = Pin(13, Pin.OUT)

led7 = Pin(14, Pin.OUT)

led8 = Pin(15, Pin.OUT)

led9 = Pin(15, Pin.OUT)

led10 = Pin(16, Pin.OUT)

led11 = Pin(17, Pin.OUT)

led12 = Pin(18, Pin.OUT)

led13 = Pin(19, Pin.OUT)

led14 = Pin(20, Pin.OUT)

led15 = Pin(21, Pin.OUT)

led16 = Pin(22, Pin.OUT)

# object declaration for push buttons

button_1 = Pin(26, Pin.IN)

button_2 = Pin(27, Pin.IN)

button_3 = Pin(28, Pin.IN)

pwm.freq(50) # set PWM frequency for servo motor

def led_blink (x):

led1.value(x)

led2.value(x)

led3.value(x)

led4.value(x)

led5.value(x)

led6.value(x)

led7.value(x)

led8.value(x)

led9.value(x)

led10.value(x)

led11.value(x)

led12.value(x)

led13.value(x)

led14.value(x)

led15.value(x)

while True:

button1_state = button_1.value()

if button1_state == True:

for position in range(1000,5000,50):

pwm.duty_u16(position)

led13.value(1)

sleep(0.01)

led13.value(0)

button2_state = button_2.value()

if button2_state == True:

for position in range(5000,9000,50):

pwm.duty_u16(position)

led14.value(1)

sleep(0.01)

led14.value(0)

button3_state = button_3.value()

if button3_state == True:

for position in range(1000,9000, 40):

pwm.duty_u16(position)

led_blink(1)

sleep(0.05)

for position in range(9000, 1000, -40):

pwm.duty_u16(position)

led_blink(0)

sleep(0.05)

Results

The results observed are attached below. In the image attached below, we can see the difference in the servo motor’s shaft position when compared with the previous image (off state).

Fig. 25 Servo motor control with push buttons

Conclusion

In this tutorial, we implemented another application of Pulse width modulation technique with Raspberry Pi Pico module and MicroPython Programming language. We also learn how to use Raspberry Pi Pico’s GPIO pins to receive input from peripheral devices.

So, this concludes the tutorial. We hope you found this of some help and also hope to see you soon with a new tutorial on raspberry Pi Pico programming series.

Taking a screenshot in Raspberry pi 4

Welcome to the next tutorial of our Raspberry Pi programming course. Our previous tutorial taught us to how to print from a Raspberry pi. We also discussed some libraries to create a print server in our raspberry pi. We will learn how to take screenshots on Raspberry Pi using a few different methods in this lesson. We will also look at how to take snapshots on our Raspberry Pi using SSH remotely.

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

Why should you read this article?

This article will assist you when working with projects that require snapshots for documenting your work, sharing, or generating tutorials.

So, let us begin.

Screenshots are said to be the essential items on the internet today. And if you have seen these screenshots in tutorial videos or even used them in regular communication, you're already aware of how effective screenshots can be. They are quickly becoming a key internet currency for more efficient communication. Knowing how and when to utilize the correct ones will help you stand out from the crowd.

Requirements

  • Raspberry Pi
  • MicroSD Card
  • Power Supply
  • Ethernet Cable

Taking Screenshots Using Scrot

In this case, we'll employ Scrot, a software program, to help with the PrintScreen procedure. This fantastic software program allows you to take screenshots using commands, shortcut keys, and enabled shortcuts.

Features of Scrot

  • We could easily snap screen captures using scrot with no other tasks.
  • We could also improve the image quality of screen photos by using the -q option and a level of quality from 1 to 100. The quality level is currently at 75 by default.
  • It is straightforward to set up and use.
  • We may capture a particular window or even a rectangle portion of the display using the button.
  • Capable of retrieving all screen captures in a specific directory and storing all screen captures on a distant Computer or networked server.
  • Automatically monitor multiple desktop PCs while the administrator is away and prevent unauthorized behaviors.

Scrot is already installed by default in the latest release of the Raspbian Operating system. In case you already have Scrot, you may skip this installation process. If you're not sure whether it's already installed, use the command below inside a pi Terminal window.

If your Pi returns a "command not found" error, you must install it. Use the following command line to accomplish this:

After installing it, you may test its functionality by using the scrot instruction again. If no errors occur, you are set to go on.

Capturing a snapshot on a Raspberry Pi isn't difficult, especially if Scrot is installed. Here are a handful of options for completing the work.

  1. Using a Keyboard Hotkey

If you have the Scrot installed on your Pi successfully, your default hotkey for taking screenshots will be the Print Screen key.

You can try this quickly by pressing the Print Screen button and checking the /home/pi directory. If you find the screenshots taken, your keyboard hotkey (keyboard shortcut) is working correctly.

In addition, screenshots and print screen pictures will be stored with the suffix _scrot attached to the end of their filename. For instance,

  1. Using Terminal Window

This is easy as pie! Execute the following command on your Pi to snap a screenshot:

That is all. It is that easy.

Taking a Delayed Screenshot

The following approach will not work unless you have the navigation closed and have to snap a screenshot without the menu. To get a perfect snapshot with no menu, you must wait a few seconds after taking the picture. You may then close your menu and allow the Scrot to initiate the image capture.

To capture in this manner, send the following command to postpone the operation for five seconds.

Other Scrot settings are as follows:

  • scrot -b : for taking a window's border.
  • scrot -e : To issue a command after taking a snapshot.
  • scrot -h : To bring up an additional assistance panel.
  • scrot -t : To generate a snapshot thumbnail.
  • scrot -u : To take a screenshot of the currently active tab.
  • scrot -v : Scrot's most recent version will be displayed.

Changing Screenshot Saving Location

You might need to give the images a unique name and directory on occasion. Add the correct root directory, followed by the individual title and filename extension, exactly after scrot.

For instance, if you prefer to assign the title raspberryexpert to it and store it in the downloads directory, do the following command:

Remember that the extension should always follow the file name .png.

Mapping the Screenshot Command to a Hotkey

If the capture command isn't already mapped as a hotkey, you'll have to map it by altering your Pi's config file, and it'll come in handy.

It would be best if you defined a hotkey inside the lxde-pi-rc.xml script to use it. To proceed, use this syntax to open the script.

We'll briefly demonstrate how to add the snapshot hotkey to the XML script. It would be best to locate the <keyboard> section and put the following lines directly below it.

We will map the scrot function to the snapshot hotkeys on the keyboard by typing the above lines.

Save the script by hitting CTRL X, Yes, and afterward ENTER key when you've successfully added those lines.

Enter the command below to identify the new changes made.

How to Take a Screenshot Remotely over SSH

You may discover that taking snapshots on the raspberry is impractical in some situations. You'll need to use SSH to take the image here.

When dealing with Ssh, you must first activate it, as is customary. You may get more information about this in our previous tutorials.

Log in with the command below after you have enabled SSH:

Now use the command below to snap an image.

If you've previously installed the Scrot, skip line 2.

Using the command below, you can snap as many snapshots as you like using varying names and afterward transferring them over to your desktop:

Remember to change the syntax to reflect the correct username and Ip.

Saving the Screenshot Directly on your Computer

you can snap a screenshot and save it immediately to your Linux PC. However, if you regularly have to take snapshots, inputting the passcode each time you access the Rpi via SSH will be a tedious chore. So you can use publicly or privately keys to configure no passcode ssh in raspberry pi.

To proceed, use the following command to install maim on raspberry pi.

Return to your computer and use the command below to take a snapshot.

We're utilizing the maim instead of other approaches since it's a more elegant method. It sends the image to stdout, allowing us to save it to our laptop via a simple URL redirect.

Taking Screenshots Using Raspi2png

Raspi2png is a screenshot software that you may use to take a screenshot. Use the code below for downloading and installing the scripts.

After that, please place it in the /usr/local/bin directory.

Enter the following command to capture a screenshot.

Ensure to use your actual folder name rather than <directory_name> used.

Taking Screenshots Using GNOME Tool

Because we are using a GUI, this solution is relatively simple and easy to implement.

First, use the following command to download the GNOME Snapshot tool.

After it has been installed, go to the Raspberry navbar, select the menu, select Accessories, and finally, Screenshot.

This opens the GNOME Picture window, where you can find three different taking options, as seen below.

Choose the appropriate capture method and select Capture Image. If you pick the third choice, you will have to use a mouse to choose the location you wish to snip. If you use this option, you will not need a picture editor to resize the snapshot image. The first choice will record the entire screen, while the second will snip the active window.

GNOME gives you two alternatives once you capture a screen. The first is to save the snapshot, and the other is to copy it to the clipboard. So select it based on your requirements.

What are the Different Types of Screenshots to know?

  1. Screenshot

It all begins with a simple screenshot. You don't need any additional programs or software to capture a basic screenshot. At this moment, this feature is built into almost all Raspberry Pi versions and Windows, Mac PCs, and cellphones.

  1. Screen capture

It is the process of capturing all or a part of the active screen and converting it to a picture or video.

While it may appear the same thing as a screenshot and a screen capture, they are not the same. A screenshot is simply a static picture. A desktop window capture is a process of collecting something on the screen, such as photographs or films.

Assume you wish to save a whole spreadsheet. It's becoming a little more complicated now.

Generally, you would be able to record whatever is on your window. Still, in case you need to snip anything beyond that, such as broad, horizontal spreadsheets or indefinitely lengthy website pages, you'll need to get a screen capture application designed for that purpose. Snagit includes Scrolling snapshot and Panorama Capture capabilities to snap all of the material you need in a single picture rather than stitching together many images.

  1. Animated GIF

This is a GIF file containing a moving image. An animated succession of picture frames is exhibited.

While gif Images aren't limited to screen material, they may be a proper (and underappreciated) method to express what's on your display.

Instead of capturing multiple pictures to demonstrate a process to a person, you may create a single animated Version of what is going on on your computer. These animations have small file sizes, and they play automatically, making them quick and simple to publish on websites and in documents.

  1. Screencast

This is making a video out of screen material to educate a program or sell a product by displaying functionality.

If you want to go further than a simple snapshot or even gif Animation, they are a good option. If you have ever looked for help with a software program, you have come across a screencast.

They display your screen and generally contain some commentary to make you understand what you are viewing.

Screencasts can range from polished movies used among professional educators to fast recordings showing a coworker how to file a ticket to Information technology. The concept is all the same.

Three reasons Why Screenshot tool is vital at work

  1. Communicate Effectively

Using screenshots to communicate removes the guesswork from graphical presentations and saves time.

The snapshot tool is ideal for capturing screenshots of graphical designs, new websites, or social media posts pending approval.

  1. Demonstrate to Save Time

This is a must-have tool for anybody working in Information Technology, human resource, or supervisors training new workers. Choose screenshots over lengthy emails, or print screen pictures with instructions. A snapshot may save you a lot of time and improve team communication.

Furthermore, by preserving the snapshot in Screencast-O-Matic, your staff will be able to retrieve your directions at any time via a shareable link.

To avoid confusion, utilize screen captures to show. IT supervisors, for instance, can utilize images to teach their colleagues where to obtain computer upgrades. Take a snapshot of the system icon on your desktop, then use the Screen capture Editor to convert your screen capture into a graphical how-to instruction.

Any image editing tool may be used to improve pictures. You may use the highlighting tool to draw attention to the location of the icons.

  1. Problem Solve and Share

Everybody has encountered computer difficulties. However, if you can't articulate exactly what has happened, diagnosing the problem afterward will be challenging. It's simple to capture a snapshot of the issue.

This is useful when talking with customer service representatives. Rather than discussing the issue, email them an image to help them see it. Publish your image immediately to Screencast and obtain a URL to share it. Sharing photos might help you get help quickly.

It can also help customer support personnel and their interactions with users. They may assist consumers more quickly by sending screenshots or photographs to assist them in resolving difficulties.

Snapshots are a simple method for social media administrators to categorize, emphasize, or record a specific moment. Pictures are an easy method to keep track of shifting stats or troublesome followers. It might be challenging to track down subscribers who breach social network regulations. Comments and users are frequently lost in ever-expanding discussions.

Take a snapshot of the problem to document it. Save this image as a file or store it in the screenshots folder of Screencast. Even if people remove their remarks, you will have proof of inappropriate activity.

Conclusion

This tutorial taught us how to take screenshots from a Raspberry Pi using different methods. We also went through how to remotely take snapshots on our Pi using SSH and discussed some of the benefits of using the screenshot tool. However, In the following tutorial, we will learn how to use a raspberry pi as a webserver.

Printing in Raspberry Pi 4

Welcome to the next tutorial of our Raspberry Pi programming course. Our previous tutorial taught us to how to tweet from Raspberry pi. We also discussed some methods used by the tweepy library to perform some API calls in our project. We will learn how to print from a Raspberry pi in this lesson.

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

Let us get started

There are several benefits of having a print server. Print servers may link numerous computers to one or multiple printers, either physically or wirelessly, allowing you to access the printer with various devices and send print instructions from all the other connected computers.

It is not easy to print from an Android smartphone to a cabled printer; however, a printer server makes it simple. A print server is useful in small workplaces where employees may print from any business printer. Another benefit is that we do not need to install drivers and software for the printer on your devices.

Requirements

  • Raspberry Pi
  • USB Printer
  • Ethernet Cable
  • Power Supply

CUPS

The Common Unix Printing System is a printing tool for machines running UNIX-like operating systems. It enables the machine installed to function as a printer server. A CUPS-enabled computer may take tasks from numerous devices, process them, and send them to the right printer for printing.

Setup Print Server Software CUPS

With our Raspberry terminal, we will configure the typical Unix printing system.

  1. Update Pi

We need to ensure that our Pi runs the most recent software; thus, we will carry out the following command in the terminal.

Once the installation is finished, we will restart our raspberry pi.

  1. Use Static IP

A few system changes are required before utilizing the Pi as a "server" on the network. We must configure the dynamic host configuration protocol client to use a static Ip; otherwise, the DHCP client may choose any accessible network address, making it difficult to access the RPi over the network.

We begin by modifying the DHCP configuration file.

If you choose to create a static Ip for the wired connection or a Wi-Fi connection, add either one of the below.

  1. Interface: This is the network connection for configuring the settings.
  2. the static Ip address is the Ip you'll use to configure your device. (Don't forget to include a /24 in the end.)
  3. static routers: It is the default gateway.
  4. Static domain_name_servers: Your DNS server's IP address is this.

Save your file by pressing Ctrl Plus X, then Yes, finally Enter key. Lastly, restart your Raspberry Pi.

Note that your network setup may differ in address category and Ip. This step must be done carefully; otherwise, your Pi will experience connection troubles. Run the following commands and look at the inet and subnet mask numbers to know what IP address you'll need:

  1. Install CUPS

The next step is to set up CUPS. This will take some time, but it will install with other requirements such as Samba, Perl, and several other tools or packages.

  1. Configure CUPS

We have to make adjustments to CUPs' config file. The following commands can be used to edit the configuration file:

To the config file, add the following. We will be able to communicate with CUPS panels due to these modifications.

If you wish to change the Ip port, locate and modify this line.

In addition, if we want to use the CUPS Interface, you must accept requests coming from that domain. Just before <location> tags, we add these lines.

Save your file by pressing Ctrl + X, then Yes, accompanied by the Enter key.

  1. User & Network Access Settings

The Raspberry user is then added to the lpadmin group. This allows the RPi to conduct CUPS administration duties without being a superuser.

We must guarantee that CUPS is available throughout the network.

Lastly, reboot CUPS to apply the modifications.

  1. Setup Samba

Samba is an industry-standard Microsoft interoperable package for Unix systems. It allows our Windows operating system to connect to our CUPS central server on the Raspberry Pi and transmit print instructions from the Windows system.

We have to change Samba's settings in the config file before we can proceed with the setup:

Scroll down to the print area and alter the guest's ok to yes.

Scroll down to the printer driver area and change the line shown below

Save the script by pressing Ctrl Plus X, then Yes, accompanied by the Enter key.

Lastly, reboot Samba to see the modifications take effect:

How do we set up our printer?

Install Printer Drivers

You may need to install printer drivers. You can look for the instructions for your specific printer brand on the internet, but we'll be using an HP printer for this lesson.

Install the following GUI if desired:

Then run the command below and download the displayed package from HP.

Adding Printer to CUPS

Link your computer to the network your Raspberry is in. Open the internet browser and navigate to the CUPS site by providing your Pi IP followed by port ":631," to which CUPS is connecting. If the internet browser displays the message "Connection not secure," select "Proceed Anyway."

You may find your Pi IP by running hostname -I on your Pi terminal. If all goes well, the website is:

Navigate to the Admin page and choose Add Printer. Ascertain that you turn the printer on and hook it to the Raspberry through USB. Follow the on-screen instructions to set up the printer. Check the "share this printer" checkbox before proceeding to the last stage. Lastly, print a sample page on the Printers tab to ensure that everything is working correctly.

Please remember that the printer might not be shown under "Local Printers." If this is the situation, you must configure the necessary printer drivers in your Raspberry Pi.

The last step is to transmit print instructions using any connected devices. After that, you can print wirelessly from Linux, Microsoft, Macintosh, Android, and apple. There is no need to install additional printer drivers for this.

Printing with the raspberry pi

This is the final and most straightforward step, in which we will wirelessly communicate print instructions to our printer. You must have CUPS installed on your Raspberry and print a sample page using the CUPS Web-based interface. Any gadget you would like to print from must be on the Pi network.

Windows

You must have Samba installed and set up on your Pi for this to function.

Navigate to Settings and select "Add a printer or scanner." This will automatically detect the network printer, and you may add it by clicking "Add Device."

Select "The printer that I want isn't displayed if it doesn't work."

The queue name, in this case, is like the printer's queue name in the Printers tab of the CUPS web-based interface.

Linux

You may add a wireless printer to a Linux desktop by going to GNOME Preferences- Devices and Printers. The procedure would be relatively similar in other Linux distributions.

The wireless printer will be discovered and added automatically. If that doesn't work, you might need to add the printers by entering the Ip of the Raspberry Pi.

macOS

At the bottom, press the Plus button. The printer will be detected automatically by Mac. Select and then click Add.

Android

The system includes a Print Function in Android. For previous versions, you must install the CUPS Print plugin. Then go to Settings -Devices Connected -Connectivity- Preference Printing and activate the CUPS Printing plugin. You may start the Print Capability in Oreo and later versions.

For printing a paper or file, open the files in a printing-compatible app. Go to Options Print, choose your printer, and press the print button.

There was an issue that occurred after installing a printer. The printer only printed a few jobs and ignored the rest. I had to reboot either the Raspberry Pi or the printers to resume printing. The command below resolved this issue:

Benefits of Wireless Printing

If you haven't yet experienced the pleasures of wireless connection printing, this project is a great place to start. But what's the point of wireless printing?

Mobility

Wireless connected printers enable users to work effectively on the go because there are no cables attaching the printer to a particular spot. This may be useful in various industries, from retail, where sales associates can construct more checkout stations during busy periods, to logistics, where haulage carriers must track the weights of their vehicles.

Organizations with mobile workers, such as health & security inspectors, may profit from wireless communication because employees can print their invoices, records, and results right away – instead of having to go back to their offices.

Accessibility

Instead of struggling to access your business services to download discs, these wireless printers work efficiently. The benefits of a wireless connection are limitless. It allows business employees to produce receipts, examination data, tickets, and labels with a single click and return to their job with minimal interruption.

Wireless printing can also eliminate the requirement for Wi-Fi using iOS and Android technologies, allowing mobile employees, public transportation drivers, and law enforcement officers to print files regardless of their place.

Multifunctional

Wi-Fi printers use infrared technologies to connect to other devices and quickly produce high-quality banners, receipts, and bar codes. The printer may increase doctor efficiency while drafting patient information if it is equipped with pre-cut labels and provide major benefits to CSI teams, who can now immediately manufacture evidence tags at crime scenes.

Depending on your company's needs, a single printer can serve various functions. While a shop manager may utilize a mini-printer for everyday receipt production, they could also opt to use the same printers to print tickets for exclusive launch events, therefore, lowering equipment expenses.

Convenience

Because the printer is small and portable, employees may set it wherever needed. The printers provide excellent space-saving solutions for better printing efficiency and the ability for many users to connect to a single printer to cut the cost of buying extra resources.

These printers are intended to reduce waste, which is very important for conferences and seminars. Workers may print on demand since the printer does not have to be supplied with pre-printed tickets, avoiding the possibility of an unneeded surplus.

Cost-effective

Wi-Fi printers are advantageous to small stores, like start-ups or pop-ups, since they are not well-established companies.

With a bit of investment in such a payment service and a portable printer, business owners may accept card payments at gatherings or establish temporary kiosks in existing businesses and cafés.

Despite their small size, Wi-Fi printers have a considerably longer battery storage life that may last weeks or even months on standby. This implies you won't have to pay a high electricity cost, and you won't have to resupply every day.

Wi-Fi printing makes printing more flexible, making it an excellent project for Raspberry Pis. The advantage of this approach is that it is compatible with Microsoft operating system, Macintosh, and other Linux distribution systems.

What Can We Do With Our Printer?

Greeting Cards

Decades ago, some individuals stopped sending these cards and letters. But there's nothing quite like receiving a handmade letter from someone. Your printer offers multiple options for printing in various sizes.

Print Your Artwork

You could even use an inkjet printer to print creative design work if you're a creative individual. Because inkjet ink offers a much more accurate and vibrant color representation than laser ink, we recommend utilizing them instead of laser printers.

Business Cards

There is no better method to share professional details with customers than offering them a professional card nowadays. Ordering these cards, on the other hand, is shockingly costly.

Custom Napkins

Are you preparing a great social event or party? Prepare your paper napkins by printing something unique on them. That's right: you can personalize your napkins with photos, graphics, initials, logos, and other details.

With this capability, you can elevate that special event or family dinner to a whole new level. Furthermore, if you own a modest business that offers personalized napkins, it is really a fantastic option to work from home.

Conclusion

In this tutorial, we learned how to print from Raspberry pi. We also learned some of the benefits of using a wireless printer. However, In the following tutorial, we will learn how to take a screenshot in our Raspberry pi.

Tweeting on Raspberry pi 4

Welcome to the next tutorial of our Raspberry Pi programming course. Our previous tutorial taught us to configure our raspberry pi for voice control. We also discussed some methods of reducing vexing noises so that the voice command program understands you. However, in this lesson, we will learn how to tweet from Raspberry pi.

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

What will we learn?

Assume you wish to add tweeting into a Raspberry Pi software you're developing. This article will show you how to build a Twitter app, get access privilege tokens, and post a tweet. On our Raspberry Pi, we'll make a simple program that tweets the result of the uptime command. This is a made-up example, but it demonstrates what is needed to tweet from a raspberry pi.

For this session, a repo has been set up. Because we'll be referring to code within the repository, cloning it will be helpful. You could use this program as a reference point for your programs or copy the components you need.

Let's start by installing git with the command below.

We're going to clone the repository into our current working directory now:

After that, change the directory into the repository.

The Twitter Application programming interface requires that all queries use OAuth for authentication. To access the Application programming interface, you must first create the authentication credentials. Four text strings make up these credentials:

  • Consumers keys
  • Consumers secrets
  • Login Tokens
  • Login Secrets

If you're a Twitter account, go through the procedures below to get the keys, tokens, and secrets. If you don't have a Twitter account, you'll need to establish one first.

Step 1: To become a Twitter Developer, fill out the form below.

Visit Twitter's developer site to sign up for a new account. You must now select the Twitter subscriber in charge of this account. It's most likely going to be yourself or your company. This is how this page appears:

After that, Twitter asks you questions about whatever you want to utilize the developer's account, as seen below:

You must specify the developer account's username and whether it will be used for commercial or personal purposes.

Step 2: Create an application

Apps and not accounts have access to Twitter's authentication credentials. Every tool or program that uses Twitter's API qualifies as an app. To perform API calls, you must first register your application. Navigate to the Twitter applications page and click on the option to create an application to register the app.

The following details regarding your application and its aim must be provided:

  • App name: a name that will help people remember your app (such as examplebot)
  • The objective of your application is described in the application description
  • Uses of the app: how customers will utilize your application
  • The uniform resource locator of your app's website is required; however, it could be a personal website's URL because bots do not require a URL to function.

Step 3: Create your Credentials for Authentication

Navigate to your Twitter applications page to generate the authentication credentials. This is how the Apps page looks:

The Details button for your app can be found here. After hitting this button, you'll be sent to the following page, on which you can obtain your credentials. You could generate and copy the keys to use in your code by selecting the Keys and Tokens tab:

Save the credentials after you've generated them to use them later in your code.

The following snippet can be used to test the credentials:

How can we set the app permissions?

Ensure that the "Read, access, and write direct message" is ticked in the "Permissions" section.

How can we Install Tweepy?

Tweepy is a Library for python for utilizing the Twitter API, and it's included in the requirements.txt document, so all you have to do is:

How does tweepy work?

Tweepy is a library that simplifies the Twitter application programming interface. Tweepy is a collection of functions and classes that mirror Twitter models and application programming interfaces, and it handles implementation details discreetly, such as:

  • Decoding and encoding of data
  • Hypertext transfer protocol requests
  • Results paging
  • Authentication
  • Rate restrictions
  • Streaming

If you didn't use Tweepy, you'd have to deal with low-level features like hypertext transfer protocol, data encoding, authorization, and speed limits. This may consume a lot of time and is subject to mistakes. Tweepy allows us to concentrate on the functionalities we wish to implement.

Tweepy can be used to access the Twitter application programming interface features. Let's have a simple example to see what we're talking about.

The example command below will download all of your tweets from your timeline and output each one to the console. Twitter mandates that all requests be authenticated using OAuth. Tweepy makes using OAuth simple for you. We'll need to establish an account for our application to get started. Build a new app, and when it's done, you should get your authentication token and secret. Keep these two with you at all times; you'll need them.

Next, create an instance of OAuthHandler. We enter our user token and secret, which we received in the previous line, into this:

If you're utilizing a callbacks uniform resource locators that need to be given dynamically in a web application, you will pass it in like this:

If the callback uniform resource locator isn't going to change, it's preferable to put it up as static on Twitter when creating your app.

Unlike basic authentication, we must first perform the OAuth "dance" before we can use the API. The steps below must be completed for this:

  • Redirect the user to the Twitter account to approve our application by obtaining a request tokens from Twitter
  • Twitter sends the user to our website whenever a callback is used. Otherwise, the user will have to enter the verification code manually.
  • Substitute an access token for the authorized request token.

So, to start the dance, let's get our request token:

This call asks Twitter for a token and then provides the authorization uniform resource locator, to which the user should be redirected to approve us. Simply keeping our OAuthHandler object alive till the user returns is sufficient. In a web app, a callback will be used. As a result, the request token must be saved in the session because it will be required in the callback uniform resource locator request. A fictitious example of saving the request tokens in a session is as follows:

As a result, we can now redirect the visitor to the uniform resource locator returned by our authorization URL() function.

If it is a desktop program (or any other software that doesn't employ callbacks), we'll need to ask for the "verifier code" that Twitter will provide after they have authorized us. This verifying code is sent in the callback query from the Twitter account as a GET query argument in the URL within a web application.

The request token is then exchanged with an access token in the last phase. The access token is the "key" to the Twitter Application programming interface treasure chest. To obtain this token, we must perform the following steps:

It's good to keep the access token on hand if you need it later. It is not necessary to fetch it every time. Because Twitter does not currently expire tokens, they would become invalid only when the user revokes our application's access. Your application determines the location where you store the authentication token. Essentially, you must save two string values: secret and key:

You can save these in a database, a file, or wherever else your data is stored. To re-create an OAuthHandler using this cached access token, follow these steps:

Since we have an access token for our OAuthHandler, we can move on to the following step:

Tweet python code

How is API used in this library?

The application programming interface class gives you access to the Twitter RESTful API's entire methods. Each method can take different parameters and provide different results. The API methods are classified into the following groups:

User timeline methods

These ways allow you to read mentions, tweets, and retweets on your timeline and any other public user's timeline.

Tweet methods

These methods deal with tweet creation, retrieval, and retweeting. Tweepy is used in the following code to produce a tweet with specific text:

Users’ methods

The functions in this group may be used to retrieve users using a filtering criterion, extract user data, and show followers for each user so long as the account is public.

Follower methods

This set of routines includes methods for following as well as unfollowing persons, requesting followers for a user, and displaying the profiles a user is following.

Account methods

Using these methods, you may write and view your profile information. This code sample might be used to change your profile information, for example:

Likes method

You can designate any twitter message as Liked or delete the Like tag if it has already been added using these API calls.

Blocking user method

This collection of methods includes unblocking and blocking members and a list of blocked users. You can view the users you've blocked in the following way:

Search methods

You may search tweets using these methods using language, text, and other filters. For instance, this code will return the ten latest public tweets in English that contain the term "Python":

Trend methods

This set of tools allows you to generate a list of the most recent developments for any place. Here's how to construct a list of worldwide hot issues, for example:

Streaming methods

Streaming enables you to actively monitor tweets in real-time for those that meet particular criteria. This indicates the program waits for the latest tweet to be produced before processing it if no other tweets satisfy the requirements.

You must construct two objects to use streaming:

  1. The stream object retrieves tweets that meet certain criteria using the Twitter API. A streaming listener receives tweets from this source.
  2. The streaming listener receives the tweets from the stream.

This is how you do it:

How about models?

Most of the time, when we call an API method, we'll get a Tweepy class model object back. This will hold Twitter's data, which we can use in our program. The following code, for example, returns a user model:

The following are the model classes:

  1. Users
  2. Statuses
  3. Friendships
  4. Search Result

Let's assume you want to obtain a list of all the tweets that mention you, then like each one and follow the author. This is how we can go about doing it:

Since every tweet object given by the mentioned timeline() belongs to the Statuses class, you can use the following syntax:

  • favorite() to make it a favorite
  • favorite() to make it a favorite

Tweet.user property is also a user object. Follow() may add the author of that tweet to the list of individuals to follow. Using Tweepy models allows us to write concise and understandable code.

What is next after setting up our app?

Maybe we can put a motion detector and a camera on our cat and tweet images of it. Alternatively, we could set up a temperature sensor and tweet some weather-appropriate status updates. We can also leave the repository unchanged and tweet the uptime command if we only want others to know our pi's load average.

Conclusion

You may take the Twitter presence to another level by creating your personal Twitter bots. You may use bots to automate content generation and other Twitter tasks. This may save time and provide a better user experience for your viewers. The Tweepy library hides numerous low-level Twitter application programming interface details, allowing you to concentrate on the logic behind your Twitter bots.

In this tutorial, we learned how to set up our tweeter app on our Raspberry pi. We also learned how to generate access tokens, set up our app's permissions, and send a tweet. However, In the following tutorial, we will learn how to print on a Raspberry pi.

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