Interfacing of RTC module with Raspberry Pi 4 for real-time Clock

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

Introduction

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.

Real-Time Clocks: What Are They?

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.

Achieving Accurate and Fair RTC Timing

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.

DS1307 Pin Description:

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.

Features of RTC Module

  • 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.

RTC Timing Modification

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.

Time and Date

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.

The real-time clock circuit

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.

Wiring Pi 4 with the rtc board.

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.

Configuring the RTC Chip

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.

Using the RTC Package

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)

Code Walkthrough

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.

Clock Differences: Making the RTC different From RPi Clock

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.

RPI with the real-time clock Module

, 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

RTC as the primary timer

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.

On the RPi, how do we sync real-time clock time?

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"

How to Sync Time From RTC to Pi

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.

What is Tkinter???

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. 

As to why Tkinter?

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.

Advantages of Tkinter

Layered technique

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.

Accessibility

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.

Portability

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.

Availability

Python distributions now include Tkinter by default. Therefore, it is possible to run commands using Tkinter without additional modules.

Tkinter's flaws

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.

Importing Modules

Import the following modules.

from Tkinter import *

from Tkinter. ttk import *

import DateTime

import platform

Tkinter Window Creation

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.

Control tabs in Tkinter

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.

Create Clock

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.

Create Alarm

We'll design an Alarm that will activate when the allotted time has expired in the next step.

Tkinter Components for Alarms

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.

Make an alarm method

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.

Make Stopwatch

As a final step, we'll add a stopwatch to our code.

Add stopwatch Tkinter component.

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.

Add stopwatch counter method.

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.

Add stopwatch method

The stopwatch method, which is invoked by the Stopwatch Controls, is now complete.

def stopwatch(work):

         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')

Make Timer

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.

Add timer Tkinter component

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.

Add timer counter method

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.

Add timer method

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."

Start clock and Tkinter

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.

Output

Alarm

Stopwatch

Timer

Disadvantages of RTC module

  • 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. 

Application of an RTC module

  • 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. 

Conclusion

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.

Car Parking System with Automatic Billing using Arduino

Hi Geeks, welcome to our new project. Our new project is one of the most common issues you’ve seen in your cities. In this project, we are going to make a car parking system with automatic billing. In the entire world, there are an estimated 1.4 billion cars on the road, which is absolutely great news if we are considering the development of the Automobile industry. But the most serious issue is that the number of cars exceeds the number of available parking places, resulting in traffic congestion. Damaged cars due to this lack of space, fewer parking locations, lack of parking signage, informal parking, and overcharging for parking are just a few of the issues.

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.ComponentsDistributorLink To Buy
1DS1307AmazonBuy Now
2Keypad 4x3AmazonBuy Now
3LCD 20x4AmazonBuy Now
4Arduino UnoAmazonBuy Now

Software to install:

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.

Project Overview:

These are required components for Accident Detection, which are as follows:

  • Arduino Uno: Arduino Uno is a development board from the Arduino family, which is the main component of this project and acts as the brain. The Microcontroller i.e., Arduino is responsible for the decisions that are going to be processed in the project.
  • 20X4 LCD display: It is used to display the information regarding parking slots and shows the amount that has to be paid by the driver at the Check out time from the parking lot.
  • Ultrasonic Sensor: It is used to calculate the distance from the car to the entry gate and detects that a car has reached near the gate.
  • RTC Module: Real-Time Clock Module is used to calculate the time and plays a key role in determining the total amount for the parking slot.

Components Needed:

  1. Arduino Uno
  2. LCD Module
  3. Ultrasonic Sensor
  4. Keypad 3x4
  5. LED’s
  6. RTC Module

Components Details

Arduino Uno:

  • Any Arduino development board can be used in this project, however, we'll be using Arduino UNO development boards. The Arduino UNO is a programmable, open-source microcontroller board from the Arduino series.
  • It contains an ATMega328P microcontroller from Atmel, which has an 8-bit RISC processing core and 32 KB of flash memory.
  • The Arduino UNO includes 14 digital I/O pins i.e., D0 - D13, with a resolution of 10 bits, including 6 PWM pins and 6 analog I/O pins (0-1024) i.e., A0 - A5.
  • Only one hardware UART peripheral pin, one I2C peripheral pin, and one SPI peripheral pin are available on the Arduino UNO (however we can use other pins for UART communication using the SoftwareSerial package in Arduino).
  • The Arduino UNO can be powered from a voltage range of 7 to 12 volts, the voltage regulator embedded inside the board will reduce the excess voltage. however, not more than 9 volts is suggested since it might harm the Arduino board.
  • A USB-B cable (the same cable that we used to upload the sketch to Arduino UNO), a DC power jack, and the Vin pin on the board may all be used to power Arduino UNO.
  • Using the Arduino IDE Software, the sketch is written and uploaded to the Arduino UNO. It is completely free, simple to comprehend, and easy to combine with a variety of electronic components.

LCD Module:

In this project, an LCD display is used to present the information to the user.
  • LCD stands for Liquid Crystal Display, and it is a type of display that is made using Liquid Crystal technology.
  • LCDs come in a variety of sizes; in this project, we utilized a 20X4 size.
  • The 20X4 indicates that it can show 80 ASCII characters at once.
  • The LCD has 16 pins. In which the necessary pins are connected in the circuit.
  • It contains eight data pins, one Read/Write select pin, one Register mode pin, one Enable pin, two backlight pins, two power supply pins, and one contrast control pin.
  • In the LCD, there are primarily two types of registers: Command Register and Data Register.
  • When the RS(Register Select) pin is set to logic high, the data register mode is selected, and when it is set to logic low, the command register mode is selected.

The RS pin will be set to logic high to display the data on the LCD.

Ultrasonic Sensor (HR-SR04):

  • The HC-SR04 ultrasonic sensor employs SONAR to estimate the distance of an object.
  • The ultrasonic sensor sends out a signal wave that has a frequency of about 40 kHz, with a high pitch that humans are unable to hear.
  • From 2 cm to 400 cm (1" to 13 feet), it provides the detection of objects with high accuracy and the pulse will not be disturbed by sunlight or any climate conditions.
  • It consists of four pins, Trig, Echo, VCC, and GND.
  • The operating voltage of an Ultrasonic sensor is 5V. We can connect the VCC pin of the sensor with 5V output in Arduino and the sensor will work perfectly.
  • Ultrasonic sensors work on the principle of sound wave reflection.
  • The trig pin works as an ultrasound transmitter which emits the high frequency sound waves in pulses. And the echo pin works as an ultrasound receiver. It receives the reflected ultrasonic waves which are bounced back from the object.
  • We calculate the distance from the object and the sensor by measuring the time taken between the transmission and the reception of the signal.
  • To measure the distance of sound traveled from trig to echo,

Distance = (Time x SpeedOfSound) / 2.

Speed of Sound: 340 meters per second i.e., 0.034
  • The easiest way to calculate the distance in cm is using this formula,

Distance in Centimeters = (( Time taken by pulse signal (in microseconds) / 2) / 29)

Keypad 3x4:

  • A keypad button is used for user input.
  • The keypad's buttons are arranged as a matrix of 3x4. Which means it has four rows and three columns.
  • They work on the principle of membrane keypads. They are very flexible and feel like a push button.
  • The switch between a column and a row trace is closed when a button is pressed, allowing current to pass between a column pin and a row pin.
  • A copper padding and line beneath the pad connects each switch in a row to the other switches in the row.

RTC Module (DS1307):

  • The DS1307 IC is a low-cost, high-accuracy RTC that uses the I2C protocol as an interface.
  • The DS1307 features a backup battery mounted on the rear of the module to maintain track of time even if the main power supply is disconnected.
  • When necessary, the chip shifts between the primary and backup power sources.
  • The RTC records information such as seconds, minutes, hours, days, dates, months, and years.
  • This module includes a Reference clock, programmable Square wave output(SQW), SCL, SDA, VCC, and GND.
  • Automatic Power-Fail Detect and Switch Circuitry
  • Low Power Operation Extends Battery-Backup Run Time.
  • The RTC module works on operating voltage 5V.

Proteus Simulation of Car Parking System:

Now, it’s time to start the design of the Proteus Simulation of our Car parking system

  • Before you begin designing, make sure Proteus is installed on your computer and that you have downloaded all of the necessary libraries.
  • We'll need Arduino libraries and LCD modules for this project. Make sure you've read the section on using libraries in Proteus software.
  • Let's begin by creating a new project, and importing all of the required components, and placing them within the working area.
  • Select all of the components from the Proteus component library that we'll require.

Circuit Diagram and Working:

After importing all required components to the workplace, let’s move to connecting them.

  • Starting with the connection of LEDs, we are using digital pins 2,3,4,5,6 for LEDs. Connect the positive side of the LEDs to the Arduino UNO board.
  • After that, connect the Ultrasonic sensor module’s Trig pin and Echo pin to digital pin 8 and 7 respectively, Vcc to 5v volt power and GND to Ground.
  • In the simulation. it will not be possible to change the distance from the Ultrasonic sensor so for that we have connected a potentiometer with the test pin of the module.
  • Now start the connection of the Keypad, as this is a 3x4 keypad so it will use 3 pins for columns and 4 pins for rows.
  • As there are limited digital pins on Arduino UNO, we have to use the analog pins of Arduino UNO as digital pins.
  • Now let’s connect the row pins A, B, C, D with A0, A1, A2, A3 respectively and column pins 1, 2, 3 with digital pins 9, 10, 11 respectively. And we have to connect the pins in an exact manner.
  • RTC module uses the I2C protocol, so we will connect SDA and SCL pins to Arduino UNO’s SDA (A4) and SCL (A5) pins respectively. Vcc with 5v power supply and Gnd with the ground.
  • As there are no pins left for connecting the LCD module therefore we will use an I2C GPIO expander for connecting the LCD module.
  • Connect the SDA and SCL pins of GPIO expander with the SDA and SCL pins of Arduino UNO and we have to set the slave address of GPIO expander, for that we will connect the A0, A1, A2 pins with ground, that will set the I2C slave address to 0x20.

Now we have done the circuit, it’s time to move to the coding side of this project.

Arduino code for the accident detection:

  • We must add relevant libraries, which operate as header files in programming languages before we begin writing the code.
  • So, if the necessary libraries aren't already installed in the Arduino IDE, we'll need to download them first.
  • We can install Arduino libraries by going to 'Sketch > Include Library > Manage Library' in the Arduino IDE. In the library manager, we can now search for our essential libraries. The libraries can also be installed via zip files.
  • We can download the libraries from the above instruction, but if they are not available, we can use the following links to download the zip files of libraries.
  • Here we used “Wire.h” to enable I2C communication and it is pre-installed.
  • “LiquidCrystal_I2C.h” is used for the LCD.
  • “Keypad.h” is used for the integration of the keypad module.
  • “RTClib.h” is the library for RTC modules.
  • Let’s declare the pins for modules. We mainly use two pins i.e. Trig and Echo for the object detection and distance calculation. Here we have connected the Echo pin to D7 and Trig pin to D8 in Arduino Uno and an array for storing the pins for LEDs as D2, D3, D4, D5, D6. Two arrays for storing the pins for keypads such as rowPins for A0, A1, A2, A3 pins and colPins for D9, D10, D11.
  • Now, Let’s declare configuration related variables for the keypad. Here we are declaring variables to store the number for Rows and Columns. We will use a 2D char array named ‘hexaKeys’ for storing the symbols of keypad.
  • Now declare some general variables for storing the values for ultrasonic sensors, charge, total charged amount, check-in time and check-out time of vehicles.
 
  • Now, Let’s declare the objects of the modules.
 
  • The “customkeypad” is initializing an instance of class NewKeypad. The statement is going to map these symbols with the pins we have declared to connect with Arduino. Hence, it will map according to the row and column pins.
  • Next, we are initializing the LCD display with an I2C serial interface and setting the address to 0x20 Hex.
  • And we are declaring an object named ‘rtc’ for the “RTC_DS1307” module.

Void Setup():

  • The void setup() is an important function in the sketch that will execute only once in the whole program. The input, output, and other serial communication initializations are done inside the void setup. Let’s write the void setup sketch now.
  • In this setup function, firstly we have enabled the serial communication with “Serial.begin” with the default baud rate of 9600.
  • Next, we are initializing the LCD and turning on the backlight of the LCD.
  • We have already declared the Trig and Echo pins before in the declaration part, and now we are going to set them up as output and input pins respectively.
  • There may be a doubt why we have declared a Trig as output and Echo as input. That is because the Trig pin will generate the ultrasonic wave pulses and the Echo pin will work as a receiver for reflected waves.
  • We are using five led’s for the five slots in the parking lot and to make the logic simpler, declare the led pins as output mode.
  • Now, we are printing a line in the serial monitor and LCD. We are using the cursor function and printing “Made by” in the first row and “Tushar Gupta” in the second row. (0,0) is representing (column, row) in the LCD.
  • After printing the line, clear the LCD screen.
  • Now, we are trying to initialize the RTC module and if the RTC is not found, it will print that “Couldn’t find RTC”. and halt the further processing of code.

  • After successful initialization of the RTC module we will know if the RTC module is running already , if yes then we don’t have to set the time explicitly otherwise we have to .
  • We will use a “dist()” function to calculate the distance using the formula mentioned in component details.
  • For the calculation of distance, we will generate the pulses using the Trig pin.
  • To generate the pulses , switch the TRIGpin to LOW for 4 microseconds and then HIGH for 10 microseconds then again LOW .
  • By using ‘pulseIn’ we can calculate the time duration the wave has taken to travel back from the object.
  • “ distance = duration*(0.034/2); ” and here 0.034 is the speed of sound and with this formula, we can calculate the distance in cm and set the threshold values.
  • “pulseIn” takes two arguments, first pin number and second logical state. This will read the pin for logic HIGH and return the time period in which that pin was at a HIGH state.
  • For more knowledge of “pulseIN “ refer to this link: pulseIN function

Void loop():

  • It is the next most important function of Arduino code/ sketch. The “void loop()” will run after the execution of “void setup()”.
  • We'll write the code required to run in a continuous loop in this part. So here we'll write our main application code.
  • Here, we are going to first discuss the Automatic billing part near the gate in our parking system.
  • In the loop function, the Date and Time of that current time are set by “rtc.now”, and the user will enter his slot number in the keypad when he/she is exiting from the slot.
  • The user will click the allocated slot number on the keypad and we are collecting that in the “customkey” variable using the “getkey” function.
  • The serial monitor will print the custom key entered by the user. Then we will check the slot status by “digitalRead (led[i])”.
  • If the led status is HIGH which means the slot was occupied now we will generate the bill for that slot and display that amount on the LCD display for1 second after clear the LCD and set that slot LED to LOW state.
  • The next step we are going to do is to calculate the total amount according to his vehicle staying inside the parking lot. And for that, we can do the simple calculation that is “amount = charge*(gotime [i] - cometime [i]) ;”.
  • We have already declared the charge amount in the above sections of the program. The charge will be multiplied by “go time - come time”, which is the total time the vehicle stayed inside the lot. And the multiplied result of stay time and charge is the final amount the driver has to pay for his parking slot.
  • Now, the driver can pay the amount and exit through the gate. Here, after a second delay, we are clearing the LCD display.
  • “What if the driver pressed any wrong key which has a free slot?” That might be the question in your mind. Well, we can cover that condition with an else statement, where we can print “The slot is already empty” on the LCD and let the driver know that he has entered the wrong key in the keypad near the exit gate.
  • Till now, we have seen the Automatic billing logic near the exit gate. But let’s see what is the slot allocation process at the entry gate.
  • As we have already calculated the distance with the ultrasonic sensor using the “dist()” function, we can set the distance limit to 100cm before the gate, and when a car reaches the entry gate the allocation of the slot will be started.
  • The “for loop” here will see what are the slots showing Low/empty in the parking and allocate that empty one to the car by printing “Park your car at ” and “Slot i” in the LCD.
  • As this slot was allocated, we have to write this LED as High which indicates the slot is not empty. This is the reason where the slot led is high at the exit gate when the user pressed his slot number in the keypad. We are turning on the LED when we are allocating the slot to a car.
  • Now we also have to collect the “come time” by the RTC module for further calculation at the end or near the exit gate.
  • We are implementing an if statement where the all LEDs are high, which means all the slots are filled, the LCD should print (“No more slots”) and inform the driver and clear the LCD screen.

Results / Working:

We have completed the Proteus simulation circuit and Arduino code for the Car Parking project. And it is ready for testing.

  • Before going to start the simulation, we have to add the hex file of our application code in the Arduino UNO module in Proteus and a hex code for the ultrasonic sensor also.
  • To add the hex file, click on the Arduino UNO and a new window will open then click on the Program files, there we will browse to our hex file.
  • In the same way, we can add a hex file for the ultrasonic sensor.
  • Now start the simulation, on the first boot of the circuit, LCD will display the welcome message and the same message will be displayed in the serial terminal also
  • Just for debugging purposes, we are continuously printing the ultrasonic sensor values.
  • In the simulation to change the distance between the vehicle and ultrasonic sensor we have used a potentiometer. Now change the value on the potentiometer.

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.

  • Let's test the condition when the vehicle approaches the sensor, to satisfy that condition the object must be at a distance of less than 100 cm. For that, we have to change the pot value. Set the pot value near to 10 %.
  • After that LCD will display a message if that spot is vacant like “Park your car at Slot 1” and LED for the same location will glow.
  • To take the bill for any location press the keypad for that location number let’s suppose here the location is 1 so we will click on ‘1’
  • After that, it will generate the bill with the total charged amount and the LED for that location will be turned off.
  • In case if we click any slot button which is already vacant then LCD will display the message for the slot is vacant.

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.

  • Let’s take another case when we want to park another car. Now slot 1 is already busy so we will park at slot 2.
  • This time when the sensor value changes less than 100 cm, then the LCD display will show “Park your car at slot 2” because slot 1 is preoccupied.
  • In the image, we can see that both LEDs are glowing as both slots are occupied now.
  • For billing, we will click the button on the keypad for the respective slot.
  • Let’s take a case when all slots are occupied. Here we can see all slot LEDs are glowing.
  • Now we will try to park another car. Then LCD will display ‘no more slot’ as there is no vacant slot available at parking.

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!

Automatic Plant Watering System using Arduino

Hello friends, I hope you all are doing great. In today's tutorial, we are going to design a Proteus Simulation for Automatic Plant Watering System using Arduino. We have designed this project for engineering students as it's a common semester project, especially in electrical, electronics and mechatronics engineering.

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.ComponentsDistributorLink To Buy
1BuzzerAmazonBuy Now
2LEDsAmazonBuy Now
3DS1307AmazonBuy Now
4LCD 20x4AmazonBuy Now
5Arduino UnoAmazonBuy Now

Software to Install

We are not designing this project using real components, instead, we are going to design its Proteus simulation. So, first of all, you should Install Proteus Software itself. Proteus software has a big database of electronics components but it doesn't have modules in it. So, we need to install Proteus Libraries of a few components, so that we could simulate them. So, these are the PRoteus libraries which you should install first, before working on this project: You can download this complete project i.e. Proteus Simulation & Arduino Code, by clicking the below button: Download Complete Project Note: You should also have a look at these other Proteus Libraries:

Project Overview:

Three main components of an autonomous watering system are:

  • Water Level Sensor: monitors the water reservoir level.
  • Moisture Sensor: monitors the soil moisture level.
  • RTC module: responsible for supplying water to the plant at predetermined intervals or at a predetermined time.
  • Arduino UNO: serves as a hub for connecting and controlling all these components.

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.

Components Needed:

  1. Arduino UNO
  2. Water Level Sensor
  3. Moisture Sensor
  4. RTC Module (DS1307)
  5. LCD
  6. 4 LEDs
  7. Buzzer
  8. Relay
  9. Water Pump
  10. PCF8574

Component Details:

Arduino UNO:

  • Arduino UNO is a programmable microcontroller board.
  • It contains Atmel's ATMega328 as is based on that microcontroller.
  • The Arduino board also contains an in-built voltage regulator to protect it from burning out and supports serial communication to help programmers.
  • The Arduino board is culturally programmed through the Arduino App designed by the board's developers and the programming is done in C language.
  • The Arduino App compiles code and interfaces the firmware into the Arduino hardware.
  • Arduino UNO has 14 digital I/O pins out of which 6 are PWM pins as well.
  • Arduino also takes analog inputs and has 6 analog input pins.

Figure # 1: Arduino UNO

Soil Moisture Sensor:

  • The soil moisture sensor is a resistive sensor that consists of two electrodes with a small charge and the resistance in those electrodes is measured and then the resistance in between the soil is used to find the moisture levels.
  • A soil moisture sensor normally comes equipped with an amplifier such as LM393. It has a VCC, GND and analog output pin.

Figure # 2: Soil Moisture Sensor

Water Level Sensor:

  • The water level sensor is a module that helps calculate the amount of liquid in a container.
  • When a liquid is present in the tank, the Submersible level sensor detects the hydrostatic pressure generated by the liquid.
  • Since hydrostatic pressure is a measure of two variables, the first of which is the density of the fluid and the second of which is the height of the fluid, it is a useful tool.

Figure # 3: Water Level Sensor

RTC Module:

  • RTC stands for real Time Clock and as the name suggests the module keeps track of time even when the external power supply is cut off.
  • It has a battery cell installed within it for that purpose, moreover, it is capable of communication with other devices such as Arduino too.

Figure # 4: RTC Module

Relay:

  • Relays are basically electrical or electromechanical switches that operate on the principle of magnetic field controlling the switching within the relay.
  • A relay has two modes of operation, normally open and normally closed.

Figure # 5: 12V Relay

PCF8574:

  • The PCF8574 is a silicon-based CMOS integrated circuit.
  • Using the two-line bidirectional bus enables general-purpose remote I/O extension for the majority of microcontroller families (I2C).
  • It is used in our project for I2C communication of LCD.

Figure # 6: PCF 8574

 

Proteus Simulation of Plant Watering System

Now, let's design the Proteus Simulation of Plant Watering System first and then will work on the Arduino Code.
  • First of all, make sure that Proteus is installed on your computer and download all the necessary libraries for Proteus beforehand.
  • For this project, you will need libraries for Arduino, LCD, RTC Module, Water Level Sensor and Soil Moisture Sensor. Make sure that you read how to use each library in Proteus as well.
  • Open a new project on Proteus, import all the components required and place them within the working area or the blue line of Proteus.
  • Select below components from Proteus Components' library:

Circuit Diagram and Working:

  • Now, place these components in your Proteus workspace, as shown in the below figure:
  • For the water level and moisture sensor, place a variable POT(potentiometer) at the test pin and place an RC filter at the output pins. (This is only for simulation purposes)
  • Start with the input side of Arduino and connect the soil moisture, water level output pins to the A1 and A0 pins of Arduino respectively.
  • To use the LCD for I2C communication, Place PCF8574 and connect with LCD.
  • Connect the SDA and SCL pins of PCF8574 and the SDA and SCL pins of the RTC module with the SDA and SCL pins of Arduino.
  • For the output side of Arduino, Connect the D7 to the relay controlling the pump.
  • Connect the buzzer at D2 and the LEDs to their respective Arduino pins as well.
  • Make sure appropriate power and ground are provided to each component. With that the making of the circuit on Proteus is complete.

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

Arduino Code for Plant Watering System

A normal Arduino code has two main segments:

  • void setup
  • void loop
We will look at both of them separately here.

Declaration Code

  • The first step in setting up our code is defining libraries, download if you don’t have any libraries already integrated in the Arduino App.

Figure # 12: Arduino Code

  • The next step in the code is tone definition for buzzer and pin definition of variables being used in the project.

Figure # 13: Arduino Code

  • After pin definition, the variables used must be defined so that Arduino knows where to find them and how to identify them.

Figure # 14: Arduino Code

  • The next step is defining the system messages that will appear on the LCD.
  • It is not necessary to define those messages in the setup, they can be easily defined within the main code but it is an easier way to define those beforehand and call them whenever needed.
  • This is especially useful when a system message is used multiple times in the code.

Figure # 15: Arduino Code

  • Now we define the objects being used in the project.
  • The two objects being defined are the RTC module and LCD. In the syntax below we used 20x0 in the argument for the LCD, that is because there are no libraries for I2C LCDs and we had to turn a simple LCD into an I2C LCD by the means of PCF8574.

Figure # 16: Arduino Code

Void setup:

Now we start the programming of void setup.
  • At first is the initialization of various components, such as initializing the RTC module and setting the time and date of RTC with respect to our computer.
  • Wire initialization and library are used for I2C communication.

Figure # 17: Arduino Code

  • The next step is defining the digital pins of Arduino being used as input or output pins and displaying the initial message on our LCD.

Figure # 18: Arduino Code

 

Void Loop:

  • The first step in the loop is to read the date and time from the computer through the RTC and read the values from the sensor.
  • Since this part of the program runs in the loop, Arduino will keep reading and refreshing the sensor inputs every time the loop starts.

Figure # 19: Arduino Code

  • In the next segment of the code, we will check various conditions of the sensor values and RTC and actuate our outputs on the basis of these conditions.
  • At first, we check the water level of the container, if it is below the set level, Arduino will actuate the buzzer to alarm the user of low tank on LCD.

Figure # 20: Arduino Code

  • In the next step, we check the values of the moisture sensor and place the conditions in three categories, namely, moist soil, soggy soil and dry soil.
  • The Arduino will light up the respective LED whenever its condition is true. Red LED for dry soil, yellow LED for soggy soil and green LED for moist soil.
  • The LCD will also display respective messages for each of those conditions.
  • The following code is for the condition of dry soil.

Figure # 21: Arduino Code

  • The following code is for the condition of moist soil.

Figure # 22: Arduino Code

  • And finally the code for the condition of soggy soil.

Figure # 23: Arduino Code

  • In the next step of the code, we check the condition of time, whether it is time to water the plants or not and the condition of the water reservoir to see its level as well.

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.

Results/Working

  1. Open Arduino and generate a hex file for that program.
  2. Put the hex file in the Arduino UNO board placed in Proteus.
  3. Run the simulation.

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.

Introduction to DS1307

Hello friends, I hope you all are doing great. In today's tutorial, we are gonna have a look at detailed Introduction to DS1307. DS1307 is a real-time clock. It is a low power device and also has battery backup, which provides power when its external power supply not working or is off. It works on the I2C protocol. It is a bidirectional device and it can send and receive data on both sides. DS1307 is used in industrial projects where constant time and date of some projects or working is required. I will give you a detailed overview of this time and date indicator IC. In today's post, we will have a look at its pinout, working, basic circuit, protocol, etc. I will also share some links of projects where I have interfaced it with Arduino and some other Microcontrollers. Friends, if you have any questions, please ask in comments and I will try my best to solve your problems and will give you comprehensive answers. So let's get started with basic Introduction to DS1307:

Introduction to DS1307

  • DS1307 is a Real-Time Control (RTC) IC. In DS1307, data is transferred in binary decimal coded, bits pattern. The data transfer rate in DS1307 is 56 bytes.
  • The memory which is used in DS1307 is NV SRAM. NV SRAM is basically a non-volatile random access memory. In working, NV SRAM is quite similar to static random access memory(SRAM).
  • DS1307 is an electronic device which plays an impotent role in real-time embedded systems. In embedded systems, we can get benefits of system clocks, students attendance time and date, we can also use it as an alarm for special work.
  • DS1307 consists of a built-in power-sense circuit. The purpose of the built-in power-sense circuit is that if power gets cut-off, then it will automatically switch to back up power supply. In this way, our circuit remains in working condition.
  • The protocol on which DS1307 works is I2C. I2C is a single line protocol in which data is transferred bit by bit along a single wire.

  • Now let's have a look at DS1307 Pinout:

DS1307 Pinout

  • DS1307 has a total of 8 pinouts, which are described below:
    • PIN 1,2: These pins are for standard 32.768 quartz crystals. Both pins can be used as input and output for internal oscillator. If X1 is input then X2 is used as output.
    • PIN 3: This pin is used for battery connection to DS1307.
    • PIN 4: We have to apply Ground on this pin.
    • PIN 5: This pin is labeled as SDA, which is short for Serial Data Line.
    • PIN 6: It is used for serial clock input (SCL) and data synchronized.
    • PIN 7: This pin is used for output square wave obtainer (SQW).
    • PIN 8: At this pin, we provide an external power supply (Vcc).
  • Now let's have a look at the pinout picture:
Now let's have a look at I2C protocol

I2C Protocol

  • I2C is a serial protocol in which data is transferred bit by bit.
  • I2C combine the best feature of  SPI and UART. By using it with one microcontroller we can control many slave devices.
  • In I2C data is transferred in the form of messages, then we convert messages into data form. Each message has an address frame that contains a binary address of devices which under control.
  • I2C protocol is cheaper to implement then SPI protocol. SPI control one slave device while I2C control more than one device.
  • For better understanding lets have a look at the I2C protocol picture. Now let's have a look at working of DS1307

Working of DS1307

  • For a better understanding of the working of DS1307 let's discuss a circuit in which we use it.
  • In this simple circuit, we connect its first two pins which are X1 and X2 with 32.768 kHz crystal oscillator as the source for the chip.
  • The third pin is connected with a battery of 3V.
  • At Vcc, we give 5v supply and it can be given by using a microcontroller. If Vcc is not provided then read and write condition are inhibited.
Let us have a look at the circuit:
  • Starts and stop conditions are required when one device wants to communicate with other devices in the I2c protocol.
  • For obtaining start condition we provide specific identification and address register to a device, by this, we get start condition.
  • For a better understanding of stop and start condition lets have a look at clock figure.
  • Let's have a look at Feature of ds1307.

Features of DS1307

  • In this section, I have designed a table where I have placed all features of DS1307 along with their symbols and units.
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
Now, let's discuss applications of DS1307

Applications of DS1307

  • These are some applications of DS1307, Lets disuses them.
  • As we know DS1307 is used to tell continues time and date showing purpose, that way it is an electronic device such as a computer, mobile, and laptops.
  • By using it with Arduino we can use it in several projects related to data logging, alarm, clocks, etc.
So, that was all about this Real Time Clock DS1307. I hope you have enjoyed today's tutorial and it will help you with your engineering projects. Will meet you guys in the next tutorial, till then take care and have fun !!! :)

DS1307 Arduino based Digital Clock in Proteus

Hello everyone, today I am going to share a complete project which is DS1307 Arduino based digital Clock in Proteus ISIS. In this project, I have designed a digital clock using Arduino UNO and DS1307 RTC Module. So, first of all, if you haven't yet installed then, you should install Arduino Library for Proteus using which you will be able to easily simulate Arduino baords in Proteus. Along with Arduino Library you will also need to install DS1307 Library for Proteus, which I have shared in my previous post as we are gonna use this RTC Module DS1307 for designing our digital clock.

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:

DS1307 Arduino based Digital Clock in Proteus

  • You can download the complete Proteus Simulation along with Arduino Code by clicking the below button.
  • You will also need DS1307 Library for Arduino, which is also available in this package.

Download Project Files

  • Now, let's get started with designing of this DS1307 Arduino based Digital Clock.
  • So, first of all, design a circuit in Proteus as shown in below figure:
  • You can see in the above figure that I have used Arduino UNO along with RTC module, LCD and the four buttons.
  • These four buttons will be used to change the year,date etc as mentioned on each of them.
  • Now here's the code for DS1307 Arduino based Digital Clock.
#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);
}
  • Now get your hex file from Arduino software and then upload it in your Proteus software.
  • Now run your simulation and if everything goes fine, then it will look like something as shown in below figure:
  • Now you can see its today's date in the LCD and the same is shown over on the small pop up of DS1307 Clock.
  • Now the time will start on ticking and the buttons will used to change the minutes hours etc.
  • You will get the better demonstration of this project in the below video.
So, that's all for today. I hope this projects DS1307 Arduino based Digital Clock will help you in some way. So see you in next post.

DS1307 Library for Proteus

Hello friends, hope you all are fine and having fun with your lives. In today's post, I am going to share a new DS1307 Library for Proteus. Recently, I have shared the GSM Library for Proteus, which was really appreciated by the readers so I got quite excited and have designed another new Proteus Library. Currently I am working on many Proteus Libraries. In future, I am gonna design almost all the sensors in Proteus. So stay tuned with us.

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:

DS1307 Library for Proteus

  • First of all, download the DS1307 Library for Proteus, by clicking the below button:
DS1307 Library for Proteus

  • Now, when you click this button you will get a rar file so unrar this file and in it you will find two files named as:
  • RTCModuleTEP.IDX
  • RTCModuleTEP.LIB
  • Place both of these files in the library folder of your Proteus software.
  • Now restart your Proteus software or open it.
  • In the search component bx, search for RTCModuleTEP or DS1307 and place it in your workspace.
  • If everything goes fine then you will get your RTC Module DS1307 as shown in below figure:
  • That's it, now you have the ready to use DS1307 module in Proteus.
  • You need to add a crystal oscillator between X1 and X2 pins while the remaining are used for I2C Protocol, which is a common protocol for RTC Modules.
  • I will also post a tutorial in which I will interface this RTC Module with Arduino or PIC Microcontroller and then you will get a better idea of how to use it.
  • If you design some project using this DS1307 Library for Proteus then do share it with our community so that others could also get benefit out of it.

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!!! :)

Syed Zain Nasir

I am Syed Zain Nasir, the founder of <a href=https://www.TheEngineeringProjects.com/>The Engineering Projects</a> (TEP). I am a programmer since 2009 before that I just search things, make small projects and now I am sharing my knowledge through this platform.I also work as a freelancer and did many projects related to programming and electrical circuitry. <a href=https://plus.google.com/+SyedZainNasir/>My Google Profile+</a>

Share
Published by
Syed Zain Nasir