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.