Thank you for joining us for yet another session of this series on Raspberry Pi programming. In the preceding tutorial, we constructed a personal Twitter bot using Tweepy, a Py framework for querying the Twitter application programming interface. We also constructed a Response to robot mentions that would post a response to everybody's tweet mentioning it with a certain keyword. However, in this tutorial, we will implement a security system using a motion sensor with an alarm.
This is what it looks like:
PIR Motion Sensors can be implemented with RPi by understanding how it is connected to a Raspberry Pi. Whenever the motion sensor detects human movement, an alarm is triggered in this project and the LEDs blink. You may create a simple motion-detection alarm using this interface.
Infrared Motion Detectors or PIR Sensors are Motion Sensors that use Infrared Radiation to detect movement.
Infrared rays are emitted by anything with a temperature higher than absolute zero, be it life or non-living. Humans are unable to see infrared radiation because its wavelength is longer than the wavelength of visible light.
That's why PIR Sensors are designed to pick up on those infrared rays. Due to their wide range of uses, such as motion sensors for security systems and intruder alert devices
"Passive" in motion sensor refers to the fact that it doesn't produce any radiant rays of its own, but rather detects it when other things emit infrared radiation. This is in contrast to active detectors, which perform both the generation of infrared waves and the detection of these waves simultaneously.
For this project, we used a motion detector that included an infrared sensor, a BISS0001 integrated circuit, and other parts.
The 3 pins on the motion sensor are used for power, data, and ground. There are two potentiometers on the Motion Sensor that may be used to modify both the sensor's sensitivity and the period it remains high on sensing a body movement.
A key role in directing infrared rays onto the sensor is played by the Fresnel lens overlaying the Pyroelectric Sensor. This lens allows the PIR Sensor to detect things at an angle of 1200 degrees. The sensor has an 8-meter detection range, meaning it can pick up on human movement within that distance.
Two potentiometers are provided for fine-tuning the sensor and output timing, as previously described.
With the aid of a potentiometer, you may modify the sensor's sensitivity. The distance can be changed between 3m and eight meters. To increase the detecting distance, spin the Potentiometer in a clockwise motion and to reduce, rotate it in the opposite direction.
The second potentiometer allows you to choose how long the motion sensor's output remains HIGH. Anywhere from 0.3s to 600s can be used. Turn the POT clockwise to raise the time and the opposite turn to decrease it.
A Motion Sensor based on RPi and Python language has been the goal of this project since the beginning, as stated in the intro.
I have an Infrared Motion Sensor Component in numerous different projects like Automated Lighting using Raspberry and Various Sensors, Automated Door Opening with Arduino and a motion sensor, and GSM Home Automation Security with Pi.
The key advantage of the Infrared Motion Sensor utilizing RPi over the above-described projects is that RPi can be readily connected to the Web and allows Internet of things implementation of the project.
The following figure illustrates the interfaces concerning the Infrared Motion Detector using RPi.
Raspberry Pi 4
PIR Sensor
Speaker
Jumper Wires
Breadboard
Power Supply
Computer
Link the Motion Sensor's Vin and GND connectors to the RPi's 5 volts and GND pins. Use pin11 to attach the Infrared Sensor's DATA Input.
Gnd and pin 3 are where you'll want to connect the led. As soon as the sensor is triggered, these LEDs will come on and go off.
Python is used for the programming portion of the project. The Python program for RPi's infrared Motion Sensor is provided below. Insert the program into a new file called motion.py.
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.IN) #Read output from PIR motion sensor
GPIO.setup(3, GPIO.OUT) #LED output pin
while True:
i=GPIO.input(11)
if i==0: #When output from motion sensor is LOW
print("No intruders",i)
GPIO.output(3, 0) #Turn OFF LED
time.sleep(0.1)
elif i==1: #When output from motion sensor is HIGH
print("Intruder detected",i)
GPIO.output(3, 1) #Turn ON LED
time.sleep(0.1)
The operation of the Infrared Motion Sensor with Raspberry Pi is pretty straightforward. If the Infrared sensor senses some body motion, it sets the Data Input to HIGH.
RPI on identifying a 1 on the associated input gpio, will trigger the alarm.
When you purchase a new sensor, it doesn't work. The Trim port is in the default setting, so it's not a sensor issue. Sensitivity of the sensor and trigger duration port if you modify these settings. It's going to start working as planned. Make sure the trigger duration port's knob is on the left as a low trigger duration and the sensitivity port is in the middle.
Infrared Motion Sensor with Raspberry Pi has already been discussed. They include:
Automated house lights
Motion sensing
Intruders notice
Automated door open
Home security systems
When motion is detected by the PIR sensor on the raspberry pi, we will look into how to record video and transmit it to Whatsapp as an alarm. So that we can tell who's in your room right away thanks to the photo.
Enable the camera by going to the Preferences menu and selecting the Raspberry Pi configuration option.
Activating the camera and saving the image will allow us to identify who or what triggered the alarm.
import picamera
from time import sleep
camera = picamera.PiCamera()
camera.capture('image.jpg')
When we run our software, the preceding code will take a picture and put it inside the root directory of the script. This image will be used to identify the intruder that has been detected.
When an alarm system is triggered, there is an alert that must sound. We'll use a loudspeaker instead of a buzzer for our alarm system in this scenario. When the motion sensor is activated, we will play an alarm sound.
import pygame
pygame.mixer.init()
pygame.mixer.music.load("alarm.mp3")
pygame.mixer.music.play()
while pygame.mixer.music.get_busy() == True:
continue
As a bridge python software for video game design, Pygame is an excellent choice. Additionally, it provides sights, sounds, and visualizations that can improve the game that is being created.
Graphics for video games can be generated using a variety of libraries that deal with visuals and sounds. It streamlines the entire game workflow and makes it easier for newcomers who wish to create games.
Copy the code above and save it to a file named alarm.py then run it in the terminal.
python alarm.py
Any internet or mobile app's compatibility with several platforms was a major hurdle to overcome when designing it. It used to be possible to build a link between two pieces of software using Bandwidth or Podium or Telnyx or Zipwhip or similar before Twilio was invented. In recent years, though, Twilio has dominated the competition. Twilio has become the preferred communication API for programmers. Twilio will become clearer to you if you stick around for a time.
Developers can use Twilio's API to communicate with each other in a modern way.
When it comes to creating the ideal client experience, developers have a wealth of tools at their disposal in the form of Twilio's APIs, which the company describes as "a set of building blocks."
It is possible to utilize Twilio to communicate with customers via text message (SMS), WhatsApp, voice, video, and email. Your software only needs to be integrated with the API.
Twilio is a provider of end-to-end solutions for integrating voice and data communication. Twilio is already used by over a billion developers and some of the world's most well-known businesses. The Twilio Communication application programming interface enables web and mobile app developers to integrate voice, message, and video conferencing capabilities. This makes it easier for app developers to communicate with one another.
The API provided by Twilio makes it simple and accessible to communicate across the web. Mobile and web applications can use this service to make phone calls as well as send text messages and multimedia messages (MMS).
You might want to learn more about Twilio and how it works. As a result, Twilio allows enterprises to better understand their customers than any other service. Twilio's primary concept is to acquire clients, get to know them, provide for their needs, and keep them coming back.
Twilio has a worldwide operations center that keeps an eye on carrier networks around the clock to ensure that they are operating at peak efficiency. To keep up with the ever-changing traffic patterns, Twilio's skilled communications engineers are on the job all the time.
They employ real-time feedback from several provider services to make smarter routing decisions based on real-time data on the availability of handsets. The key distinction between Twilio and other application programming interface integration networks is that Twilio's data-centric strategy provides customer engagement service.
Managing a contact center in today's business environment is critical to the success of the company. Businesses can use Twilio to manage their interactions with clients and consumers through a central contact center platform.
Before Twilight, sending mass SMS was a difficult task. Now, the Twilio Message application programming interface is widely used to transmit and receive messages, MMS, and OTT communications worldwide. Users can verify whether or not messages have been delivered using the intelligence tracking services.
For healthcare, virtual classrooms, recruiting, and other uses, Twilio's WebRTC and cloud infrastructure components make it easy for developers to create secure, video, and HD audio applications.
Twilio's ability to run and manage marketing campaigns is another noteworthy but still-evolving feature. Users can examine performance numbers, run campaigns, and view design concepts.
As a result of this trend, Twilio has also seen an increase in voice traffic. Any app, website, or service can use Twilio to make phone calls over the PSTN or SIP. It's easy to use Twilio Programmable Voice to make and manage digital calls for any campaign.
The Twilio SendGrip application programming interface eliminates the issue of emails that never make it to their intended recipient's inbox. Customers and clients will receive your emails with Twilio, so you won't have any worries about them not getting them.
You'll never have to worry about online scams or fraud again using Twilio's verify feature. It is continuously validated by SMS, Voice, email, and push alerts continuously.
Advancing solutions and services provided by Twilio allow for global connectivity. As a result of this connectedness, your company can grow with ease.
Developing and testing your app is made simple using Twilio's WhatsApp Sandbox. Your Twilio mobile number must be approved by WhatsApp before you can seek production access.
You'll learn how to connect your phone to the environment in this section. Select Messaging in the Twilio Console and then Take a look at the WhatsApp section by clicking on it. On the webpage, you'll find the information you need to join our sandbox.
The word "join" will be the first character in the code, followed by a two-word phrase chosen at random.
As soon as Twilio receives your message, you should be able to send and receive text messages on your cell phone without any issues.
Please repeat the sandbox application process for each additional mobile device that you wish to use to test the application
Set up a new Python project in the following section.
mkdir python-whatsapp-pic
cd python-whatsapp-pic
We'll need a virtual space for this project because we'll be installing several Python packages.
Open a terminal on your RPI machine and type:
python -m venv venv
source venv/bin/activate
(venv) $ pip3 install twilio
When using a PC running Windows, execute these commands from a command line.
python -m venv venv
source venv\bin\activate
(venv) $ pip3 install twilio
Python's Twilio library will be used to deliver messages via Twilio.
To authenticate with the Twilio service, we must safely store a few critical credentials. To use Twilio we need to register for an account at the official Twilio website. Create a new account with your email and password. They will send a confirmation message to your email inbox for you to confirm the registration. Go ahead and confirm it. You will also have to verify your WhatsApp phone number to proceed.
Setting environment variables can be done by entering the code below into your terminal:
ssh auth token
export TWILIO_ACCOUNT_SID="your account sid"
export TWILIO_AUTH_TOKEN= "your auth token"
after we have exported the credentials in our environment, the next step is to activate the WhatsApp sandbox to receive messages. Go to the develop mode, then select messaging and send a Whatsapp message.
You will see a message directing you to deliver a text to your phone and if Whatsapp is connected to the computer, it will be easier to click on the link that will be provided below to send the message. Send the message that will be displayed on the chat box on your Whatsapp application.
If it works you will see a message shown below:
This number that will be displayed here is the “from” number that we will use in our code and the “to” number is your Whatsapp number.
Copy the following code into your python file.
from twilio.rest import Client
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)
from_whatsapp_number = 'whatsapp:+14155238886'
to_whatsapp_number = 'whatsapp:+254706911425'
message = client.messages.create(body='The engineering project sent your this image!',
media_url='https://www.theengineeringprojects.com/wp-content/uploads/2022/04/TEP-Logo.png',
from_=from_whatsapp_number,
to=to_whatsapp_number)
print(message.sid)
With this now all we have to do is run our app.py program on the terminal.
python app.py
import pygame
import RPi.GPIO as GPIO
import time
import picamera
camera = picamera.PiCamera()
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.IN) #Read output from PIR motion sensor
GPIO.setup(3, GPIO.OUT) #LED output pin
pygame.mixer.init()
pygame.mixer.music.load("alarm.mp3")
import os
from twilio.rest import Client
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)
from_whatsapp_number = 'whatsapp:+14155238886'
to_whatsapp_number = 'whatsapp:+254706911425'
while True:
i=GPIO.input(11)
if i==0: #When output from motion sensor is LOW
print("No intruders",i)
GPIO.output(3, 0) #Turn OFF LED
pygame.mixer.music.stop()
time.sleep(0.2)
elif i==1: #When output from motion sensor is HIGH
print("Intruder detected",i)
GPIO.output(3, 1) #Turn ON LED
pygame.mixer.music.play()
capture image
camera.capture('intruder.jpeg')
#send image to whatsapp
message = client.messages.create(body='The engineering projects program has detected and intruder!',
media_url='https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse4.mm.bing.net%2Fth%3Fid%3DOIP.q1z1XWRn_WAV4oM-Qr2M2gHaGb%26pid%3DApi&f=1',
from_=from_whatsapp_number,
to=to_whatsapp_number)
print(message.sid)
time.sleep(0.2)
GPIO.cleanup()
break
In this article, you learned to build a security system using a motion detector and raspberry pi. We also learned how to set up Twilio to send and receive Whatsapp messages using the Twilio API. This project can be implemented in so many areas therefore it is a good idea for you it plays around with the code and implements some extra features. In the next tutorial, we are going to build a led cube in raspberry pi 4.
Thank you for joining us for yet another session of this series on Raspberry Pi programming. In the preceding tutorial, we integrated a real-time clock with our raspberry pi four and used it to build a digital clock. However, In this tutorial, we will construct your personal Twitter bot using Tweepy, a Py framework for querying the Twitter application programming interface.
You will construct a Response to mentions robot that will post a response to everybody's tweet mentioning it with a certain keyword.
The response will be a photo we will make and put any text over it. This message is a quote you will acquire from a 3rd application programming interface. Finally, we will look at the benefits and drawbacks of bots.
This is what it looks like:
Where To Buy? | ||||
---|---|---|---|---|
No. | Components | Distributor | Link To Buy | |
1 | Raspberry Pi 4 | Amazon | Buy Now |
To continue through this guide, you'll need to have the following items ready:
Ensure you've joined up for Aws Beanstalk before deploying the finished project.
To connect your robot to Twitter, you must create a developer account and build an app that Twitter provides you access to.
Python 3.9 is the current version, although it is usually recommended to use an edition that is one point behind the latest version to avoid compatibility problems with 3rd party modules.
You have these Python packages installed in your local environment.
Tweepy — Twitter's API can be used to communicate with the service.
Pillow — The process of creating an image and then adding words to it
Requests — Use the Randomized Quote Generation API by sending HTTP queries.
APScheduler — Regularly arrange your work schedule
Flask — Develop a web app for the Elastic Beanstalk deployment.
The other modules you will see are already included in Python, so there's no need to download and install them separately.
OAuth authentication is required for all requests to the official Twitter API. As a result, to use the API, you must first create the necessary credentials. The following are my qualifications:
consumer keys
consumers secret
access tokens
access secrets
Once you've signed up for Twitter, you'll need to complete the following steps to generate your user ID and password:
The Twitter developer’s platform is where you may apply to become a Twitter developer.
When you sign up for a developer account, Twitter will inquire about the intended purpose of the account. Consequently, the use case of your application must be specified.
To expedite the approval process and increase your chances of success, be as precise as possible about the intended usage of your product.
The verification will arrive in a week. Build an application on Twitter's developers portal dashboard after Twitter's developers account access has been granted.
Apps can only use authentication details; thus, you must go through this process. Twitter's application programming interface can be used to define an app. Information regarding your project is required:
Your project's purpose or how users will interact with your app should be described in this section.
To begin, navigate to Twitter's apps section of your account and create your user credentials. When you click on this tab, you'll be taken to a new page on which you can create your credentials.
The details you generate should be saved to your computer so they may be used in your program later. A new script called credentials.py should be created in your project's folder and contains the following four key-value pairs:
access_token="XXXXXXX"
access_token_secret="XXXXXXXX"
API_key="XXXXXXX"
API_secret_key="XXXXXXXX"
You can also test the login details to see if everything is functioning as intended using:
import tweepy
# Authenticate to Twitter
auth = tweepy.OAuthHandler("CONSUMER_KEY", "CONSUMER_SECRET")
auth.set_access_token("ACCESS_TOKEN", "ACCESS_SECRET")
api = tweepy.API(auth)
try:
api.verify_credentials()
print("Authentication Successful")
except:
print("Authentication Error")
Authorization should be successful if everything is set up correctly.
Tweepy is a Python module for interacting with the Twitter application programming interface that is freely available and simple. It provides a way for you to interact with the Application programming interface of your program.
Tweepy's newest release can be installed by using the following command:
pip install tweepy
Installing from the git repo is also an option.
pip install git+https://github.com/tweepy/tweepy.git
Here are a few of its most important features:
As part of Tweepy, OAuthHandler class handles the authentication process required by Twitter. As you can see from the code above, Tweepy's OAuth implementation is depicted below.
If you'd want to use the RESTful application programming functions, Tweepy provides an application programming interface class that you can use. You'll find a rundown of some of the more popular approaches in the sections that follow:
Function for tweet
Function for user
Function for user timeline
Function for trend
Function for like
Tweepy model class instances are returned when any of the application programming interface functions listed above are invoked. The Twitter response will be contained here. How about this?
user = api.get_user('apoorv__tyagi')
When you use this method, you'll get a User model with the requested data. For instance:
python print(user.screen_name) #User Name print(user.followers_count) #User Follower Count
You're now ready to begin the process of setting up your bot. Whenever somebody mentions the robot, it will respond with a picture with a quotation on it.
So, to get the quote, you'll need to use an application programming interface for a random quotation generator. If you want to do this, you'll need to establish a new function in the tweetreply.py script and send a hypertext transfer protocol request to the application programming interface endpoint. Python's requests library can be used to accomplish this.
Using Python's request library, you can send hypertext transfer protocol requests. As a result, you could only fixate on the software's interactions with services and data consumption rather than dealing with the complex making of requests.
def get_quote():
URL = "https://api.quotable.io/random"
try:
response = requests.get(URL)
except:
print("Error while calling API...")
This is how they responded:
The JSON module can parse the reply from the application programming interface. You can use import JSON to add JSON to your program because it is part of the standard libraries.
As a result, your method returns the contents and author alone, which you will use. As you can see, here's how the whole thing will work.
def get_quote():
URL = "https://api.quotable.io/random"
try:
response = requests.get(URL)
except:
print("Error while calling API...")
res = json.loads(response.text)
return res['content'] + "-" + res['author']
You have your text in hand. You'll now need to take a picture and overlay it with the text you just typed.
The Pillow module should always be your first port of call when working with images in Python. The Python Pillow imaging module provides image analysis and filetypes support, providing the interpreter with a strong image processing capacity.
Wallpaper.py should be created with a new function that accepts a quote as the argument.
def get_image(quote):
image = Image.new('RGB', (800, 500), color=(0, 0, 0))
font = ImageFont.truetype("Arial.ttf", 40)
text_color = (200, 200, 200)
text_start_height = 100
write_text_on_image(image, quote, font, text_color, text_start_height)
image.save('created_image.png')
Let's take a closer look at this feature.
Image.new() A new photo is created using the given mode and size. The first thing to consider is the style used to generate the new photo. There are a couple of possibilities here: RGB or RGBA. Size is indeed the second factor to consider. The width and height of an image are given as tuples in pixels. The color of the background image is the final option (black is the default color).
ImageFont.TrueType() font object is created by this method. It creates a font object with the desired font size using the provided font file. While "Arial" is used here, you are free to use any other font if you so like. Font files should be saved in the project root folder with a TrueType font file extension, such as font.ttf.
In other words, the text's color and height at which it begins are specified by these variables. RGB(200,200,200) works well over dark images.
Image. Save () created png image will be saved in the root directory due to this process. It will overwrite any existing image with the same name that already exists.
def write_text_on_image(image, text, font, text_color, text_start_height):
draw = ImageDraw.Draw(image)
image_width, image_height = image.size
y_text = text_start_height
lines = textwrap.wrap(text, width=40)
for line in lines:
line_width, line_height = font.getsize(line)
draw.text(((image_width - line_width) / 2, y_text),line, font=font, fill=text_color)
y_text += line_height
A message will be added to the image using the following method in the same script, Wallpaper.py. Let's take a closer look at how this feature works:
Create two-dimensional picture objects with the ImageDraw package.
A solitary paragraph is wrapped in texts using text wrap. Wrap () ensures that each line is no more than 40 characters in length. Output lines are returned in a tally form.
Draw. Text () will draw a text at the provided location.
XY — The text's upper-left corner.
Text — The text to be illustrated.
Fill — The text should be in this color.
font — One of ImageFont's instances
This is what Wallpaper.py look like after the process:
from PIL import Image, ImageDraw, ImageFont
import text wrap
def get_wallpaper(quote):
# image_width
image = Image.new('RGB', (800, 400), color=(0, 0, 0))
font = ImageFont.truetype("Arial.ttf", 40)
text1 = quote
text_color = (200, 200, 200)
text_start_height = 100
draw_text_on_image(image, text1, font, text_color, text_start_height)
image.save('created_image.png')
def draw_text_on_image(image, text, font, text_color, text_start_height):
draw = ImageDraw.Draw(image)
image_width, image_height = image.size
y_text = text_start_height
lines = textwrap.wrap(text, width=40)
for line in lines:
line_width, line_height = font.getsize(line)
draw.text(((image_width - line_width) / 2, y_text),line, font=font, fill=text_color)
y_text += line_height
You've got both the quote and an image that incorporates it in one. It's now only a matter of searching for mentions of you in other people's tweets. In this case, in addition to scanning for comments, you will also be searching for a certain term or hashtags.
When a tweet contains a specific hashtag, you should like and respond to that tweet.
You can use the hashtag "#qod" as the keyword in this situation.
Returning to the tweet reply.py code, the following function does what we want it to:
def respondToTweet(last_id):
mentions = api.mentions_timeline(last_id, tweet_mode='extended')
if len(mentions) == 0:
return
for mention in reversed(mentions):
new_id = mention.id
if '#qod' in mention.full_text.lower():
try:
tweet = get_quote()
Wallpaper.get_wallpaper(tweet)
media = api.media_upload("created_image.png")
api.create_favorite(mention.id)
api.update_status('@' + mention.user.screen_name + " Here's your Quote",
mention.id, media_ids=[media.media_id])
except:
print("Already replied to {}".format(mention.id))
Respond to tweet() The last id is the function's only argument. Using this variable, you can only retrieve mentions produced after the ones you've previously processed. Whenever you initially invoke the method, you will set its value to 0, and then you'll keep updating it with each subsequent call.
mentions_timeline() Tweets are retrieved from the Tweepy module using this function. Only tweets with the last id newer than the provided value will be returned using the first parameter. The default is to show the last 20 tweets. When tweet mode='extended' is used, the full uncut content of the Tweet is returned. Text is shortened to 140 characters if the option is set to "compat."
Create favorite() is used to generate a favorite for every tweet that mentions you in reverse chronological order, starting with the earliest tweet first and working backward from there.
In your case, you'll use update status() to send a reply to this message, which includes the original tweet writer's Twitter handle, your textual information, the original tweet's identification, and your list of multimedia.
There are several things to keep in mind when repeatedly responding to a certain tweet. Simply save the tweet's identification to which you last answered in a text document, tweetID.txt; you'll scan for the newer tweet afterward. The mention timeline() function will take care of this automatically because tweet IDs can be sorted by time.
Now, you'll pass a document holding this last identification, and the method will retrieve the identification from the document, and the document will be modified with a new one at the end.
Finally, here is what the method response to tweet() looks like in its final form:
def respondToTweet(file):
last_id = get_last_tweet(file)
mentions = api.mentions_timeline(last_id, tweet_mode='extended')
if len(mentions) == 0:
return
for mention in reversed(mentions):
new_id = mention.id
if '#qod' in mention.full_text.lower():
try:
tweet = get_quote()
Wallpaper.get_wallpaper(tweet)
media = api.media_upload("created_image.png")
api.create_favorite(mention.id)
api.update_status('@' + mention.user.screen_name + " Here's your Quote",
mention.id, media_ids=[media.media_id])
except:
logger.info("Already replied to {}".format(mention.id))
put_last_tweet(file, new_id)
You'll notice that two additional utility methods, get the last tweet() and put the last tweet(), have been added to this section ().
A document name is required for the function to get the last tweet(); the function putlasttweet() requires the document as a parameter, and it will pick the most recent tweet identification and modify the document with the latest identification.
Here's what the final tweet reply.py should look like after everything has been put together:
import tweepy
import json
import requests
import logging
import Wallpaper
import credentials
consumer_key = credentials.API_key
consumer_secret_key = credentials.API_secret_key
access_token = credentials.access_token
access_token_secret = credentials.access_token_secret
auth = tweepy.OAuthHandler(consumer_key, consumer_secret_key)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
# For adding logs in application
logger = logging.getLogger()
logging.basicConfig(level=logging.INFO)
logger.setLevel(logging.INFO)
def get_quote():
url = "https://api.quotable.io/random"
try:
response = requests.get(url)
except:
logger.info("Error while calling API...")
res = json.loads(response.text)
print(res)
return res['content'] + "-" + res['author']
def get_last_tweet(file):
f = open(file, 'r')
lastId = int(f.read().strip())
f.close()
return lastId
def put_last_tweet(file, Id):
f = open(file, 'w')
f.write(str(Id))
f.close()
logger.info("Updated the file with the latest tweet Id")
return
def respondToTweet(file='tweet_ID.txt'):
last_id = get_last_tweet(file)
mentions = api.mentions_timeline(last_id, tweet_mode='extended')
if len(mentions) == 0:
return
new_id = 0
logger.info("someone mentioned me...")
for mention in reversed(mentions):
logger.info(str(mention.id) + '-' + mention.full_text)
new_id = mention.id
if '#qod' in mention.full_text.lower():
logger.info("Responding back with QOD to -{}".format(mention.id))
try:
tweet = get_quote()
Wallpaper.get_wallpaper(tweet)
media = api.media_upload("created_image.png")
logger.info("liking and replying to tweet")
api.create_favorite(mention.id)
api.update_status('@' + mention.user.screen_name + " Here's your Quote", mention.id,
media_ids=[media.media_id])
except:
logger.info("Already replied to {}".format(mention.id))
put_last_tweet(file, new_id)
if __name__=="__main__":
respondToTweet()
In order to complete the process, you will need to upload your program to a server. Python applications can be deployed using AWS Elastic Beanstalk in this area.
Amazon web service simplifies management while allowing for greater flexibility and control. Your application is automatically provisioned with capacity, load-balanced, scaled and monitored for health using Elastic Beanstalk.
Here is how it's going to work out:
Install Python on the AWS environment
Build a basic Flask app for the bot
Connect to AWS and deploy your Flask app
Use logs to find and fix bugs
After logging into the Aws services account, type and pick "Elastic Beanstalk," then click "setup a New App."
You'll be asked to provide the following information:
Name of the application;
Application's tags;
Environment;
Code of the application
Each AWS Elastic Beanstalk application resource can have up to 50 tags. Using tags, you may organize your materials. The tags may come in handy if you manage various AWS app resources.
Platform branches and versions are automatically generated when Python is selected from the selection for the platform.
Later, you will deploy your app to elastic Beanstalk. Select "sample app" from the drop-down menu and click "new app." For the most part, it should be ready in about a minute or two
Python is used to create Flask, a website development framework. It's simple to get started and use. Flask has no dependencies, making it a more "beginner-friendly" framework for web applications.
Flask has several advantages over other frameworks for building online applications, including:
Flask comes with a debugger and a development server.
It takes advantage of Jinja2's template-based architecture.
It complies with the WSGI 1.0 specification.
Unit testing is made easier with this tool's built-in support.
Flask has a plethora of extensions available for customizing its behavior.
It is noted for being lightweight and simply providing the needed components. In addition to routing, resource handling, and session management, it includes a limited set of website development tools. The programmer can write a customized module for further features, such as data management. This method eliminates the need for a boilerplate program that isn't even being executed.
Create a new Python script and call it application.py, then paste the code below into it while AWS creates an environment.
from flask import Flask
import tweet_reply
import atexit
from apscheduler.schedulers.background import BackgroundScheduler
application = Flask(__name__)
@application.route("/")
def index():
return "Follow @zeal_quote!"
def job():
tweet_reply.respondToTweet('tweet_ID.txt')
print("Success")
scheduler = BackgroundScheduler()
scheduler.add_job(func=job, trigger="interval", seconds=60)
scheduler.start()
atexit.register(lambda: scheduler.shutdown())
if __name__ == "__main__":
application.run(port=5000, debug=True)
Use up scheduler and a flask app to execute a single job() function that will ultimately call the main method in the tweet reply.py script on a minute basis.
As a reminder, the object instance's identifier of the flask app must be "app." For Elastic Beanstalk to work with your application, you must give it the correct name.
Deploy and set up the app to Amazon Web Services.
Your online app's code can include Elastic Beanstalk conf files (.ebextensions) for configuring amazon web services resources and the environments.
The .config script extension is used for YAML files, and these are put in the .ebextensions directory together with the app's code during the deployment process.
Establish a new directory called .ebextensions inside the code folder and add a new file called Python .config. Add the following code:
files:
"/etc/httpd/conf.d/wsgi_custom.conf":
mode: "000644"
owner: root
group: root
content: WSGIApplicationGroup %{GLOBAL}
If you want Elastic Beanstalk to tailor its settings to the app's prerequisites, you'll need to include a list of any external libraries inside a requirements.txt script you produce.
Execute the command below to generate the requirements.txt file using pip freeze
Finally, package up everything for uploading on Elastic Beanstalk with Elastic Beanstalk. The architecture of your project directory should now look like this:
Compress all the files and directories listed here together. Open amazon web services again and select Upload Code.
Once you've selected a zip archive, click "Deploy." When the health indicator becomes green, your app has been successfully launched. "Follow @zeal quote!" if all of the above steps have been followed correctly, they should appear on your website link.
The following steps will help you access the reports of your app in the event of an error:
Logs can be seen under the "Environment" tab in the Dashboard.
After choosing "Request Log," you'll be taken to a new page with an options list. The last lines option is for the latest issues, but the "full log" option can be downloaded if you need to troubleshoot an older error.
To see the most recent log line, click "Download," A new web page will open.
Media platforms entrepreneurs benefit greatly from automation, which reduces their workload while increasing their visibility on Twitter and other media platforms. We may use various strategies to ensure that we're always visible on Twitter.
The benefits of automation are numerous.
There is still a need for human intervention with any automated process.
However, automation should only be a minor element of your total plan. An online presence that is put on autopilot might cause problems for businesses. If your campaign relies on automation, you should be aware of these problems:
Engaging others is all about being yourself. The tweet was written by a person who was using a phone to produce it, based on the bad grammar and occasional errors. Those who aren't in the habit of writing their own Twitter tweets on the fly risk seeming robotic when they send out several automated messages. Tweets written in advance and scheduled to post at specific times appear disjointed and formulaic.
It is possible to appear robotic and dry if you retweet several automated messages. If your goal is to promote user interaction, this is not the best option.
The solution: Don't automate all of your messages. The platform can also be used for real-time interaction with other people. Whenever feasible, show up as yourself at gatherings.
When you plan a message to go out at a specific time, you have no idea what will be trending. If a tragic tale is trending, the tweet could be insensitive and out of context. On Twitter, there is a great deal of outrage. Because everyone is rightly concerned about their collective destiny, there is little else to talk about.
Then, in a few hours, a succession of your tweets surface. Images showing the group having a great time in Hawaii.
While it's understandable that you'd want to avoid coming across as uncaring or unaware in this day and age of global connectivity and quick accessibility of info from around the globe, it's also not a good look. Of course, you didn't mean it that way, but people's perceptions can be skewed.
What to do in response to this: Automatic tweets should be paused when there is a major development such as the one above. If you're already informed of the big news, it's feasible, but it may be difficult due to time variations.
Twitter automation allows your messages to display even if you are not into the service. Your or your company's identity will remain visible to a worldwide audience if you have a global target market.
If an automatic tweet appears before you can brush up on the latest events in your location, follow it up with a real one to show your sympathy. People find out about breaking news through Twitter, a global platform. Few of us have the luxury of remaining in our small worlds. While it's excellent to be immersed in your company's day-to-day operations, it's also beneficial to keep up with global events and participate in Twitter's wider discussion.
People respond to your automatic tweet with congratulations, questions, or pointing out broken links that go unanswered because you aren't the one publishing it; a program is doing it in your stead, not you. Awkward.
Suppose something occurs in the wee hours of the morning. Another tweet from you will appear in an hour. After seeing the fresh tweet, one wonders if Mr. I-Know-It-All-About-Social-Media has even read his reply.
What to do in response to this situation: When you next have a chance to log on, read through the comments and answer any that have been left. Delayed responses are better than no responses. Some people don't understand that we're not all connected to our Twitter 24 hours a day.
As a means of providing customer support, Twitter has become increasingly popular among businesses. It's expected that social media queries will be answered quickly. Impatience breeds on the social web since it's a real-time medium where slow responses are interpreted as unprofessionalism.
On the other hand, Automatic tweets offer the idea that businesses are always online, encouraging clients to interact with the company. Customers may think they're being neglected if they don't hear back.
When dealing with consumer issues, post the exact hours you'll be available.
As soon as somebody insults you, the business, or even just a tweet, you don't want to let those unpleasant feelings linger for too long. We're not referring to trolls here; we're referring to legitimate criticism that individuals feel they have the right to express.
What should you do? Even though you may not be able to respond immediately, you should do so as soon as you go back online to limit any further damage.
Individuals and organizations may use IFTTT recipes to do various tasks, like favorite retweets, follow back automatically, and send automated direct messages.
The unfortunate reality is that automation cannot make decisions on its own. In light of what people may write unpredictably, selecting key phrases and establishing a recipe for a favorite tweet that includes those terms, or even postings published by certain individuals, may lead to awkward situations.
Spam firms or individuals with shady history should not be automatically followed back. Additionally, Twitter has a cap on the number of followers you can follow at any given time. Spammy or pointless Twitter individuals should not be given your followers.
What should you do? Make sure you are aware of what others are praising under your name. Discontinue following anyone or any company that does not exude confidence in your abilities. In our opinion, auto-DMs can work if they are personalized and humorous. Please refrain from including anything that can be found on your profile. They haven't signed up for your blog's newsletter; they've just become one of your Twitter followers. Take action as a result!
Smaller companies and busy people can greatly benefit from Tweet automation. As a result of scheduling Twitter posts, your workload is reduced. A machine programmed only to do certain things is all it is in the end. But be careful not to be lulled into complacency.
Social media platforms are all about getting people talking. That can’t be replaced by automation. Whether you use automation or not, you must always be on the lookout for suspicious activity on your Twitter account and take action as soon as you notice it.
In this article, you learned how to build and publish a Twitter robot in Py.
Using Tweepy to access Twitter's API and configuring an amazon web service Elastic Beanstalk environment for the deployment of your Python application were also covered in this tutorial. As part of the following tutorial, the Raspberry Pi 4 will be used to build an alarm system with motion sensors.
Where To Buy? | ||||
---|---|---|---|---|
No. | Components | Distributor | Link To Buy | |
1 | Jumper Wires | Amazon | Buy Now | |
2 | DS1307 | Amazon | Buy Now | |
3 | Raspberry Pi 4 | Amazon | Buy Now |
Thank you for joining us for yet another session of this series on Raspberry Pi programming. In the preceding tutorial, we implemented a speech recognition system using raspberry pi and used it in our game project. We also learned the fundamentals of speech recognition and later built a game that used the user's voice to play. However, this tutorial will integrate a real-time clock with our raspberry pi four and use it to build a digital clock. First, we will learn the fundamentals of the RTC module and how it works, then we will build a digital clock in python3. With the help of a library, we'll demonstrate how to integrate an RTC DS3231 chip with Pi 4 to keep time.
RTCs are clock units, as the name suggests. There are eight pins on the interface of the RTC IC, the DS1307. An SRAM cell backup of 56 bytes is included in the DS1307, a small clock, and a calendar. Secs, mins, hrs, days, and months are all included in the timer. When a month has fewer than 31 days, the date of the end of this month is automatically shifted.
They can be found in integrated circuits that monitor time and date as a calendar and clock. An RTC's key advantage is that the clock and calendar will continue to function in the event of a power outage. The RTC requires only a small amount of power to operate. Embedded devices and computer motherboards, for example, contain real-time clocks. The DS1307 RTC is the subject of this article.
The primary purpose of a real-time clock is to generate and keep track of one-second intervals.
The diagram to the right shows how this might look.
A program's method, A, is also displayed, which reads a second counter and schedules an action, B, to take place three secs from now. This kind of behavior is known as an alarm. Keep in mind that the secs counter doesn't start and stop. Accuracy and reliability are two of the most important considerations when choosing a real-time clock.
A real-time clock's hardware components are depicted in the following diagram.
An auxiliary crystal and a spectral reference can be used with a real-time clock's internal oscillator, frequently equipped with an interior crystal. The frequency of all clocks is 32,768 Hertz. A TCXO can be used with an exterior clock input since it is extremely accurate and steady.
An input to a Prescaler halves the clock by 32,768 to generate a one-second clock, which is selectable via a multiplexer.
For the most part, a real-time clock features a secs counter with at least thirty-two bits. Certain real-time clocks contain built-in counters to maintain track of the date and time.
Firmware is used to keep track of time and date in a simple real-time clock. The 1 Hertz square waveform from an output terminal is a frequent choice. It's feasible for a real-time clock to trigger a CPU interrupt with various occurrences.
Whenever the whole microcontroller is turned off, a real-time clock may have a separate power pin to keep it running. In most cases, a cell or external power source is attached to this pin's power supply.
Using a 32,768 Hertz clock supply, real-time clock accuracy is dependent on its precision. The crystals are the primary source of inaccuracy in a perfectly-designed signal generator. The internal oscillators and less costly crystals can be employed with sophisticated frequency enhancement techniques for incredibly precise timing. A crystal has three primary causes of inaccuracy.
Tolerances for the initial circuitry and the crystal.
Temperature-related crystal smearing.
Crystallization
Real-time clock accuracy is seen graphically in the figure below:
Using this graph, you can see how a particular concern tolerance changes with increased temperature. The temperature inaccuracy is visible inside the pink track. The quadratic function used to predict the future characteristics of crystals is essential to correct for temperature. Once a circuit board has been built and the temp is determined, an initial error measurement can be used to correct most of the other sources of error.
To acquire an accurate reading, you'll need to adjust to the yellow band. A year's worth of 1 ppm equals 30 seconds of your life. To some extent, the effects of crystallization can't be undone. Even though you're getting older, it's usually just a couple of years.
Pin 1, 2: The usual 32.768-kilohertz quartz crystal can be connected here.
Pin 3: Any conventional 3 Volt battery can be used as an input. To function properly, the battery voltage must be in the range of 2V to 3.5V.
Pin 4: This is the ground.
Pin 5: Streaming data input or output. It serves as the serial interface input and output, and a resistor is required to raise the power to the maximum of 5.5 volts. Irrespective of the current on the VCC line.
Pin 6: Input for the serial timer Data sync is done via the interface clock here.
Pin 7: Driver for the output waveform. A square wave frequency can be generated by connecting a signal to the out pin with the sqwe value set to 1.
Pin 8: The main source of power. Data is written and read whenever the voltage provided to the gadget is within standard limits.
an output waveform that can be programmed
Power-failure detection and switch circuitry automation
Consume less power
Real-time data and time is provided
The rtc is mainly used for writing and reading to and from its registers. Addresses for the rtc registers can be found from zero to 63. If necessary, transitory variables can be stored in random access memory in place of the first eight clock registers. Second, minute, hour, dates, months, and years are all included in the clock's top seven registers. Let's have a look at how DS1307 operates.
The sole purpose of a real-time clock is to record the passage of time. Regular monitoring of the passing of time is critical to the operation of computers and many smaller electronic devices. Although it simply serves one purpose, managing time has many applications and functions. Nearly every computer activity uses measurements taken and monitoring the present time, from the generation of random numbers to cybersecurity.
Kinematic activities or a real-time clock module keep track of time in a classic watch, so how does it work?
The answer is in crystal oscillators, as you would have guessed. The real-time clock uses oscillator pulses in electronic components to keep track of time. Quartz crystals are commonly used in this oscillator, which typically operates at a frequency of 32 kilohertz. Software cleverness is needed to take the processing times and correct any differences related to power supply variations or tiny changes in cycle speed.
Auxiliary tracking is used in real-time clock modules, which uses an exterior signal to lock onto a precise, uniform time. As a result, this does not override the internal measures but complements them to ensure the highest level of accuracy. An excellent example is a real-time clock module that relies on external signals, such as those found on cell phones. Oscillation cycles are counted again if the phone loses access to the outside world.
An object made of quartz crystals has a physical form. As a result, the real-time clock module accuracy can degrade over time due to extreme heat and cold exposure. Many modules include a temperature sensing technique to counteract the effects of temperature variations and improve the oscillator's overall accuracy. There is a wide range of frequencies available in cheap a crystal used in Computer systems. So, the error rate is around 72 milliseconds per hr in real-time. In this case, the following criteria are met:
Start data transfer: Clock and Data lines must be high for a START.
Stop data transfer: In STOP mode, data lines go from low to high while the clock lines remain high.
Data valid: START conditions must be met before a clock signal high period can be used to determine if the transmission line is stable. The info on the channel must be updated when the clock signal is at a lower frequency. Each piece of data has one clock frequency.
Each data transfer begins and ends with START and END conditions, respectively. During the START or STOP circumstances, the data rate bytes that can be sent are not restricted and are set by the master unit. Byte-by-byte, each recipient validates the transmission with a 9th bit.
A real-time clock can be used in systems to correct timing faults in two different ways. The graphic below shows the Prescaler counting the oscillation cycles per the second period.
The advantage of this method is that the time interval between each second is only slightly altered. However, a variable Prescaler and an extra register for storing the prescale counts, and the interval between applications are necessary for this technology to work.
Suppose the real-time clock does not contain a built-in prescaler that can be used to fine-tune the timing. This diagram illustrates a different way of approaching the problem.
The numbers in the rectangles indicate the secs counter. The program continuously tracks and calculates the real-time clock seconds count. A second is added or subtracted to compensate for the cumulative mistake whenever the error reaches 1 second.
This strategy has a drawback: the difference in seconds whenever an adjustment is made might be rather considerable. With this method, you can use it with any real-time clock.
To keep track of the current date and time, certain RTCs use electronic counters. Counting seconds, mins, hours, days, weeks, months, and years and taking leap years into account is necessary. Applications can also keep track of the time and date.
The second counter of a real-time clock can be used to implement this system on a microcontroller.
The proprietary method gets time(), or something similar is commonly used to access the device timer. Using get time() is as simple as taking a second counter and printing out the resulting value. The library handles the remainder of the work to convert this time in secs to the present time of day and date.
If you turn off your RPi, you won't have access to its internal clock. It uses a network clock protocol that requires an internet connection when it is turned on. A real-time timer must be installed in the raspberry pi to keep time without relying on the internet.
First, we'll need to attach our real-time control module to the RPi board. Ensure the Rpi is deactivated or unplugged before beginning any cabling.
Make use of the links in the following table and figure:
The rtc is powered by a 3.3V supply; hence it needs an input of 3.3V. Connect the RTC to the Pi 4 via a communication protocol.
We must first enable I2C in the RPi to use the RTC component.
Open a terminal window and enter the command raspi-config:
sudo raspi-config
Select the Interfacing Option in the configuration tool.
Selecting I2C will allow I2C in the future.
Before rebooting, enable the I2C.
sudo reboot
Confirm the Connections of the RTC. Then using the I2C interface, we can check to see if our real-time clock module is connected to the device.
Ensure your Pi's software is updated before putting any software on it. Defective dependencies in modules are frequently to blame for installation failures.
sudo apt-get update -y
sudo apt-get upgrade -y
If our RPi detects a connection from the real-time clock module, we'll need python-SMBus i2c-tools installed.
On the command line:
sudo apt-get install python-SMBus i2c-tools
Then:
sudo i2cdetect -y 1
Many real-time devices use the 68 address. This indicates that any driver is not using the address. If the address returned by the system is "UU," it indicates that a program actively uses it.
Install Python.
sudo apt-get install python-pip
sudo apt-get install python3-pip
To get the git library, you'll first need to get the git installed on your computer.
$sudo apt install git-all
First, we will have to download the library using the following command in the command line.
sudo git clone https://github.com/switchdoclabs/RTC_SDL_DS3231.git
A file called "RTCmodule" should be created after cloning. The following code should be copied and pasted into a new py file. Please save it.
import time
import SDL_DS3231
ds3231 = SDL_DS3231.SDL_DS3231(1, 0x68)
ds3231.write_now()
while True:
print “Raspberry Pi=\t” + time.strftime(%Y-%m-%d %H:%M:%S”)
print “Ds3231=\t\t%s” % ds3231.read_datetime()
time.sleep(10.0)
We begin by importing the packages we plan to use for this project.
The clock is initialized.
Next, the RPi and real-time clock module times are printed.
Then, execute the program.
$ python rtc.py
In this case, the output should look something like the following.
The write all() function can alter the rtc to run at a different rate than the Pi's clock.
ds3231.write_all(29,30,4,1,3,12,92,True)
import time
import SDL_DS3231
ds3231 = SDL_DS3231.SDL_DS3231(1, 0x68)
ds3231.write_all(29,30,4,1,3,12,92,True)
while True:
print “Raspberry Pi=\t” + time.strftime(%Y-%m-%d %H:%M:%S”)
print “Ds3231=\t\t%s” % ds3231.read_datetime()
time.sleep(10.0)
Time and date are shown to have adjusted on the rtc. With this, we'll be able to use the real-time clock and the package for various projects. However, more setup is required because we'll use the RPi's real-time clock for this project.
, we will configure the rtc on the RPi used in this project. The first thing to do is to follow the steps outlined above.
The real-time clock address is 0x68, so we must use that. Configuration.txt must be edited so that a device tree layer can be added.
sudo nano /boot/config.txt
Please note where your real-time clock chip is in the Pi config file and include it there.
dtoverlay=i2c-rtc,ds1307
or
dtoverlay=i2c-rtc,pcf8523
or
dtoverlay=i2c-rtc,ds3231
After saving and restarting the Pi, inspect the 0x68 address status.
sudo reboot
After reboot, run:
sudo i2cdetect -y 1
Once the "fake hwclock" has been disabled, we can use the real-time clock real hwclock again.
The commands below should be entered into the terminal to remove the bogus hwclock from use.
sudo apt-get -y remove fake-hwclock
sudo update-RC.df fake-hwclock remove
sudo systemctl disable fake-hwclock
We can use our rtc hardware as our primary clock after disabling the fake hwclock.
sudo nano /lib/udev/hwclock-set
Afterward, type in the lines below.
#if [-e/run/systemd/system];then
#exit 0
#if
#/sbin/hwclock --rtc=$dev --systz --badyear
#/sbin/hwclock --rtc=$dev --systz
We can now run some tests to see if everything is working properly.
To begin with, the real-time clock will show an inaccurate time on its screen. To use the real-time clock as a device, we must first correct its time.
To verify the current date, the real-time clock is launched.
$sudo hwclock
It is necessary to have an internet connection to our real-time clock module to synchronize the accurate time from the internet.
To verify the date of the terminal and time input, type in:
date.
Time can also be manually set using the line below. It's important to know that the internet connection will immediately correct it even if you do this manual process.
date --date="May 26 2022 13:12:10"
The real-time clock module time can also be used to set the time of the Rpi.
sudo hwclock –systems
or
sudo hwclock –w
Setting the time on our real-time clock module is also possible using:
sudo hwclock --set --date "Thu May 26 13:12:10 PDT 2022"
Or
sudo hwclock --set --date "26/05/2022 13:12:45"
Once the time has been synchronized, the real-time clock module needs a battery inserted to continue saving the timestamp. Once the real-time clock module has been installed on the RPi, the timestamp will be updated automatically!
Building our application
Next, we'll build a digital clock that includes an alarm, stopwatch, and timer features. It is written in Python 3, and it will operate on a Raspberry Pi using the Tkinter GUI library.
The library includes the Tkinter Graphical interface framework, which runs on various operating systems and platforms. Cross-platform compatibility means that the code can be used on every platform.
Tkinter is a small, portable, and simple-to-use alternative to other tools available. Because of this, it is the best platform for quickly creating cross-platform apps that don't require a modern appearance.
Python Tkinter module makes it possible to create graphical user interfaces for Python programs.
Tkinter offers a wide range of standard GUI elements and widgets to create user interfaces. Controls and menus are included in this category.
Tkinter has all of the benefits of the TK package, thanks to its layered design. When Tkinter was first developed, its Graphical interface toolkit had already had time to evolve, so it benefited from that experience when it was created. As a result, Tk software developers can learn Tkinter very quickly because converting from Tcl/Tcl to Tkinter is extremely simple.
Because Tkinter is so user-friendly, getting started with it is a breeze. The Tkinter application hides the complex and detailed calls in simple, understandable methods. When it comes to creating a working prototype rapidly, python is a natural choice. Because of this, it is anticipated that its favorite Graphical interface library will be applied similarly.
Tkinter-based Py scripts don't require any running changes on a different platform. Any environment that implements python can use Tkinter. This gives it a strong benefit over many other competitive libraries, typically limited to a single or a handful of operating systems. Tkinter, on the other hand, provides a platform-specific look and feel.
Python distributions now include Tkinter by default. Therefore, it is possible to run commands using Tkinter without additional modules.
Tkinter's slower execution may be due to the multi-layered strategy used in its design. Most computers are relatively quick enough to handle the additional processes in a reasonable period, despite this being an issue for older, slower machines. When time is of the essence, it is imperative to create an efficient program.
Import the following modules.
from Tkinter import *
from Tkinter. ttk import *
import DateTime
import platform
We are now going to build a Tkinter window.
window = Tk()
window.title("Clock")
window.geometry('700x500')
Here, we've created a basic Tkinter window. "Clock" has been officially renamed. And make it a 700X500 pixel image.
Tkinter notebook can be used to add tab controls. We'll create four new tabs, one for each of the following: Clock, Alarm, Stopwatch, and Timer.
tabs_control = Notebook(window)
clock_tab = Frame(tabs_control)
alarm_tab = Frame(tabs_control)
stopwatch_tab = Frame(tabs_control)
timer_tab = Frame(tabs_control)
tabs_control.add(clock_tab, text="Clock")
tabs_control.add(alarm_tab, text="Alarm")
tabs_control.add(stopwatch_tab, text='Stopwatch')
tabs_control.add(timer_tab, text='Timer')
tabs_control.pack(expand = 1, fill ="both")
We've created a frame for every tab and then added it to our notebook.
We are now going to add the clock Tkinter components. Instead of relying on the RPi to provide the date and time, we'll use the rtc module time and date instead.
We'll include a callback function to the real-time clock module in the clock code to obtain real-time.
def clock():
date_time = ds3231.read_datetime()
time_label.config(text = date_time)
time_label.after(1000, clock)
Timestamps are retrieved from the DateTime package and transformed to Am or Pm time. This method must be placed after Tkinter's initialization but before the notebook.
We'll design an Alarm that will activate when the allotted time has expired in the next step.
get_alarm_time_entry = Entry(alarm_tab, font = 'calibri 15 bold')
get_alarm_time_entry.pack(anchor='center')
alarm_instructions_label = Label(alarm_tab, font = 'calibri 10 bold', text = "Enter Alarm Time. Eg -> 01:30 PM, 01 -> Hour, 30 -> Minutes")
alarm_instructions_label.pack(anchor='s')
set_alarm_button = Button(alarm_tab, text = "Set Alarm", command=alarm)
set_alarm_button.pack(anchor='s')
alarm_status_label = Label(alarm_tab, font = 'calibri 15 bold')
alarm_status_label.pack(anchor='s')
Set the alarm with the following format: HH: MM (PM/AM). For example, the time at which 01:30 PM corresponds to 1:30 p.m. As a final step, a button labeled "Set Alarm Button." In addition, the alarm status label indicates if the alarm has been set and shows the current time.
The set alarm button will trigger an alarm when this method is called. Replace Clock and Notebook setup functions with this one.
def alarm():
main_time = datetime.datetime.now().strftime("%H:%M %p")
alarm_time = get_alarm_time_entry.get()
alarm_time1,alarm_time2 = alarm_time.split(' ')
alarm_hour, alarm_minutes = alarm_time1.split(':')
main_time1,main_time2 = main_time.split(' ')
main_hour1, main_minutes = main_time1.split(':')
if int(main_hour1) > 12 and int(main_hour1) < 24:
main_hour = str(int(main_hour1) - 12)
else:
main_hour = main_hour1
if int(alarm_hour) == int(main_hour) and int(alarm_minutes) == int(main_minutes) and main_time2 == alarm_time2:
for i in range(3):
alarm_status_label.config(text='Time Is Up')
if platform.system() == 'Windows':
winsound.Beep(5000,1000)
elif platform.system() == 'Darwin':
os.system('say Time is Up')
elif platform.system() == 'Linux':
os.system('beep -f 5000')
get_alarm_time_entry.config(state='enabled')
set_alarm_button.config(state='enabled')
get_alarm_time_entry.delete(0,END)
alarm_status_label.config(text = '')
else:
alarm_status_label.config(text='Alarm Has Started')
get_alarm_time_entry.config(state='disabled')
set_alarm_button.config(state='disabled')
alarm_status_label.after(1000, alarm)
In this case, the module's time is taken and formatted in this way in case the If the time provided matches the time stored, it continues. In this case, it beeps following the operating system's default chime.
As a final step, we'll add a stopwatch to our code.
To complete our timer, we'll add all Tkinter elements now.
stopwatch_label = Label(stopwatch_tab, font='calibri 40 bold', text='Stopwatch')
stopwatch_label.pack(anchor='center')
stopwatch_start = Button(stopwatch_tab, text='Start', command=lambda:stopwatch('start'))
stopwatch_start.pack(anchor='center')
stopwatch_stop = Button(stopwatch_tab, text='Stop', state='disabled',command=lambda:stopwatch('stop'))
stopwatch_stop.pack(anchor='center')
stopwatch_reset = Button(stopwatch_tab, text='Reset', state='disabled', command=lambda:stopwatch('reset'))
stopwatch_reset.pack(anchor='center')
The stopwatch method is activated by pressing the Start, Stop, and Reset Buttons located below the Stopwatch Label.
Stopwatch counters will be included in the next section. Two stopwatch counters will be added first. Tkinter Initialization and the clock's method should be added to the bottom of the list.
stopwatch_counter_num = 66600
stopwatch_running = False
The stopwatch is described in these words. Adding a Stopwatch Counter is the next step. Add it to the bottom of the alarm clock and the top of the notebook's setup procedure.
def stopwatch_counter(label):
def count():
if stopwatch_running:
global stopwatch_counter_num
if stopwatch_counter_num==66600:
display="Starting..."
else:
tt = datetime.datetime.fromtimestamp(stopwatch_counter_num)
string = tt.strftime("%H:%M:%S")
display=string
label.config(text=display)
label.after(1000, count)
stopwatch_counter_num += 1
count()
The counter controls the stopwatch on the stopwatch. At the rate of one second each second, the Stopwatch counter is incremented by 1.
The stopwatch method, which is invoked by the Stopwatch Controls, is now complete.
if work == 'start':
global stopwatch_running
stopwatch_running=True
stopwatch_start.config(state='disabled')
stopwatch_stop.config(state='enabled')
stopwatch_reset.config(state='enabled')
stopwatch_counter(stopwatch_label)
elif work == 'stop':
stopwatch_running=False
stopwatch_start.config(state='enabled')
stopwatch_stop.config(state='disabled')
stopwatch_reset.config(state='enabled')
elif work == 'reset':
global stopwatch_counter_num
stopwatch_running=False
stopwatch_counter_num=66600
stopwatch_label.config(text='Stopwatch')
stopwatch_start.config(state='enabled')
stopwatch_stop.config(state='disabled')
stopwatch_reset.config(state='disabled')
We will now create a timer that rings when the timer has expired. Based on the stopwatch, it deducts one from the counter rather than adding 1.
The timer component will now be included in Tkinter.
timer_get_entry = Entry(timer_tab, font='calibiri 15 bold')
timer_get_entry.pack(anchor='center')
timer_instructions_label = Label(timer_tab, font = 'calibri 10 bold', text = "Enter Timer Time. Eg -> 01:30:30, 01 -> Hour, 30 -> Minutes, 30 -> Seconds")
timer_instructions_label.pack(anchor='s')
timer_label = Label(timer_tab, font='calibri 40 bold', text='Timer')
timer_label.pack(anchor='center')
timer_start = Button(timer_tab, text='Start', command=lambda:timer('start'))
timer_start.pack(anchor='center')
timer_stop = Button(timer_tab, text='Stop', state='disabled',command=lambda:timer('stop'))
timer_stop.pack(anchor='center')
timer_reset = Button(timer_tab, text='Reset', state='disabled', command=lambda:timer('reset'))
timer_reset.pack(anchor='center')
Get timer provides guidance that explains how to set the timer. HH:MM: SS, For instance, 01:30:40 denotes a time interval of one hour, thirty minutes, and forty secs. It then has a toggle that calls the Timer method, which has a start, stop, and reset button.
To begin, we'll insert 2 Timer counters. The two lines of code below the stopwatch and the clock method below should be added.
timer_counter_num = 66600
timer_running = False
In this section, we learn more about the "Timer" feature. Next, we'll implement the Timer Counter feature. In between the Stopwatch method and Notebook Initiation, put it.
def timer_counter(label):
def count():
global timer_running
if timer_running:
global timer_counter_num
if timer_counter_num==66600:
for i in range(3):
display="Time Is Up"
if platform.system() == 'Windows':
winsound.Beep(5000,1000)
elif platform.system() == 'Darwin':
os.system('say Time is Up')
elif platform.system() == 'Linux':
os.system('beep -f 5000')
timer_running=False
timer('reset')
else:
tt = datetime.datetime.fromtimestamp(timer_counter_num)
string = tt.strftime("%H:%M:%S")
display=string
timer_counter_num -= 1
label.config(text=display)
label.after(1000, count)
count()
The Timer counter controls the timer. Timer counter-variable num is decreased by one each second.
def timer(work):
if work == 'start':
global timer_running, timer_counter_num
timer_running=True
if timer_counter_num == 66600:
timer_time_str = timer_get_entry.get()
hours,minutes,seconds=timer_time_str.split(':')
minutes = int(minutes) + (int(hours) * 60)
seconds = int(seconds) + (minutes * 60)
timer_counter_num = timer_counter_num + seconds
timer_counter(timer_label)
timer_start.config(state='disabled')
timer_stop.config(state='enabled')
timer_reset.config(state='enabled')
timer_get_entry.delete(0,END)
elif work == 'stop':
timer_running=False
timer_start.config(state='enabled')
timer_stop.config(state='disabled')
timer_reset.config(state='enabled')
elif work == 'reset':
timer_running=False
timer_counter_num=66600
timer_start.config(state='enabled')
timer_stop.config(state='disabled')
timer_reset.config(state='disabled')
timer_get_entry.config(state='enabled')
timer_label.config(text = 'Timer')
If the task is started, this method retrieves the Timer input text and formats it before setting the Timer counter and calling the Timer counter to set the clock running. The timer is set to "False" if programmed to Stop. The counter is set to 666600, and running is configured to "False."
Finally, here we are at the end of the project. Finally, add the code below to start Tkinter and the clock.
clock()
window.main loop()
It will open the Tkinter and clock windows.
Stopwatch
32-Bit Second Counter Problems
Even while this counter can operate for a long period, it will eventually run out of memory space. Having a narrow count range can pose problems.
Management of the streetlights
Lighting Street Management System is a one-of-a-kind solution that regulates the automatic reallocation of lights in public spaces. It can measure electric consumption and detect tampering and other electrical situations that hinder the most efficient use of street lights. IoT-based automated streetlight management systems are intended to cut electricity usage while decreasing labor costs through precession-based scheduling. Streetlights are a vital element of any town since they improve night vision, offer safety on the streets, and expose public places, but they waste a significant amount of energy. Lights in manually controlled streetlight systems run at full capacity from sunset to morning, even if there is adequate light. High reliability and lengthy stability are guaranteed by this method. This task is carried out using computer software. When compared to the previous system, the new one performs better. Automated On and Off processes are based on the RTC module for the time frame between dawn and dusk of the next day. Manual mode was removed because of human flaws and difficulties in timely on and off activities, which necessitated the relocation of certified electricians over wide distances and caused time delays. Using an Internet of things controlled from a central command center and portable devices helps us avoid these delays while also identifying and correcting faults, conserving energy, and providing better services more efficiently.
This tutorial teaches the mechanics of a real-time clock and some major applications in real life. With ease, you can integrate this module into most of your projects that require timed operations, such as robot movements. You will also understand how the RTC works if you play around with it more. In the next tutorial, we will build a stop motion movie system using Raspberry pi 4.
Rental property management is a potentially lucrative strategy – one that can supply you with a steady stream of passive income and, if you do things right, set you up for long-term accumulation of wealth.
But at the same time, the day-to-day process of managing properties can be a headache. You’ll be responsible for overseeing the property, responding to maintenance requests, collecting rent, and dealing with problematic tenants.
Is it worth designing an automation system to handle some of these tasks on your behalf? How much value do you stand to gain?
Let's start by talking about some of the reasons why automation is so valuable.
Many property owners choose to hire a property manager to take care of the property management side of things, from screening tenants to managing evictions. That's because most people want their rental properties to be a passive income source, requiring little to no effort on their part. Automation allows you to take this to the next level, reducing your manual effort even further and possibly allowing you to forgo the necessity of hiring a property manager to begin with.
Another benefit of automation is process consistency. If you automate messages and follow-ups, you'll never have to worry about forgetting a message. Your tenants will know exactly what to expect, and you'll be much more successful in navigating this financial strategy.
Accurate and consistent record keeping is an absolute must in the world of rental property management. Not only is it important for your personal accounting, but it's also important for tax planning. Automating the process of activities like accepting rent payments and producing reports can make it much easier to maintain accurate and consistent records.
Are there any drawbacks to attempting to automate your rental property management?
Creating an automation algorithm is faster now than it’s ever been. But it still might be an uphill battle if you're designing your own automated systems from scratch. If you only have one rental property, or if this is only a temporary pursuit for you, it may not be worth that initial time investment.
If you're not designing your own solution, you'll be required to buy one that's already in existence. Most rental property automation platforms are relatively inexpensive, but you'll still have an upfront monetary expenditure to plan for.
Lazy coding and overlooked variables can lead to potential mistakes and inaccuracies. Your automated systems will run exactly the way you tell them to – but sometimes, that can work against you.
If you're using automated messages to handle most of the communications with your tenants, they may perceive these communications as impersonal. Relationship management isn't your primary responsibility, but this is still a variable worth considering.
For most rental property managers, the ideal solution is to find an existing product on the market that can handle your automation needs.
If you're shopping for a solution, be sure to consider:
Think about all the core features you're going to need and make sure every solution you seriously consider contains them. Do you want to automate the process of collecting tenant applications? What about collecting rent? Should the system also handle maintenance and repair requests? What features should be available to you, as the property manager?
Always take a look at the history of this product, including the reviews and testimonials left behind by people who have used it in the past. Do people find this product to be reliable? Does it solve their needs efficiently?
The easier the tool is to use, the better – both for you and your tenants.
Accounting for taxes is often a major pain for rental property owners. If you want to make it easier on yourself, you need to have a solution with organized, automated, and efficient recordkeeping.
Finally, consider the pricing. This is especially important if you're also debating whether or not you should build your own tool. Could you build something similar for less?
Of course, it's also possible to design and build your own automated solution to rental property management. This can be time-consuming, and there are some risks involved, but the finished product can be extremely valuable and you'll probably have fun building it in the process.
Automation is the right move for most rental property managers, but it doesn't always take the same form. Think carefully about the automation solutions you incorporate into your financial strategies and always plan with the future in mind.
Hello friends, after completing that basic part of ladder logic programming, let us today go through one topic which is not essential to know to complete a PLC ladder program but it is important t have our code readable program and reusable pieces of code. That could happen by using what so-called a subroutine. So what is a subroutine?
Well, it is a piece of code that includes a few rungs to perform specific tasks. that piece of code can be reused numerous times through the program when we need to call it for performing that task. That subroutine enables us to structure our code like building blocks so that the program will be readable very easy and also reusable later in other projects. The idea of dividing the program into routines to apply the divide and conquer technique is very crucial to ease the coding of your program especially when it comes to the large-scale program which is the common cause in the best industry practice.
Each routine achieves one specific task and they are integrated to accomplish the whole mission. By programming in that way, the code is more readable and reusable meaning that one routine could be called many times instead of keeping repeating the lines of code or ladder rungs everywhere we need it. In this tutorial, we are going to be very familiar with subroutine-based programming including different ways to call a subroutine and the instructions that are used for handling subroutines. And yes we are going to practice examples that program that subroutines in ladder logic so let's get started.
Routines can be classified into two main types: the calling routines that call subroutines. And routines that are being called. Figure 1 shows the very typical scenario of calling one subroutine. It shows the scenario when the calling routine reaches the calling instruction when the subroutine is being called with the value of the parameter passed by the calling routine and then the subroutine has a return instruction to take the execution to the following instruction of the calling instruction. So you can imagine the calling instruction is in the calling routine which is mostly the main program and the called subroutine is responsible to return the control or the execution point to the instruction next to the calling instruction.
There are two main ways for passing parameters between the calling routine and the subroutine that is being called. The two ways are calling by value and calling by reference. In the calling by value method, the calling routine passes a copy of the original parameters so the called subroutine works on a copy. Therefore, there are no changes could happen to the original parameters in the calling routine. In contrast, in the second method which is called call by reference, the parameters are shareable between the calling routine and the subroutine that is being called. So, changes happened to the parameters but the called subroutine reflected on the original ones. Figure 2 depicts a case scenario of the two types of passing parameters. In that very example, the main routine calls subroutine “Call_Val” to apply an increment of operand “Op1” passing the parameter Op1 using the method “calling by value” while it calls “Call_ref” to do the same process but in that case, it passes parameter Op1 by using the method of “calling by reference”. As you can see, in the case it uses the “calling by value” method, it does not change the value of parameter Op1 because it uses a copy of the parameter and increments that copy not the original parameters. On the other hand, when it has used the other method, “calling by reference”, to increment the same parameter Op1, it does change the original operand because it uses a reference that points to the original parameter address. In another word, calling a subroutine based on a call by value works on a copy of the parameters and does not change the original variables while calling by reference works on the originally passed parameters so it does change the parameters. The advantage of calling by reference is saving the memory as it does not need an instance of the variables or a separate data block. On the other hand, calling by value needs to have a separate data block to include that copy of passing parameters. However, it can be called many times with a separate copy without any conflicts.
Figure 3 shows the program sequence when using multilevel branching using subroutines. For example, the main module keeps carrying out the network net1, and net2, and it calls the subroutine “Sub x” in-network net3. Then subroutine “sub x ” starts executing from network net1 to net3 at which, it calls subroutine “Sub y”. Then subroutine “Sub y” carries out starting from the network “net 1”, and network “net 2” calls subroutine “Sub a”. You can notice subroutine “Sub a” returns to the calling routine “Sub y” which returns to subroutine to its calling routine “Sub x” which returns to its calling routine which is the main routine. So, you can notice how many levels of subroutine calls? Yes, they are a lot. But, it is recommended to be as much as needed for two reasons. First, many branching causes some headaches in processing in terms of memory and time. Memory is represented in the data block that is needed for each subroutine every single branching or subroutine calling and time is represented in extra instructions of calling and returning and stacking data related to the called routine and the returning addresses.
There are two main instructions used for calling a subroutine and returning to the calling routine. Figure 4 shows the network rung that calls a subroutine called “Auto Mode”. It is going to call the subroutine at any time when the “System OK” memory contact MB180 is true. So I hope you can feel now how your program is more organized and readable when you go through the main program and easily can catch what the program does by reading the names of the called subroutines. Exactly, having a meaningful name for subroutines is very important to give the advantage of the readability of your program. So, my friends please make sure you chose a purposeful name for your subroutines.
Also fig. 5 shows the network rung that represents the returning command to the calling routine. It shows when the alarm is true represented by memory contact MB32 and pump status “Stop Pump” represented by memory bit64, the return command will be enabled for returning the execution point to the network just next to the calling network in the calling program. For example, if the calling network is at rung number 3, then the return command in the subroutine will return the execution at rung number 4 in the calling routine. By the way, in most cases of ladder logic programming, you might not find a return instruction because it is inherently performed by completing the called subroutine but we just include it here as in fig. 5 to show up how the process of calling a subroutine and returning to the calling routine.
Figure 6 depicts the whole image of the scenario of calling one subroutine. In rung 3, a subroutine called “Auto mode” is being called by having the memory contact MB18 true. Then after that subroutine, “Auto mode” is completed it returns to the calling routine at the next rung to the calling rung which is in this case example rung number 4. As we stated earlier, you can notice that there are now returning instructions but automatically, the called subroutine returns to the calling routine at the instruction just next to the calling instruction.
My friends, let us go to our lab as usual and do some hands-on practicing subroutine using the simulator. But before going further in practice subroutine we want to elaborate on the different types of subroutines in Siemens programming. Table 1 compares the subroutine implementation based on function and function block. It shows that subroutine can be implemented by either function FC or function block FB. And both ways can use input, output, and in-out parameters.
FC does not use static data or data block (DB) while FB uses DB and passing parameters by making an instance of the variables which is calling by value. FC passes the parameter by pointing to the address of the variable which calling by reference technique.
Table 1: Comparison between FC and FB subroutine in Siemens
Characteristic |
FC |
FB |
Can be used as a subroutine |
Yes |
Yes |
Can use parameters for Inputs, Outputs, and Input |
Yes |
Yes |
Can use temporary variables |
Yes |
Yes |
Can use static variables (with remanence) |
No |
Yes |
Need an auxiliary (instance) DB for each call |
No |
Yes |
Parameters are passed as the address for internal use |
Yes |
No |
Parameters are copied to/from a DB (instance) for internal use |
No |
Yes |
Can call internally a FB or FC |
Yes |
Yes |
Can be called for a FB or FC |
Yes |
Yes |
Can call a FB as multi-instance |
No |
Yes |
Can be called without filling all parameters |
No |
Yes |
Again, there are two ways of calling a subroutine in Siemens ladder programming as shown in fig. 7. We have developed a sample ladder program that calls a simple subroutine to add two input operands. In the first rung, it uses function “FC1” called “fun_A” and in the second rung, it utilizes a function block FB1 called “FB_A” as you can notice function block uses a data block instance for passing a copy of the operands while function FC does not use a data block and uses the address of the input and output parameters.
Figure 8 shows the function block FB_A. the function block has two input operands which are “op1” and ‘’op2” and one output operand which is “sum”.
Because the function block passes parameters as copies or instances, fig. 9 shows the related data block DB1 which contains the parameters of the function block. It is composed of many structures for holding input, output, input, and static data as well.
On the other hand, the function uses the addresses of the parameters. Therefore, it does not need a data block as shown in fig. 10. It uses many structures to pass input, output, input, temporary, and constant data types.
Now let’s check the work with the simulator. Figure 11 shows the results of simulating the calling subroutine based on function FC_A that adds two static operands showing the calling path from the main organization block to the function.
On the other hand, calling a subroutine based on a function block uses an instance of parameters in a data block as shown in fig. 12. This means another instance of data is used every time we called that subroutine while using the function it is referencing the same variables at the same addresses.
Thank you guys for following me up to this very point of our tutorial and being very confident by knowing the subroutine you now are all set to write an organized program and readable and reusable piece of code using ladder logic programming. the next time we are going to talk about one of the most important topics in PLC programming which is master reset control showing what is it about and its importance for PLC and control project and for sure will practice with our simulator lab. So be ready and let’s meet in the next tutorial to enjoy learning and practice the PLC ladder programming series.
Hello friends, I hope you are doing very well. Today we are going to learn and practice the master control reset (MCR)! So what is that MCR? Well! This is a tool you might use to control a group of devices with one push button for performing fast emergency responses with one click for a group of devices in one zone. In another word, you divide the program into zones and put this zone between a master control to control their operation as one unit by one contact. This technique is useful for applying emergence stops and also protecting some equipment by applying a safety restriction to not operate when that condition is in effect.
Figure 1 shows the master control relay in a ladder logic showing a couple of rungs between the master control and master control reset to be controlled as one zone by master control. for example, input 1 enables the master control relay M100 which is the only way to relay the hotline of power to rungs 2 and 3 as shown in the figure. When input 1 is on, the master control relay is energized. Therefore, input 2 and input 3 can energize output 1 and output 2 respectively. But, if input 1 is off, the master control relay is off. Therefore, rungs 2 and 3 are disconnected from the power. Therefore, even if input 2 and input 3 are on, outputs 1 and 2 will not energize because of a missing connection to power via master control relay M100. To sum up, there is a zone that contains a couple of rungs, these rungs are not enabled without master control enabled. Also, fig. 1 shows the structure of the master control and master control reset to have one rung to enable the master control relay and one rung at the end to represent the master control reset and declare the end of the zone that is under master control. and the code or rungs that are located between the master control and the master control reset is the zone that we need to control its running based on master control. So, if the master control is not true, the code in that zone between the master control and the master control reset will be bypassed and the next instruction after the master control reset instruction will be executed.
So we want to go further in demonstrating the master control reset by a practical example from real life. Figure 3 shows a practical example of real-life in the industry of which automatic bottle filling process. So what does master control have to do with such a process? Will! That is a good question because it tells me you understand master control reset and are with me on the same page. So, as you can see, there is the start and stop pushbuttons and we need to use master control to control starting and stopping the whole process regardless of the status of individual inputs and sensors. by having such control, we can stop the process in any emergency case or for doing maintenance. The sequence of the process is to start moving the conveyor by hitting the start push button. The conveyor keeps running until the proximity sensor comes ON. At that time, the valve will open for 5 seconds and then the conveyor continue moving again after 5 seconds and continue for 3 bottles repeating the same process. But if there is an emergency happens, there should be a way to stop the process including moving the conveyor, and opening the valve even if all conditions to do are met. Well done! You are correct, master control and master control reset should bracket the process to be enabled and disabled when that emergency comes to happen.
Master control and master control reset are the same concepts. However, a few differences you can notice in ladder logic from one plc brand to another. For example, Fig. 4 shows the ladder logic code of a master control reset in Mitsubishi PLC. You can notice the same concept has been applied. A zone of a couple of rungs is surrounded by master control and master control reset instructions based on master control relay M100. Input 1, X400 enables the master control relay M100. And rungs 2 and 3 are included in the zone under master control.
On the other hand, master control and master control reset look a little bit different in Allen-Bradley as shown in fig.5. However, you can notice the same concept is applied by having the zone that includes a couple of rungs between the master control relay and master control reset for enabling or disabling that zone based on the logic and situation.
Also, Siemens shows a few differences in ladder logic of master control as shown in Fig.6. however, the same concept is thereby enclosing the code to be controlled in a zone preceded by enabling to master control relay and followed by a master control reset to clear that master control and show the end of the controlled zone.
Guys, it is now the time to enter our lab and enjoy practicing the master control and master control reset by using our simulator as usual for validating our understanding of what we have gone through in this tutorial on ladder logic programming. In the example simulated below and shown in fig. 7, we have designed simple master control and master control rest to have master control of running of Q0.0. you can notice that, despite input I0.1 being true, Q0.0 is not energized because master control is not enabled or in off status. So what happens if we enable master control by switching on input I0.0?
Yes, you are correct! The output Q0.0 will now work after enabling the master control by turning input I0.0 on as shown in Fig.8.
Let me thank you guys for following up until this point and because your knowledge of ladder logging is getting increase every single tutorial, I would like to announce that, the next tutorial will be about one of the very advanced levels of ladder logic programming which is for expert and I thought you are now. The sequencer output instruction in ladder logic is our topic for the next tutorial in which we will learn and practice how to, massively output data sequentially to outputs. Please do not worry if that is not clear for now and just be there to go through it step by step and enjoy practicing one topic for an expert ladder programmer.
Hello, readers. Welcome to another lecture on signals and systems where, on the previous day, we studied the transforms. A Z transform is used to change the domain of a signal or function. It is used to convert the signal from the time domain into the z plane. Now we are going a little deep into the discussion. Have a quick promo of the topic of today:
What are the properties of z transform?
What is the unit impulse of z transform?
What is the unit ramp of z transform?
What is the difference equation and how is it related to the z transform?
What are some important applications of z transform?
We’ll go through each of these topics in detail, so stay with us to learn about all of them.
Till now, we have seen the introduction of z transform along with some basic information. It's time to discuss some properties of z transform in this lecture. We always mention the properties of the topic if possible to clearly describe the nature and workings of that particular topic. It will be correct to say that while discussing the properties of a mathematical tool, we provide you with a wide domain of learning and experimenting about that particular topic.
The z transform is always linear. It means, if we have two statements and apply the z transform individually on both of them, then we always get the linear results. Mathematically,
If
F(z) = Z{fn}
and
G(z) = Z{gn}
Then
Z{afn + bgn} = aF(z) + bG(z)
When we talk about the time shifting property of z transform, we come to know that while passing through the time shifting process while we are performing the z transform, we get the following results:
If we take n-m instead of n in the property given above, we’ll find the results in which the signal in the z plane multiplies with the z complex number having the exponential power equal to the m with a negative sign with it.
The time reversal property of z transform states that if we have the following condition:
x(n)⟷Z.TX(Z)x(n)⟷Z.TX(Z)
Then after applying the z transform, we will get
x(−n)⟷Z.TX(1/Z)
You can see that after the application of z transform, we get the z in that is present in the denominator of the resultant X value. Therefore, this property is named the reversal property.
Convolution is an important process in signals and systems and we have also read great detail about it in this course. While merging the concept of convolution and z transform, we get to know that if,
x(n)⟷Z.TX(Z)x(n)⟷Z.TX(Z)
and
y(n)⟷Z.TY(Z)y(n)⟷Z.TY(Z)
Then we can easily guess that
x(n)∗y(n)⟷Z.TX(Z).Y(Z)x(n)∗y(n)⟷Z.TX(Z).Y(Z)
Keep in mind, the convolution is not same as the multiplication of the signal. It is the process in which two signals are overlapped in such a way that they form the third signal that has a mix of the properties of both the signals that are convoluted.
If you have studies about the convolution, you will surely have the information of correlation as well. This property of z transform states that if we have
x(n)⟷Z.TX(Z)x(n)⟷Z.TX(Z)
and
y(n)⟷Z.TY(Z)
Then after the process of correlation while you are using z transform, you will get the following results:
x(n)⊗y(n)⟷Z.TX(Z).Y(Z−1)
If you are new to the correlation then you must gpo to our previous lecture about correlation where we have descried this briefly.
Based on different experiments and studies, a theorem has been introduced and the initial theorem is one of them. This theorem is used to find the initial value of of the statement without using the inverse z transform and it states that:
x(0)=limz→∞X(z)
This theorem is only applicable to casual signals.
This is another theorem that is usually introduced while discussing the initial value theorem. It states that if:
x(∞)=limz→1[z−1]X(z)
It is also used in cases where you do not want to apply the inverse z transform and use the alternative way.
The unit impulse function is used in physics and mathematics. It indicates the function that has zero width and a unit area that is the area of value 1. Unit step function using z transform is simple and easy and it results in the sequential series. Suppose we have the following function:
Then after applying the z transform of this statement, we get a geometric series. Recall that geometric series is the one in which every value is the result of the multiplication of the previous value with a particular constant depending upon the condition given for the geometric constant.
A unit ramp function is one that after the implementation of different operations, provides a graph that has a straight slope. Such functions are widely used in the formation of complex operations. While using the z transform, it is defined as:
x(n)=r(n)={n For n≥0 0 For n<0 }
Then we can solve this by using the procedure of z transform as:
The multiplicative property of z transform is also called the complex convolution property of z transform. It is because, it results by the multiplication of two signals of time domain that corresponds to the complex number of z domain. You can have the idea of this property with the help of the code given nex that is the extension of the code that we have worked with before.
Code |
Output |
syms n; f=sin(2*n) F=ztrans(f) G=iztrans(F) H=F*G |
|
The difference equation is somehow a special case in the equation and the z transform is used to solve this in an effective way. It is defined as:
“The difference equation is the special type of equation in which there exists a difference (minus operation) of different variables. These show the relationship between an independent variable and the consecutive difference of a dependent variable.
These are not complex equations, and usually they depend upon arithmetic operations. Here is a simple example of the difference equation:
y(n)− 34y(n−1)+y(n−2)=x(n)+x(n−3)
Another example of the difference equation is:
𝒚-(𝒏+𝟐)−𝟔𝒚-(𝒏+𝟏)+𝟗𝒚-𝒏=𝟐^𝒏
There are certain steps that are used to solve the difference equation, and these are given next:
Convert the difference equation into the algebraic equation using the specific procedure of the z transform.
Calculate the solution of the resultant equation in the z domain.
Take the time domain equation of the result by using the inverse z transform (that we learned in the previous lecture).
Code |
Output |
fs=1000; t=0:1/fs:1 f=2; x=cos(2*pi*f*t) n=-0.1+(0.1*0.1)*rand(1,length(x)) nx=n+x; num=[1 0.3 1/3] den=[1] y=filter(num,den,x); plot(t,y) |
|
Here, you can see that we have used the plot command to see the signal graphically. You can skip it if you want to have the numerical values only. By changing the frequency value, you can have different types of results. Other parameters that qwe have used are the same that we have described in the previous sections of this series.
Z transform has great significance in the mathematical field, especially in the signal and system and other branches where the signals have a fundamental role. Till now, we have learned a lot of things about this transform and therefore, we expect that you will understand the reason why this transform is used in almost every field of mathematics.
As we have said earlier, z transform deals with discrete-time signals. This is the main reason z transform is used in the process of digital filter analysis. The interesting fact is, laplace transform can not be used in this regard because they can not work on the discrete signals.
The digital filters are the mathematical algorithms that are mainly used in the implemetnatation of digital input signals to obtain the digital output signals.
One of the property that we have learned till now is the linearity of z transform and this property is also used in the analysis process of linear discrete system. The are the system that takes the discrete system as input and after different operations, it also restun us the discrete signals again. Z transform is used to maintain the stability of the result throughout the system.
We all know that the z transform is used to obtain the result in the z plane. It converts the signal with the time domain into other formats, such as the frequency domain. Therefore, while working with the signals, the z transform is used in finding the frequency response.
In the field of telecommunication, all systems are based upon the transfer of a number of bits from one place to another. Z transform is used there to stabilize the flow of the bits as they are in the form of discrete signals. Other techniques are also useful for the same purpose, but while using the z transform, it becomes easy to predict the results and the time at which the communication will occur.
A Z transform is used to overcome the feedback control problems of the system. It is done by using different types of signals, including continuous time and discrete time signals. This transform can be used differently when practically implemented.
In operations where experts want to know the exponentially changing values of the signals, they prefer to work with the z transform according to the nature of the signal.
As we have learned previously, there is a z value that is used in the work of z transform. This is an important feature of the z transform because of its complex nature. It is used to perform complex calculations easily, which were not possible with the Laplace transform.
Z transform is widely used in signal processing ( as we are reading it from the start). Basically, it is a signal processing tool that is efficiently used in the analysis and interaction of different signals. The poles and zeros used in this type of transform help to recognize the nature of the signal; that is, is it casual, stable, or inverse in nature?
It was a long article based upon interesting facts about the z transform. We were having the discussion of the z transform from our previous session where we saw the basics of the z transform. We saw the properties of the z transform and discussed the important points to clarify our concepts. We also use MATLAB for the implementation of a difference equation. In the end, we learned the simple description of the z transforms application to make our minds about the importance of this topic. If you want to learn more, you can find examples of each property and Use them as your homework. The next lecture is also going to be a little bit complex yet interesting because we are going to learn another transform, which is the Fourier transform.
Hey learners! Welcome to another exciting lecture in this series of signals and systems. We are learning about the transform in signals and systems, and in the previous lectures, we have seen a bulk of information about the Laplace transform. If you know the previous concepts of signal and system, then this lecture will be super easy for you to learn, but if your concepts are not clear, do not worry because we will revise all the basic information from scratch for our new readers. So, without wasting time, have a look at the topics of today.
What is z transform?
What is the region of convergence of z transform?
What are some of the important properties of the region of convergence?
How to solve the z transform?
What is an example of the z transform in MATLAB?
What are the methods for the inverse z transform?
You must have an idea that the Laplace transform is a general case transform and converts the signal from a time domain into a frequency domain. The same is the case with the z transform, it changes the domain of the signal but in another way. The Laplace transform is associated with the power signal and the z transform has some other characteristics. Usually, the z transform is used to understand the stability of the system. Z transforms are used in
Energy signals
Power signals
Neither power nor energy signals
Yet it is applicable to a certain level, and after that level, it is not that much more effective. The Z transform is a powerful mathematical tool and is widely used in mathematical courses and applications including signals and systems. We introduce the z transform as:
"The Z transform is a mathematical tool that, after different procedures, converts the differential equation (with time domain) into the algebraic equation of the z domain."
Mathematically, we show it as:
As you can see clearly, the summation sign contains the limits from negative infinity to positive infinity which means it is a bilateral function of the z transform that we have shared with you.
By the same token, you can also predict that the z transform also has another region that lies between the zero to positive infinity. It is called the unilateral z transform and it works a little bit differently than the first case discussed here. We describe it as:
Let’s discuss the whole statement in detail but prior to starting, recall in your mind the definition of discrete-time signals. We know that:
“A discrete-time signal is one whose value can be measured at discrete intervals." When working with a discrete-time signal, there will be time intervals of n during which you will not have a value. In the representation of DT signals, the form x[n] is used. Discrete signals approximate continuous-time (CT) signals."
Therefore, when talking about the z transform, keep the definition of z transform in your mind to understand what exactly is going on.
Now, look at the statement given above.
We have the discrete-time signal in the time domain represented by x[t].
We applied the z transform to it.
Now, we got the same signal that lies in the z domain and is multiplied with a complex number z having the exponential of the n with a negative sign.
Do not worry about the value of n all the time. The summation sign indicates that the value of n starts from negative infinity (or zero in unilateral z transform) to positive infinity, and in this way, we found the values of the series. (This will be much clearer when we discuss the procedure).
Here z is a complex number that is described with the help of this equation:
x(n)⟷X(Z)
The whole discrete time signal is converted into another format with the z transform as a base,
The region of convergence, or simply ROC, is an important term that is used to describe the range of z in the z transform. As we have said, z is a complex number and its range, therefore, has different types of properties.
No. of poles: In z transform, where x[z] is always finite, there are no poles. (We’ll define them in a later section). The ROC of the z transform does not contain any poles.
When talking about a right-sided signal, the region of convergence is always outside the z-plane circle.
When talking about a left-sided signal, the region of convergence is always inside the z-plane circle.
If we have the signal on both sides, then the region of ROC is in the form of a ring inside the circle.
To have a stable form, the region of convergence has a unit value.
There are different cases in the z transform that if we start to describe, will be more confusing and time taking than other transforms. So, we’ll discuss a general format of z transform, and after practice, you will learn the procedure effectively.
Thoroughly examine the question.
Use the formula of the z transform given above.
Put z into the denominator as it has negative power. Doing so will convert the negative power into a positive.
Make sure you take the common values out of the sequence.
Put the value of n as 0, 1, 2, 3, 4, and so on to get the series.
Solve the equation.
It is the most basic and simple description, but the z transform is not that simple. Instead of solving the long calculations, why not use MATLAB for practical implementation? If you have your own course instructor at university, you must have the idea of solving the procedure by hand.
In MATLAB, the z transform is as simple as the previous transform was. Therefore, we are emphasizing the usage of MATLAB at every step. Note that if you want to have a detailed procedure to perform the functions theoretically, you can find your instructors. But from the performance point of view, you should go to MATLAB to confirm your answers all the time. Here is a simple example of an equation that also shows some little details.
Code:
syms n;
f=(2*n+5)/3
disp('x[n]=')
disp(f)
ans=ztrans(f)
disp('z[n]')
disp(F)
Output:
Here, you can see we have used the pre-defined function of z transform given as:
ztrans(x)
With the help of the z transform, you can solve any equation or expression that you want.
Notice that we have used a display function in the code. You must know that z transform can also be done in MATLAB without using the function.
The display function is used to label the numerical output. It does the same work as the xlabel and ylabel in the graphical window of MATLAB. Moreover, this function is also used to call the value that we have specified before using it and to display the results directly. The syntax of the display function is
disp(x)
disp(‘x’)
Where,
To display the string value, we use inverted commas around the value.
To call the value of x, we simply use it as it is.
Never use this function with a capital D or any other change in the spelling, otherwise, you will get the error.
Have a look at another example of the z transform in which we added two trigonometric functions and found their z transform.
Code:
syms n;
f=sin(2*n)
ans=ztrans(f)
g=cos(3*3.14*n)
ans=ztrans(g)
Output:
When you study this particular topic of z transform, you will hear some terms named as zeros and poles. These are the simple topics while learning z transform and usually, are used in the numerical problem. Consider the following equation:
Zeros: while solving the equation with the fraction, the numerator contains the M roots corresponding to the zeros. In the equation given above, q represents the zeros.
Poles: When you are solving the fractional equation by z transform, the N roots in the denominator are called the poles. Here, these are represented with the letter p.
While solving the z transform, we make a circular representation to solve the equation, just like we did while we were learning ROC. Poles are represented at the y-axis, and zeros are represented at the x-axis.
As you can guess from the name, the inverse z transform is used to convert the results of the z transform into the form before the z transform. There are different methods through which the calculations of the z transform are inverted from an equation.
Long division
The partial fraction method of inverse z transforms
Residue method
Power series of inverse z transform
This method is applicable when:
There is a ratio of two polynomials
The polynomials can not be factorized
To apply inverse z transform with this method, the division process of numerator with denominator is carried out. The resultant equation is then passed through the procedure of inverse z transform and we get the results. It is a complex method.
This is the method that involves the rules and procedure of partial fraction (we have received it in the previous lecture) and after that, the inverse z transform is applied.
There are different names for this method including the inversion integration method and contour integral method. For this method, we have to follow the equation given below:
The inverse z transform is obtained by summing up all the residues of this equation from the poles point of view.
In the end, this is the simplest and easiest way to find the z transform. In this method, the equation is expanded and we get the series of ascending powers. After that, the coefficient of z^-n is the required result.
To apply the inverse z transform in MATLAB, we use the following formula:
iztrans(x)
For convenience, we have put the process of z transform and the inverse in the same code.
Code:
syms n;
f=sin(2*n)
F=ztrans(f)
G=iztrans(F)
Output:
We have started the discussion of another transform named the z transform that is somehow similar to the Laplace transform that we have learned in the previous sessions. Z transform is a useful mathematical tool and we studied the ROC, procedure, and the inverse method of z transform. We also saw some examples in MATLAB. In the next lecture, we are going to learn some other basic information on the same topic.
Hey fellows, in the previous lecture, we read the basics of Laplace transform and now, we want to go into a deep study about the same topic. Usually, it is important to learn all the properties of a mathematical tool to use it well, but we’ll focus on the basic and important properties of the Laplace transform to understand its concepts. Here are these:
Linearity
Time delay
Nth derivative
Frequency shifting
Multiplication with time
Complex shift property
Convolution of the Laplace transform
Time shifting
Time reversal
If you have read the previous concepts clearly, then these concepts should be clear in your mind. We’ll define all of them one after the other, and you'll understand each of them clearly.
We all know what linearity is. Yet, the linearity of the Laplace transform is slightly different. When we apply the Laplace transform to two functions that are multiplied with a constant value, say a and b, then the result obtained is equal to the addition of these Laplace entries and multiplying the respective constant with it. In short, we can say:
“Adding two or more values and applying the Laplace transform does not have any change in the result, but we get the linear output.”
This can be illustrated clearly with the following mathematical representation:
You must keep in mind that no matter how many entries you add, the result will always remain linear.
Laplace equation A time delayed function's transform is the function's Laplace Transform multiplied by e-as, where an is the time delay. We frequently investigate systems as a function of frequency.
One must keep in mind that to apply this property, we multiply the delayed version of a function with a delayed step. For instance,
If
Original function= g(t)·γ(t)
Then
Shifted function= g(t-td)·γ(t-td)
If
td=time delay
When taking the derivative of the Laplace to transform, there is a long procedure. It is stated as follows:
There is a long calculation of the whole statement, but after that, the result follows the formula given below:
So, you do not have to take care of each and every value of a long calculation, simply follow this formula and put the values in it, and you can find the derivative of any degree when dealing with the Laplace Transform.
In some other places, the 1st and 2nd derivatives of the Laplace transform are also discussed as properties, but the key point is, that you can put any value of n in the formula given above and get the required results. We have not mentioned them to make things simple.
The frequency shifting property of the Laplace transform is described as
es0t f(t)) ⟷ F(s – s0)
The result on the left-hand side describes the shift of the Laplace transform.
When multiplying the Laplace transform with the time T, the result obtained is:
T f(t) ⟷ (−d F(s)⁄ds) |
When dealing with the complex number and the Laplace transform, one must keep the following statement in your mind:
f(t) e−at ⟷ F(s + a) |
If you are following our previous series, then you must know what the meaning of this property is. Yet, we can revise it. Convolution is the method in which two signals are folded onto one another in such a way that they produce a third signal. The same is the case with the Laplace transform.
When two functions of the Laplace transform in the time domain are convoluted, we get results that have the multiplication of them within the frequency domain.
As we have read about convolution in the previous two lectures, you can get an idea of how you can check this property. To save time, you can also check it in MATLAB. You just have to follow these steps:
Go to MATLAB.
Write the code for the Laplace transform of the first statement by using the function.
Repeat the same procedure with the other statement.
Write the code of convolution of the results as we have done previously.
Output the results.
Time scaling is a basic property of signals, and when we talk about the Laplace transform, we get to know that after scaling, the variable a from the denominator is shifted into the multiplication; that is, we get the time signal in the frequency domain.
Here is another thing about the Laplace transform. The step function is defined when we use the function of the following form:
u(t) = ( 0 for t < 0,
1 for t > 0)
This statement shows that for the values between 0 and 1, this statement is also known as the Heaviside function.
As you can guess from the name, the Laplace transform can be inverted, and this procedure is called the inverse transform. Once you transform the function from the time domain to the frequency domain (that's what the Laplace transform does), you can simply invert the whole process by using the inverse Laplace and get the result in the time domain again. This technique is useful in a number of applications of the Laplace transform. It is represented as:
f(t) = L-1{F(s)}
Now coming towards the solution to this transform. While checking the table, you can easily find the inverse transform. However, if the solution or the term is not present in the table, you can find this inverse with the help of the partial fraction expansion method.
As in the previous case, inverse Laplace is also performed in MATLAB with the help of functions. Here is the simplest example of this function. Suppose we want to perform the inverse transform of the code that we have discussed before.
Code:
syms t s;
ilaplace(exp(3*t)/(s+13)*(s-2))
Output:
All the descriptions are the same as in the previous case, but you can see we used a slightly different function as
ilaplace(x)
Where x is the value of the question that we have fed into this function. Finally, have a look at the code given next in which I just have merged Laplace transform with the inverse Laplace so that you may understand the whole mechanism.
Code:
syms t a s;
f=exp(a*t) %Question
F=laplace(f) %Laplace Transform
G=ilaplace(f) %Inverse Laplace Transform
Output:
Here, a new thing is introduced in our program that may be new to you. We used the comments and these can be added to any program of MATLAB same as the other programming languages.
Comments in the programming languages are ignored by the compiler at compile time. In other words, we can not add any extra words in programming languages because the compiler does not understand them and we risk an error. So, if a person wants to add details about the steps or wants to add any notes, he or she uses the comments. The compiler then ignores these lines, and in this way, we do not get any errors. Usually, comments are shown in a different color than the code lines (green in MATLAB). To add comments in the program, we simply put a percentage sign % before the notes.
As we have all learned in our matriculation, the partial fraction is the method in which the difficult denominator is solved by converting it into different partial fractions. In this way, it becomes easy to find the values of variables, and after that, the result is recollected into the desired form.
There are different cases in the partial fraction of the Laplace transform and some of them are given next:
Direct real roots
Repeated real roots
Complex roots
Order of numerator and denominator are equal.
Exponential in the numerator
Now, you must be thinking about how inverse Laplace can be used as a partial fraction. Let's have a simple example in which you will learn to solve this case.
Consider the following question:
F(s)= s^2 +3/s^2(s+2)
You have to follow the steps given next:
Write the right-hand side part of this equation on the left side of the equal sign and mark it as X.
At the right side of the equal sign, you have to split the denominator. Here, you can see that there will be three fractions when we split the denominator. These are:
s
s^2
s+2
The numerator is ignored at this point, and you have to put A, B, and C on each numerator of the partial fraction.
Now, simply multiply s with the whole equation and solve them one after the other.
Cancel the values as much as possible.
Solve the equation.
Repeat the previous four steps by placing the 2nd and 3rd denominator values.
You will find the values of A, B, and C.
Put the values in equation X and this is the required answer.
This explanation is just for revision, otherwise, we all know the implementation of a partial fraction.
As you were expecting, MATLAB has the implementation of fractions in just a second. You do not have to do long conversions. Simply put the code in MATLAB and you will get accurate and easy answers in just a second.
Suppose we have the question:
F(s)=(4s+24s^22+48^3)/(s+4)(s+1)(s+2)
Then you will use the following code.
Code:
num=[4,24,48]
roots1=[-4 1 2]
den=poly(roots1);
[r,k]=residue(num,den)
Output:
Here, you can see that we have used a different type of code that till now we have not discussed. So have a look at the description given next:
The term "num" describes the values in the numerator.
The den represents the entries of the denominator.
We used the poly(x) function in which x represents the value that has to be converted into polynomial form.
Here in the place of x, we inserted the values that, before calling it, we stored in the user-defined variable roots1. It was named by us, but you can call it by any other name.
[r,k] = residue (num, den) is the pre-defined function of MATLAB in which we find the values of the variables that we have shown by storing them in num and den.
Always keep in mind that the values that we have stored in the den are the values when we put the s-x=0, the sign of each value is reversed. Moreover, never change the sequence of the numerator or denominator in the pre-defined function otherwise, you will get different results.
Have a quick review of the Laplace transform here:
In data mining, there is a great role for databases and records of previous values. The laplace transform plays an important role there and helps to keep the record in a great way.
All the conversation about the Laplace transform was based upon the application of this transform in signal processing. It is used in the filtering of signals, processing of signals, and changing the domain of the signals.
This transform is used to convert the governing complex equations into simple differential equations.
Not only in probability, but it is also used in the moment and variance as well. It is a necessary topic in most mathematical courses.
In computer ICs, the Laplace transform is used to measure and predict the current and other parameters in a great way. Therefore, it is used in the designing of ICs and delicate circuits in a great way.
Today we have seen some interesting facts about the Laplace transform and read thoroughly about the properties and types of Laplace transforms. We used MATLAB for examples, and we also found the working of this transform in detail. In the end, we have a glance at some basic and simple applications of Laplace transforms.
We've all heard that clicking on links or attachments can lead to identity theft of sensitive, personal information. And while it's true - if you're not careful, you could be leaving yourself open to hackers and other dangers. But what most people might not know is the difference between "hacking" and "data theft". In this post, we outline the steps data security engineers recommend you take to protect yourself from these different types of threats.
Data security engineers are not your everyday IT professionals, so what do they recommend for parts of the population who aren't working in IT?
While some advice might be obvious - if you're on a secure, encrypted site, for example - for regular Internet users, data security engineers often urge people to take this one step further. In general, we suggest that individuals don't just treat a website as secure if they can't see that the website is encrypted with HTTPS , but instead assume encryption is there unless it's explicitly said otherwise.
What this means for you as a regular Internet user is that before you click on a link, you should pause and consider if the destination is where it says it's going to take you. If in doubt, search for the destination site to find out where it lives, then visit the site from there instead of clicking the link.
Two-factor authentication adds an extra layer of security in addition to your password by asking for another "factor" to activate your account - most commonly, a number sent either via text message or generated by an app on your smartphone.
Using two-factor authentication, you get maximum protection of your data in your account, protecting yourself from both hackers who have your password and malicious advice that directs you to a fake login page. And once you're there, using two-factor authentication can stop attackers from taking over your account entirely.
Computer security is a constant battle between developers on one side who are trying to make their applications as secure as possible and attackers on the other who are trying to exploit flaws in those applications. To keep up with the latest patches, developers recommend that users keep their software up to date with the latest versions - either automatically or manually.
Users also have a choice to control which applications automatically update. To stop them from installing unwanted software, users can opt out of automatic updates through their OS's control panel. And to ensure the latest security updates from their developer, developers recommend that users always install updates when told.
Since browsers are the foundation on which websites are built, regular Internet users need to keep their browsers current with the latest patches, features, and security fixes. And that means staying up to date.
For users who find themselves caught in an old browser, or for those who might have trouble keeping track of updates, developers recommend taking advantage of automatic browser updates . Then, when updates are available, the browser will notify you and you can update from there. With automatic patches and feature updates, your browser will ensure you're always current with the latest security features to protect your devices and information.
With all the benefits of social networking and sharing, it's easy to feel comfortable sharing each other's information with a promise of trust.
For regular Internet users putting personal information online for others to see, data security engineers think it's important to make sure that when you do share your information online, you're doing so for the right reasons.
The deciding factor here is whether or not you have control over the information and how to delete it from the site when you decide later that you don't want it there anymore.
If you do have control over the information and can delete it from that site, then data security engineers don't see any harm in sharing.
If you don't have control over the information though and aren't allowed to delete it, then data security engineers think it's important to consider other ways of getting your point across - perhaps by taking a picture with your smartphone and posting that online, rather than posting another selfie or a picture of your cat.
Regular Internet users who are constantly using smartphones and tablets are not only making themselves vulnerable to hackers when they're out in public but also at home with their devices. And data security engineers suggest that if users aren't already encrypting their devices, it might be time to start.
Locking an Android device with a password gives users a greater layer of protection over their phones and tablets. Encrypting laptops and desktops can also prevent someone in the same household from accessing your devices. And data security engineers recommend making encryption automatic for all of your cloud storage services like Dropbox and Google Drive since this makes recovery much easier should something go wrong.
While most mobile apps are smaller and more focused than larger software systems, it's still important for regular Internet users to choose the ones that offer security features over those that don't. And for those that do offer features, it's important to make sure they're useful and useful only in your specific situation.
Data security engineers suggest taking a look at reviews of any apps you're considering installing first - both those that are free and paid. Just because an app looks like something you might want isn't always the best reason to install it. After all, what good is an app that can protect security if it can't protect your information?
These steps should keep your online information and devices secure. But sometimes, no matter how prepared you are, problems can still happen. For those times when things do go wrong, data security engineers suggest taking a look at cyber liability insurance. So long as you're not violating the terms of service of any sites or apps that you might use - or ignoring the advice of data security engineers - then your policy should protect you if something happens.