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.
People are still choosing manual parking methods, which have a number of drawbacks, such as searching for a vacant spot in a parking lot without knowing if the lot is full or not, resulting in time and fuel waste. Vehicle safety is also a concern that may be addressed. We've all been in a position when we've spent a long time looking for parking at a location just to discover that none is available. You would think that if you knew the slots were full, you would've ended up finding another parking spot.
Based on these scenarios, we came up with the idea of a Car Parking System with Automatic Billing which will also reduce manpower such as security, booth attendants, etc., required in parking lots. Everything in the modern day is automated, and with this project, we can automate this procedure using simple electronics components and Arduino. Let's get started.
Where To Buy? | ||||
---|---|---|---|---|
No. | Components | Distributor | Link To Buy | |
1 | DS1307 | Amazon | Buy Now | |
2 | Keypad 4x3 | Amazon | Buy Now | |
3 | LCD 20x4 | Amazon | Buy Now | |
4 | Arduino Uno | Amazon | Buy Now |
Instead of using real components, we'll use the Proteus Simulation tool to design this project. It's also a good habit to experiment with simulations before attempting to build everything with real components. By simulating an issue that may develop when working on actual components, we may identify the problem and avoid any damage to our components.
Proteus is an interesting software that lets you model and build electronics circuits. Despite having a huge library of electronics components, Proteus software lacks pre-installed modules such as Arduino boards, Ultrasonic sensors, RTC modules, LCD modules, and so on.
Now, we’ll start installing the libraries, which is needed for our project:
By clicking the button below, you can download the entire project, including Proteus Simulation and Arduino Code.
These are required components for Accident Detection, which are as follows:
The RS pin will be set to logic high to display the data on the LCD.
Distance = (Time x SpeedOfSound) / 2.
Speed of Sound: 340 meters per second i.e., 0.034Distance in Centimeters = (( Time taken by pulse signal (in microseconds) / 2) / 29)
Now, it’s time to start the design of the Proteus Simulation of our Car parking system
After importing all required components to the workplace, let’s move to connecting them.
Now we have done the circuit, it’s time to move to the coding side of this project.
We have completed the Proteus simulation circuit and Arduino code for the Car Parking project. And it is ready for testing.
As we can see that for 50% value on the pot ultrasonic sensor value is near to 500 cm and for 77% value on the pot ultrasonic sensor value is near to 850 cm.
Here it is not visible which button on the keypad has clicked but suppose we have clicked ‘1’ and if that location is vacant then it will display that message.
I hope you have a good understanding of how our Car parking system project works and that you have liked it. Although it’s a tough nut to crack in the first read, I strongly recommend you to read the logic part twice for better understanding. I believe we have covered almost everything, please let us know if you have any questions or suggestions in the comments section.
Thank you very much for reading this project. All the best for your projects!
The two most significant hazards to the agriculture industry are the need for extensive labor and a scarcity of water. According to the World Wildlife Fund (WWF) organization, water shortages might affect two-thirds of the world's population by 2025, putting both the ecosystem and human health at risk. The use of automatic plant watering systems eliminates both of these problems by watering plants at specified times and amounts while monitoring their hydration levels through measuring moisture in the soil surrounding the plants. Automatic plant watering systems can be used in homemade gardens and can also be deployed in fields for large-scale use. Whenever designing an automatic watering system, it is important to keep in mind that the system should be expandable, allowing for the simple integration of new devices in order to broaden the applicability of the system.
Where To Buy? | ||||
---|---|---|---|---|
No. | Components | Distributor | Link To Buy | |
1 | Buzzer | Amazon | Buy Now | |
2 | LEDs | Amazon | Buy Now | |
3 | DS1307 | Amazon | Buy Now | |
4 | LCD 20x4 | Amazon | Buy Now | |
5 | Arduino Uno | Amazon | Buy Now |
Three main components of an autonomous watering system are:
It is necessary to integrate the water level sensor with the microcontroller before it can be installed within the water reservoir. The location of the water level sensor within the reservoir is variable and is determined by the user and the application for which it is being utilized. The Arduino receives continuous data from the water level sensor and warns the user when the water goes below a certain level, either by an alarm or a buzzer, as appropriate.
The soil moisture sensor operates in a manner similar to that of the water level sensor. The tip of the sensor is inserted into the soil near the plant, and the sensor is activated. In the case of a moisture sensor, the closeness of the sensor to the plant is also variable, and the user may adjust it depending on the features of the plant for which it is being used. In vast agricultural fields, a single sensor may be used for numerous plants if they are closely spaced and their hydration levels can be determined by measuring the soil moisture at one location that overlaps with another spot on the soil surface.
The RTC module operates on the same concept of time monitoring in the background as other electronic devices such as computers and smartphones; even when these devices appear to be turned off, they continue to keep track of the current time. The RTC module, on the other hand, is capable of exchanging time information with the Arduino board. On a specific day of the week, at a specific time of day, the Arduino is pre-programmed to turn on the water pump and turn off the water pump after a specified length of time.
Figure # 1: Arduino UNO
Figure # 2: Soil Moisture Sensor
Figure # 3: Water Level Sensor
Figure # 4: RTC Module
Figure # 5: 12V Relay
Figure # 6: PCF 8574
Figure 7 shows the circuit diagram of the system. Proteus was used to simulate the circuit and Arduino App was used for the simulation of the Arduino code. The circuit was designed in a way that is easy to understand and further integrated easily. We will now go through a step-by-step guide on how the circuit was built.
Figure # 7: Proteus Circuit diagram
A normal Arduino code has two main segments:
Figure # 12: Arduino Code
Figure # 13: Arduino Code
Figure # 14: Arduino Code
Figure # 15: Arduino Code
Figure # 16: Arduino Code
Figure # 17: Arduino Code
Figure # 18: Arduino Code
Figure # 19: Arduino Code
Figure # 20: Arduino Code
Figure # 21: Arduino Code
Figure # 22: Arduino Code
Figure # 23: Arduino Code
Figure # 24: Arduino Code
If you see the code closely, you may see the function of the right hour, which is called various times in the main code. The function code in itself is written at the bottom of the main code. This function is used for displaying the time and date on the LCD and also for fixing the date and time.
Figure # 8: Proteus circuit simulation when soil is soggy
Figure # 9: Proteus circuit simulation when soil is moist
Figure # 10: Proteus circuit simulation when soil is dry
Figure # 11: Proteus circuit simulation when soil is dry and it is time to water the plant
As you can see from figure 8 that our simulation is running according to the program set at Arduino. You can increase or decrease the values coming from the sensors through the Potentiometer. So, that was all for today. I hope you have enjoyed today's lecture. If you have any questions, please ask in the comments. Thanks for reading.No. | Parameter | Symbol | Value | Unit |
1. | Supply Voltage | VCC | 5 | V |
2 | Logic 1 Input | VIH | 2.2 | V |
3 | Logic 0 Input | VIL | +0.8 | V |
4 | VBAT Battery Voltage | VBAT | 3.5 | V |
5 | Input Leakage | ILI | 1 | uA |
6 | I/O Leakage | ILO | 1 | uA |
7 | Logic 0 OUTPUT | VOL | 0.4 | V |
8 | Active Supply Current (fSCL = 100kHz) | ICC | 1.5 | mA |
9 | Standby Current | ICCS | 200 | uA |
10 | VBAT Leakage Current | IBATLKG | 50 | nA |
11 | Power-Fail Voltage (VBAT = 3.0V) | VPFtd> | 1.284 x VBAT | V |
12 | VBAT Current (OSC ON); SQW/OUT OFF | IBAT1 | 500 | nA |
13 | VBAT Current (OSC ON); SQW/OUT ON (32kHz) | IBAT2 | 100 | nA |
14 | VBAT Data-Retention Current (Oscillator Of) | IBATDR | 100 | nA |
15 | SCL Clock Frequency | fSCL | 100 | kHZ |
16 | Bus Free Time Between a STOP and START Condition | tBUF | 4.7 | us |
17 | Hold Time (Repeated) START Condition | tHD:STA | 4 | us |
18 | LOW Period of SCL Clock | tLOW | 4.7 | us |
19 | HIGH Period of SCL Clock | tHIGH | 4 | us |
20 | Setup Time for a Repeated START Condition | tSU:STA | 4.7 | us |
21 | Data Hold Time | tHD:DAT | 0 | us |
22 | Rise Time of Both SDA and SCL Signals | tR | 1000 | ns |
23 | Fall Time of Both SDA and SCL Signals | tF | 300 | ns |
24 | Setup Time for STOP Condition | tSU:STO | 4.7 | us |
So, now I hope that you have installed both these libraries successfully and are ready to design this DS1307 Arduino based Digital Clock. I have given the Simulation and Code for download below but as I always advise, don't just download the files. Instead design your own simulation and try to write your own code. In this way, you will learn more out of it. So, let's get started with DS1307 Arduino based Digital Clock in Proteus ISIS:
#include <LiquidCrystal.h> #include <DS1307.h> #include <Wire.h> LiquidCrystal lcd(13,12,11,10,9,8); int clock[7]; void setup(){ for(int i=3;i<8;i++){ pinMode(i,INPUT); } lcd.begin(20,2); DS1307.begin(); DS1307.setDate(16,4,7,0,17,50,04);//ano,mes,dia,semana,horas,minutos,segundos } void loop(){ DS1307.getDate(clock); lcd.setCursor(0,1); lcd.print("Time: "); Print(clock[4]); lcd.print(":"); Print(clock[5]); lcd.print(":"); Print(clock[6]); lcd.setCursor(0,0); lcd.print("Date: "); Print(clock[1]); lcd.print("/"); Print(clock[2]); lcd.print("/"); lcd.print("20"); Print(clock[0]); if(digitalRead(7)){ clock[5]++; if(clock[5]>59) clock[5]=0; DS1307.setDate(clock[0],clock[1],clock[2],0,clock[4],clock[5],clock[6]); while(digitalRead(7)); } if(digitalRead(6)){ clock[4]++; if(clock[4]>23) clock[4]=0; DS1307.setDate(clock[0],clock[1],clock[2],0,clock[4],clock[5],clock[6]); while(digitalRead(6)); } if(digitalRead(5)){ clock[2]++; if(clock[2]>31) clock[2]=1; DS1307.setDate(clock[0],clock[1],clock[2],0,clock[4],clock[5],clock[6]); while(digitalRead(5)); } if(digitalRead(4)){ clock[1]++; if(clock[1]>12) clock[1]=1; DS1307.setDate(clock[0],clock[1],clock[2],0,clock[4],clock[5],clock[6]); while(digitalRead(4)); } if(digitalRead(3)){ clock[0]++; if(clock[0]>99) clock[0]=0; DS1307.setDate(clock[0],clock[1],clock[2],0,clock[4],clock[5],clock[6]); while(digitalRead(3)); } delay(100); } void Print(int number){ lcd.print(number/10); lcd.print(number%10); }
Anyways coming to today's post, today we are gonna have a look at DS1307 Library for Proteus. Using this library, now you can quite easily simulate DS1307 module in Proteus in a quite stylish way. ;) I have designed it in red color because its available in red color in market. DS1307 module is already available in Proteus but that one is quite basic and it looks quite dull. The one designed by our team looks quite attractive and is also easy to use. I will post its tutorials soon in which I will interface it with Arduino and PIC Microcontroller. You should also have a look at DS1307 Arduino based Digital Clock in Proteus. So, let's get started with DS1307 Library for Proteus:
So, that's all for today. You should also have a look at these New Proteus Libraries for Engineering Students. I hope you are gonna enjoy this DS1307 Library for Proteus. If you have any suggestions or feedback then do let us know in comments. Till next tutorial, take care and have fun!!! :)