Posted on 1 Comment

Variables and Data Types in MicroPython on Raspberry Pi Pico

Variables and data types are fundamental concepts in programming. In MicroPython, just like in any programming language, variables are used to store data values and data types define the kind of data that can be stored.

In this tutorial, we will explore variables and data types in MicroPython on Raspberry Pi Pico.

Variables in MicroPython

Variables in MicroPython are used to store data values such as numbers, strings, and boolean values. A variable is simply a named reference to a value.

To create a variable, you simply assign a value to a name using the equals sign (=). For example:

x = 5

In this case, the variable x is assigned the value of 5.

You can also assign values to multiple variables at once, like this:

x, y, z = 5, "Hello", True

This assigns the value of 5 to the variable x, the string “Hello” to the variable y, and the boolean value True to the variable z.

Further Explanation

x, y, z = 5, “Hello”, True is a way of assigning values to multiple variables at once in Python. In this case, the values 5, “Hello”, and True are assigned to the variables x, y, and z respectively.

This syntax is known as “tuple unpacking”. The values on the right-hand side of the equals sign are packed into a tuple, which is then unpacked and assigned to the variables on the left-hand side.

Essentially, it’s the same as writing:

my_tuple = (5, "Hello", True)
x = my_tuple[0]
y = my_tuple[1]
z = my_tuple[2]

But using tuple unpacking is a more concise and readable way to assign values to multiple variables at once.

Data Types in MicroPython

MicroPython has several built-in data types that define the kind of data that can be stored in a variable. These include:

  • Integer: whole numbers, such as 5 or -3.
  • Float: decimal numbers, such as 3.14 or -2.5.
  • String: a sequence of characters, such as “Hello” or “123”.
  • Boolean: a value that is either True or False.
  • List: a collection of values, such as [1, 2, 3] or [“apple”, “banana”, “orange”].
  • Tuple: a collection of values, like a list, but cannot be modified once created, such as (1, 2, 3) or (“apple”, “banana”, “orange”).
  • Dictionary: a collection of key-value pairs, such as {“name”: “John”, “age”: 30}.

To determine the data type of a variable, you can use the type() function, like this:

This will output <class ‘int’>, indicating that x is an integer.

x = 5
print(type(x))  # Output: <class 'int'>
Posted on Leave a comment

How to Read internal temperature sensor of Raspberry Pi Pico using Thonny IDE

The internal temperature sensor of RP2040 is read using micropython. The Thonny IDE is used in Windows environment.

The temperature sensor is connected to Channel number 4 of the ADC.

But since this is a rather small implementation using Thonny IDE, it does most of the interfacing related code in the background.

Code

import machine
import time

"""
Function Name: Read internal temperature sensor
Description: This function reads the internal temperature sensor of RP2040 chip.
             The temperature sensor measures the Vbe voltage of a biased bipolar diode,
             connected to the fifth ADC channel (AINSEL=4).
"""
def read_internal_temperature_sensor():
    tsi = machine.ADC(machine.ADC.CORE_TEMP)
    temp = tsi.read_u16() * (3.3 / (65535))
    temp = 27 - (temp - 0.706)/0.001721
    return temp

while True:
    #reads the temprature and prints it
    print("Temperature: ", read_internal_temperature_sensor())
    #Create a dealy of 1 second
    time.sleep(1)
Posted on Leave a comment

How to setup Raspberry Pi Pico using Thonny IDE on windows and Blink onboard LED

First you have to install micropython on your raspberry pi pico board.
Follow the steps shown in the video.

To blink the onboard LED you can follow these steps:

  1. Connect your Raspberry Pi Pico to your Windows computer using a micro USB cable.
  2. Open Thonny IDE on your Windows computer.
  3. Click on the “File” menu and select “New”.
  4. In the new window, enter the following code:
import machine
import time

led_onboard = machine.Pin(25, machine.Pin.OUT)

while True:
    led_onboard.toggle()
    time.sleep(1)
  1. Save the file with a meaningful name and the “.py” extension.
  2. Click on the “Run” menu and select “Run current script” or press the “F5” key.
  3. Thonny IDE will run the code and the onboard LED of Raspberry Pi Pico will start blinking at a frequency of 1 second.

That’s it! You have successfully blinked the onboard LED of Raspberry Pi Pico using Thonny IDE on Windows.

Posted on Leave a comment

Diodes

  • Diodes are electronic devices that conduct in one direction. Ideally, they have to block the conduction of current in the reverse direction, but in reality, there is always a small leakage current present.
  • Due to the presence of impurities in the diode, it gets hot when a large amount of current is passed through.
  • There are diodes for various applications which focus on a special property of the diode.
    • For example:
      • Zener Diode – Works in reverse bias condition. Provide excellent voltage regulation.
      • Schottky Diode – Has low forward voltage drop and high switching speed. Suitable for high-frequency applications and power supply circuits.
      • Silicon Controlled Rectifier (SCR) – Can handle high current and voltage levels. Used for power switching and motor control applications.
      • Light Emitting Diode (LED) – Emits light when forward biased. Used for lighting and display applications.
      • Tunnel Diode – Exhibits negative resistance. Used in microwave oscillators, amplifiers, and detectors.
      • Avalanche Diode – Can withstand high reverse voltage and exhibits avalanche breakdown. Used for overvoltage protection and voltage regulation.
      • Photodiode – Generates a current when exposed to light. Used in optical communication and sensing applications.
      • These are just a few examples, and there are many more types of diodes available for various applications.

The following properties should be looked at in a datasheet. There may be additional details but these are the minimum.

  • VF is the voltage drop across the diode when it is conducting current in the forward direction. For example, a silicon diode may have a VF of around 0.7V.
  • IF is the maximum current that the diode can handle without being damaged. For example, a diode rated for 1A can handle a maximum current of 1A flowing through it.
  • VR is the maximum reverse voltage that the diode can withstand before breakdown. For example, a diode with a VR of 100V can withstand a reverse voltage of up to 100V before it starts conducting in the reverse direction.
  • PD is the maximum power that the diode can safely dissipate without getting damaged. For example, a diode with a PD of 500mW can safely dissipate up to 500mW of power without getting damaged.
  • Tj is the maximum temperature that the junction of the diode can reach without getting damaged. For example, a diode with a Tj of 150°C can safely operate at a maximum temperature of 150°C.
  • trr is the time taken by the diode to switch from forward conduction to reverse blocking mode. For example, a diode with a trr of 50ns will take 50ns to switch from forward conduction to reverse blocking mode.
  • The package type and dimensions specify the physical size and shape of the diode and are usually given in the mechanical drawing section of the datasheet. For example, a diode may be packaged in a through-hole or surface-mount package with specific dimensions.

Electronic Diodes and Their Part Numbers

Rectifier Diodes

  • Small Signal Diode: 1N4148, 1N914
  • Schottky Diode: BAT54, BAT85
  • Silicon Controlled Rectifier: TYN616, C106D
  • PIN Diode: HP5082-2810, HSMP-386L

Zener Diodes

  • Zener Diode: 1N4728A, 1N5349B

LED and Laser Diodes

  • Light Emitting Diode (LED): 5mm Red LED, 3mm Green LED
  • Laser Diode: 650nm Red Laser, 405nm Blue Laser

Special Function Diodes

  • Tunnel Diode: 1N3716, NTT406AB
  • Varactor Diode: BB112, BB204
  • Transient Voltage Suppression Diode: P6KE36A, 1.5KE200A
  • Avalanche Diode: BZX84C5V6, P6KE100CA

Photodiodes

  • PIN Photodiodes: BPW34, SFH205F
  • Avalanche Photodiodes: S8664, C30932EH
  • Schottky Photodiodes: 1N5711, HSMS-2855-BLKG
  • MSM Photodiodes: YT201M, YT202M
  • InGaAs Photodiodes: G9933, G8941

Power Diodes

  • General Purpose Power Diodes: 1N4007, 1N5399
  • Fast Recovery Power Diodes: UF4007, FR107
  • Schottky Barrier Diodes: SB560, SB5100
  • Ultrafast Recovery Power Diodes: UF5404, UF5408
  • Super Barrier Diodes: SB540, SB570
  • Avalanche Diodes: MUR1100E, 1N4937GP
  • TVS Diodes (Transient Voltage Suppressor): P6KE15CA, 1.5KE400A
Posted on Leave a comment

What does sticky do in tkinter

In Tkinter, the sticky option is used to specify how a widget should expand to fill the space allotted to it within its container widget.

The sticky option is used when placing a widget using the grid geometry manager. When a widget is placed in a cell of the grid, it can be set to “stick” to one or more sides of the cell. The sticky option takes one or more of the following values:

  • N: stick to the top edge of the cell
  • S: stick to the bottom edge of the cell
  • E: stick to the right edge of the cell
  • W: stick to the left edge of the cell
  • NW: stick to the top-left corner of the cell
  • NE: stick to the top-right corner of the cell
  • SW: stick to the bottom-left corner of the cell
  • SE: stick to the bottom-right corner of the cell

For example, if you want a widget to fill the entire width of a cell and stick to the top edge of the cell, you can use:

widget.grid(row=0, column=0, columnspan=2, sticky='W' + 'E' + 'N')

This will place the widget in the first row, first column of the grid, and span two columns. The sticky option is set to 'W' + 'E' + 'N', which means the widget will stick to the left, right, and top edges of the cell, but not the bottom edge. As a result, the widget will expand horizontally to fill the width of the cell, but not vertically.

Example

import tkinter as tk

root = tk.Tk()

# Create a label widget and place it in the first row, first column of the grid
label = tk.Label(root, text="Hello, world!")
label.grid(row=0, column=0)

# Create a button widget and place it in the second row, first column of the grid
button = tk.Button(root, text="Click me!")
button.grid(row=1, column=0)

# Create an entry widget and place it in the second row, second column of the grid
entry = tk.Entry(root)
entry.grid(row=1, column=1, sticky='W')

# Create a text widget and place it in the third row, first column of the grid
text = tk.Text(root)
text.grid(row=2, column=0, columnspan=2, sticky='W'+'E'+'N'+'S')

branding_label = tk.Label(root, text="Powered by exasub.com")
branding_label.grid(row=3, column=0, columnspan=2, padx=10, pady=10, sticky='E')

root.mainloop()

In this example, we create a label widget, a button widget, an entry widget, and a text widget, and place them in a grid using the grid geometry manager.

The label widget is placed in the first row, first column of the grid, with no sticky option specified, so it will not expand to fill the cell.

The button widget is placed in the second row, first column of the grid, with no sticky option specified, so it will not expand to fill the cell.

The entry widget is placed in the second row, second column of the grid, with the sticky option set to ‘W’, so it will stick to the left edge of the cell and not expand to fill the cell.

The text widget is placed in the third row, first column of the grid, with the sticky option set to ‘W’+’E’+’N’+’S’, so it will stick to all four edges of the cell and expand to fill the entire cell.

Posted on Leave a comment

How to blink onboard LED on Raspberry Pi Pico W using Thonny IDE in Windows

The raspberry pi pico w has a LED on it.
This LED is not connected to the GPIO pins of RP2040 microcontroller directly.

As you can see in the image of the pinout taken from the official datasheet.
The onboard LED is connected to a pin ‘WL_GPIO0’.
WL_GPIO0 is an internal pin.

There are different ways to program the pico W.
The easiest method is to install thonny IDE. And install micropython on the pico w.

Download Thonny IDE

After you have installed thonny. Now connect you raspberry pi pico w board to the computer USB port while holding the onboard BOOTSEL button. Then follow the steps shown in the following images.

After you have done the above steps. You now have to install a MicroPython library.

picozero is a MicroPython library which has functions for Wifi and other RP2040 chip.

To complete the projects in this path, you need to install the picozero library as a Thonny package.

In Thonny, choose Tools > Manage packages.

Code

import machine
import time

# create a Pin object to control the LED on pin 'WL_GPIO0'
led_pin = machine.Pin('WL_GPIO0', machine.Pin.OUT)

# enter an infinite loop
while True:
    # set the LED pin to a high (on) state
    led_pin.value(1)
    # pause the program for one second
    time.sleep(1)
    # set the LED pin to a low (off) state
    led_pin.value(0)
    # pause the program for one second
    time.sleep(1)

In this program, we first import the machine module and the time module. The machine module provides access to hardware-level features on the Raspberry Pi Pico, while the time module provides functions for time-related operations.

Next, we create a Pin object called led_pin to control the LED connected to the pin labeled ‘WL_GPIO0’. The machine.Pin() function is used to create the led_pin object, with the first argument specifying the pin label and the second argument specifying that the pin is an output pin, i.e. we can set its state to high or low.

Then, we enter an infinite loop using the while True: statement. Within the loop, we use the value() method of the led_pin object to set the state of the LED pin to high (on) or low (off), with a one second delay between each state change using the time.sleep() function.

Comments are added to explain each line of code and make it easier to understand the purpose and function of the program.

Posted on Leave a comment

Board Specification of Raspberry Pi Model 3b+

Overview of the Raspberry Pi 3B+ board

  1. Processor and Memory
    • CPU: Broadcom BCM2837B0, Cortex-A53 (64-bit)
    • Clock speed: 1.4 GHz
    • RAM: 1GB LPDDR2 SDRAM
    • The Raspberry Pi 3B+ is powered by a Broadcom BCM2837B0 chipset, which includes a 1.4 GHz 64-bit quad-core ARM Cortex-A53 CPU.
    • The BCM2837B0 also includes a VideoCore IV GPU, which is capable of hardware-accelerated video decoding and encoding, 3D graphics rendering, and image processing.
    • The Raspberry Pi 3B+ comes with 1 GB of LPDDR2 SDRAM memory, which is shared between the CPU and GPU.
    • The LPDDR2 SDRAM on the Raspberry Pi 3B+ runs at 900 MHz, providing a maximum memory bandwidth of 7.2 GB/s.
    • The Raspberry Pi 3B+ also supports virtual memory, which allows it to use a portion of its SD card storage as swap space to increase the available memory.
    • The BCM2837B0 chipset includes a level 2 (L2) cache of 512 KB, which is shared between all four CPU cores.
    • The L2 cache on the Raspberry Pi 3B+ runs at the same speed as the CPU cores (1.4 GHz), providing fast access to frequently used data and instructions.
    • The BCM2837B0 chipset also includes a hardware random number generator, which can be used for cryptographic applications that require secure and unpredictable random numbers.
  2. Connectivity
    • Ethernet: Gigabit Ethernet over USB 2.0 (maximum throughput 300 Mbps)
    • Wireless: 2.4GHz and 5GHz IEEE 802.11.b/g/n/ac wireless LAN
    • Bluetooth: Bluetooth 4.2, Bluetooth Low Energy (BLE)
  3. Storage
    • microSD card slot for loading operating system and data storage
    • The Raspberry Pi 3B+ has a microSD card slot that supports the use of microSD, microSDHC, and microSDXC cards.
    • The microSD card slot on the Raspberry Pi 3B+ supports UHS-I bus speeds, which can provide faster data transfer rates than standard SD cards.
    • The Raspberry Pi 3B+ also supports booting from USB mass storage devices, such as USB flash drives or external hard drives.
    • The Raspberry Pi 3B+ supports the use of file systems such as ext4, NTFS, and FAT32 on external storage devices.
    • The maximum recommended microSD card size for the Raspberry Pi 3B+ is 32 GB, although larger cards can be used with some limitations.
  4. Multimedia
    • Video: H.264 (up to 1080p60), MPEG-4 (up to 1080p30), H.263 (up to 1080p30)
    • Audio: Stereo audio via 3.5mm jack, or HDMI
  5. GPIO
    • 40-pin GPIO header with support for SPI, I2C, and UART protocols
    • 40 GPIO pins are available in two rows of 20 pins each on the GPIO header.
    • The GPIO pins on the Raspberry Pi 3B+ operate at 3.3V logic levels and are not 5V tolerant. Connecting 5V devices directly to the GPIO pins can damage the Raspberry Pi.
    • The GPIO pins can source or sink up to 16 mA of current.
    • The GPIO pins can be configured as inputs or outputs, and can also be used for hardware PWM (Pulse Width Modulation) and hardware SPI (Serial Peripheral Interface) communication.
    • The GPIO pins are grouped into several GPIO banks, each with its own set of features and capabilities. These banks include the General Purpose Input/Output (GPIO) bank, the Serial Peripheral Interface (SPI) bank, the Inter-Integrated Circuit (I2C) bank, and the Universal Asynchronous Receiver-Transmitter (UART) bank.
    • The GPIO pins on the Raspberry Pi 3B+ can be accessed using a variety of programming languages and libraries, including Python, C, C++, and Node.js. The RPi.GPIO library, which is included with the Raspbian operating system, provides a simple and easy-to-use interface for controlling the GPIO pins using Python. Additionally, it is possible to access the GPIO pins using bare metal programming, which involves programming the Raspberry Pi directly without using an operating system. This method provides more control over the hardware and can be useful in applications where performance and real-time control are critical.
  6. Power
    • 5V DC via micro-USB connector, or GPIO header
  7. Form Factor
    • Dimensions: 88 x 56 x 19.5 mm
    • Weight: 46g
Posted on Leave a comment

Introduction to Bare Metal Programming on Raspberry Pi 3b+

What is Bare Metal Programming?

Bare metal programming is the practice of programming a computer or microcontroller without using an operating system or any other software layer between the hardware and the code. It involves writing code that directly interacts with the hardware, using low-level programming languages such as Assembly or C. This allows for greater control over the hardware, as you have direct access to the processor, memory, and other resources.

In the case of Raspberry Pi, bare metal programming involves writing code directly to the hardware, using low-level programming languages such as Assembly or C.

AdvantagesDisadvantages
Provides direct access to the hardware, enabling greater control over system resourcesRequires advanced knowledge of low-level programming languages such as Assembly or C
Avoids the overhead and complexity of operating systems and middlewareRequires more effort and time to develop and maintain code compared to high-level programming languages or using an operating system
Enables faster and more efficient code executionLack of abstraction and protection from hardware errors can lead to more complex and error-prone code
Ideal for applications with strict timing requirements or low-latency communication with hardware peripheralsDifficult to integrate with higher-level software stacks or libraries

To get started with bare metal programming on Raspberry Pi 3B+, you’ll need the following tools:

  1. Raspberry Pi 3B+: This is the main hardware component you’ll need to get started with bare metal programming on Raspberry Pi.
  2. MicroSD card: You’ll need a MicroSD card to store the operating system and your code. A capacity of 8GB or higher is recommended.
  3. Cross-compiler: This is a toolchain that allows you to compile your code on a different platform (such as a PC) and generate code that can run on the ARM-based Raspberry Pi. You can use the GNU ARM Embedded Toolchain or other cross-compilers.
  4. Text editor: You’ll need a text editor to write and edit your code. Some popular free options include Notepad++, Nano, and Visual Studio Code.
Posted on Leave a comment

How to Create a Resistor Color Code Calculator with GUI using Tkinter in Python

Resistor Color Code Calculator

exasub.com

This code is a Resistor Color Code Calculator. A resistor is an electronic component used in circuits to control the flow of electricity. The colors of the bands on the resistor indicate the resistance value of the resistor. This code allows you to select the color of the four bands on the resistor and then calculate the resistance value of the resistor.

The code uses a graphical user interface (GUI) built using a library called tkinter. The GUI consists of labels, dropdown menus, a button, and a link. The dropdown menus allow you to select the colors of the four bands on the resistor. The button, when pressed, calculates the resistance value of the resistor and displays it on the screen. The link is a hyperlink that takes you to a website.

The code defines two dictionaries that hold the color codes and tolerance values for resistors. The calculate_resistance function uses the selected colors to calculate the resistance value of the resistor. The open_website function opens a website when the link is clicked.

Code

import tkinter as tk
import webbrowser

# Define the color code values
color_codes = {
    "black": {"value": 0, "color": "#000000"},
    "brown": {"value": 1, "color": "#964B00"},
    "red": {"value": 2, "color": "#FF0000"},
    "orange": {"value": 3, "color": "#FFA500"},
    "yellow": {"value": 4, "color": "#FFFF00"},
    "green": {"value": 5, "color": "#008000"},
    "blue": {"value": 6, "color": "#0000FF"},
    "violet": {"value": 7, "color": "#8B00FF"},
    "gray": {"value": 8, "color": "#808080"},
    "white": {"value": 9, "color": "#FFFFFF"}
}

# Define the tolerance values
tolerances = {
    "brown": {"value": 1, "color": "#964B00"},
    "gold": {"value": 5, "color": "#FFD700"},
    "silver": {"value": 10, "color": "#C0C0C0"}
}

# Define the GUI
root = tk.Tk()
root.title("Resistor Color Code Calculator")

# Define the functions
def calculate_resistance(band1, band2, band3, band4):
    resistance_value = (color_codes[band1]["value"] * 10 + color_codes[band2]["value"]) * (10 ** color_codes[band3]["value"])
    if band4 != "none":
        tolerance_value = tolerances[band4]["value"]
        return f"Resistance value: {resistance_value} ohms, Tolerance: ±{tolerance_value}%"
    else:
        return f"Resistance value: {resistance_value} ohms"

def open_website():
    webbrowser.open_new("http://www.exasub.com")

# Define the GUI elements
label1 = tk.Label(root, text="Select the color of the first band:")
label1.grid(row=0, column=0)

band1_var = tk.StringVar(root)
band1_var.set("black")

band1_color_label = tk.Label(root, bg=color_codes[band1_var.get()]["color"], width=10)
band1_color_label.grid(row=0, column=1)

band1_dropdown = tk.OptionMenu(root, band1_var, *color_codes.keys(), command=lambda _: band1_color_label.config(bg=color_codes[band1_var.get()]["color"]))
band1_dropdown.grid(row=0, column=2)

label2 = tk.Label(root, text="Select the color of the second band:")
label2.grid(row=1, column=0)

band2_var = tk.StringVar(root)
band2_var.set("black")

band2_color_label = tk.Label(root, bg=color_codes[band2_var.get()]["color"], width=10)
band2_color_label.grid(row=1, column=1)

band2_dropdown = tk.OptionMenu(root, band2_var, *color_codes.keys(), command=lambda _: band2_color_label.config(bg=color_codes[band2_var.get()]["color"]))
band2_dropdown.grid(row=1, column=2)

label3 = tk.Label(root, text="Select the color of the third band:")
label3.grid(row=2, column=0)

band3_var = tk.StringVar(root)
band3_var.set("black")

band3_color_label = tk.Label(root, bg=color_codes[band3_var.get()]["color"], width=10)
band3_color_label.grid(row=2, column=1)

band3_dropdown = tk.OptionMenu(root, band3_var, *color_codes.keys(), command=lambda _: band3_color_label.config(bg=color_codes[band3_var.get()]["color"]))
band3_dropdown.grid(row=2, column=2)

label4 = tk.Label(root, text="Select the color of the fourth band (optional):")
label4.grid(row=3, column=0)

band4_var = tk.StringVar(root)
band4_var.set("gold")

band4_color_label = tk.Label(root, bg=tolerances[band4_var.get()]["color"], width=10)
band4_color_label.grid(row=3, column=1)

band4_dropdown = tk.OptionMenu(root, band4_var, *(["none"] + list(tolerances.keys())), command=lambda _: band4_color_label.config(bg=tolerances[band4_var.get()]["color"]))
band4_dropdown.grid(row=3, column=2)

calculate_button = tk.Button(root, text="Calculate", command=lambda: result_label.config(text=calculate_resistance(band1_var.get(), band2_var.get(), band3_var.get(), band4_var.get())))
calculate_button.grid(row=4, column=1)

result_label = tk.Label(root, text="", font=("Arial", 14))
result_label.grid(row=5, column=0, columnspan=3)

link_label = tk.Label(root, text="exasub.com", font=("Arial", 14), fg="blue", cursor="hand2")
link_label.grid(row=6, column=0, pady=10)
link_label.bind("<Button-1>", lambda event: open_website())

root.mainloop()

Posted on Leave a comment

How to Create a Digital Clock Using Python

A digital clock is a very common type of clock that displays the time in digits, as opposed to an analog clock that displays the time using clock hands. With Python, you can easily create a digital clock using the Tkinter GUI toolkit. In this article, we will show you how to create a digital clock using Python.

Step 1: Importing Required Libraries We need to import the following libraries to create a digital clock in Python:

from tkinter import *
import time

Here, we import the Tkinter library for creating the graphical user interface, and the time library for working with time and dates in Python.

Step 2: Creating the Digital Clock Class We will create a class called DigitalClock that contains the code for creating the digital clock.

class DigitalClock:
    def __init__(self, root):
        self.root = root
        self.root.title("Digital Clock")
        self.root.geometry("300x200")
        self.root.resizable(False, False)

        # Create a label for displaying the current time
        self.time_label = Label(root, text="", font=("Arial", 50))
        self.time_label.pack(pady=20)

        # Add your website name with a hyperlink
        self.link_label = Label(root, text="exasub.com", font=("Arial", 14), fg="blue", cursor="hand2")
        self.link_label.pack(pady=10)
        self.link_label.bind("<Button-1>", lambda event: self.open_website())

        # Update the time every second
        self.update_clock()

Here, we define the __init__ method that initializes the class with the root argument. We set the title of the window to “Digital Clock”, and set the window size to 300×200. We then create a label called time_label to display the current time with a font size of 50.

We also create another label called link_label that displays your website name with a hyperlink. When the user clicks on the link, the open_website method will be called.

Finally, we call the update_clock method to update the time every second.

Step 3: Updating the Clock We will now define the update_clock method that will update the clock every second.

def update_clock(self):
    # Get the current time and format it
    current_time = time.strftime("%H:%M:%S")
    self.time_label.config(text=current_time)

    # Schedule the next update after 1 second
    self.root.after(1000, self.update_clock)

Here, we get the current time using the strftime method of the time library, and format it in the HH:MM:SS format. We then set the text of the time_label to the current time using the config method.

We also schedule the next update after 1 second using the after method of the root window.

Step 4: Opening the Website We will define the open_website method that will open your website when the user clicks on the hyperlink.

def open_website(self):
    import webbrowser
    webbrowser.open_new("http://www.exasub.com")

Here, we import the webbrowser library and use the open_new method to open your website.

Step 5: Running the Program Finally, we will create the main method and run the program.

if __name__ == "__main__":
    root = Tk()
    clock = DigitalClock(root)
    root.mainloop()

Here is the complete code for creating a digital clock using Python:

from tkinter import *
import time

class DigitalClock:
    def __init__(self, root):
        self.root = root
        self.root.title("Digital Clock")
        self.root.geometry("300x200")
        self.root.resizable(False, False)

        # Create a label for displaying the current time
        self.time_label = Label(root, text="", font=("Arial", 50))
        self.time_label.pack(pady=20)

        # Add your website name with a hyperlink
        self.link_label = Label(root, text="exasub.com", font=("Arial", 14), fg="blue", cursor="hand2")
        self.link_label.pack(pady=10)
        self.link_label.bind("<Button-1>", lambda event: self.open_website())

        # Update the time every second
        self.update_clock()

    def update_clock(self):
        # Get the current time and format it
        current_time = time.strftime("%H:%M:%S")
        self.time_label.config(text=current_time)

        # Schedule the next update after 1 second
        self.root.after(1000, self.update_clock)

    def open_website(self):
        import webbrowser
        webbrowser.open_new("http://www.exasub.com")

if __name__ == "__main__":
    root = Tk()
    clock = DigitalClock(root)
    root.mainloop()