Posted on Leave a comment

Derivative Control Demo in Control Systems Engineering Using Slider in Tkinter

Control systems engineering plays a crucial role in various industries, enabling precise and efficient control of processes and systems. One fundamental concept in control systems is derivative control, which helps improve the system’s response to changes and disturbances. In this blog post, we’ll explore a simple demonstration of derivative control using a slider in Tkinter, a popular Python GUI toolkit.

Understanding Derivative Control

Derivative control is a control strategy that utilizes the derivative of the error signal to adjust the control output. By calculating the rate of change of the error, derivative control can anticipate the system’s response to changes and take corrective actions to minimize the error. It provides a damping effect and improves the system’s stability and responsiveness.

The derivative control algorithm consists of three main components:

  1. Derivative Control Function: The derivative control function calculates the derivative term based on the current error, previous error, and a time interval. The derivative term is obtained by multiplying the derivative gain (Kd) with the difference in error divided by the time interval.
  2. Main Loop: The main loop of the control system continuously monitors the process variable and applies derivative control to update the control output. It calculates the error by subtracting the desired setpoint from the process variable. The derivative control function is then invoked to compute the derivative term. The control output is actuated, and the previous error is updated.
  3. Slider and GUI: To interact with the control system, we’ll create a graphical user interface (GUI) using Tkinter. A slider widget allows us to adjust the feedback stimulus, representing the process variable. Labels display the feedback stimulus value and the computed derivative term in real-time. Additionally, a hyperlink is provided to visit a website for further information.

Implementation with Tkinter

Let’s delve into the implementation of the derivative control demo using Tkinter. Here’s the code:

import tkinter as tk
import time
import webbrowser

# Derivative control function
def derivative_control(error, prev_error, dt):
    # Derivative gain
    Kd = 0.2
    derivative_term = Kd * (error - prev_error) / dt
    return derivative_term

# Main loop
def main_loop():
    setpoint = 50  # Desired setpoint
    process_variable = 0  # Initial process variable
    prev_error = 0  # Previous error
    dt = 0.1 * 9  # Time interval for derivative control
    while True:
        # Read process variable from the slider
        process_variable = slider.get()

        # Calculate the error
        error = setpoint - process_variable

        # Apply derivative control
        derivative_term = derivative_control(error, prev_error, dt)

        # Actuate the control signal (in this example, update the label)
        control_label.configure(text="Derivative Term: {:.2f}".format(derivative_term))

        # Update the previous error
        prev_error = error

        time.sleep(dt)  # Sleep for the time interval


# Callback function for the slider
def slider_callback(value):
    feedback_label.configure(text="Feedback Stimulus: {:.2f}".format(float(value)))

# Open exasub.com in a web browser
def open_link(event):
    webbrowser.open("http://www.exasub.com")

# Create the main Tkinter window
window = tk.Tk()
window.title("Derivative Control Demo")

# Create the slider for adjusting the feedback stimulus
slider = tk.Scale(window, from_=0, to=100, orient=tk.HORIZONTAL, length=300, command=slider_callback)
slider.pack()

# Create a label to display the feedback stimulus value
feedback

_label = tk.Label(window, text="Feedback Stimulus: {:.2f}".format(slider.get()))
feedback_label.pack()

# Create a label to display the derivative term value
control_label = tk.Label(window, text="Derivative Term: ")
control_label.pack()

# Add a link to exasub.com
link = tk.Label(window, text="Visit exasub.com", fg="blue", cursor="hand2", font=("Arial", 14))
link.pack()
link.bind("<Button-1>", open_link)

# Start the main loop in a separate thread
import threading
main_loop_thread = threading.Thread(target=main_loop)
main_loop_thread.start()

# Start the Tkinter event loop
window.mainloop()

Exploring the Code

Let’s break down the code to understand how the derivative control demo works:

  1. We begin by importing the necessary modules: tkinter for GUI, time for time-related operations, and webbrowser for opening web links.
  2. The derivative_control function calculates the derivative control term based on the error, previous error, and a specified time interval. It multiplies the derivative gain (Kd) with the difference in error and divides it by the time interval. Adjusting the value of Kd can impact the system’s response.
  3. The main_loop function serves as the central control loop of the demo. It sets the desired setpoint and initializes variables for the process variable and previous error. The time interval (dt) determines the frequency of derivative control updates. Within the loop, the process variable is read from the slider, the error is calculated, derivative control is applied, and the control output is displayed in the GUI label. The previous error is updated, and the loop pauses for the specified time interval.
  4. The slider_callback function is triggered whenever the slider value changes. It updates the feedback label to display the current value of the feedback stimulus, representing the process variable.
  5. The open_link function opens the “exasub.com” website in a web browser when the “Visit exasub.com” link is clicked. This functionality provides an opportunity to learn more about derivative control or related topics.
  6. The main Tkinter window is created, titled “Derivative Control Demo”.
  7. A slider widget is added to the window, allowing the user to adjust the feedback stimulus. It spans from 0 to 100, is oriented horizontally, and has a length of 300 pixels. The slider_callback function is bound to this slider to update the feedback label.
  8. A label is created to display the current value of the feedback stimulus.
  9. Another label is created to display the computed derivative term. Initially, it displays the placeholder text “Derivative Term: “.
  10. A hyperlink labeled “Visit exasub.com” is added to the window. It appears in blue and changes the cursor to a hand when hovered over. The open_link function is bound to this label to open the specified website.
  11. The main loop is started in a separate thread using the threading module. This allows the control loop to run concurrently with the Tkinter event loop and ensures the GUI remains responsive.
  12. Finally, the Tkinter event loop is started using the mainloop() method of the window object. It listens for user interactions and updates the GUI accordingly.

Running the Derivative Control Demo

To run the derivative control demo, you’ll need to have Python and the Tkinter library installed. Save the code in a Python file (e.g., derivative_control_demo.py) and execute it. A window will appear with a slider and two labels.

Adjusting the slider will update the feedback stimulus

value label in real-time. As you adjust the slider, the derivative control algorithm will calculate the derivative term, which will be displayed in the “Derivative Term” label. The calculated derivative term reflects the system’s response to changes in the feedback stimulus.

Additionally, clicking the “Visit exasub.com” link will open a web browser and direct you to the “exasub.com” website, providing an opportunity to explore further resources on derivative control or related topics.

Conclusion

In this blog post, we’ve explored a derivative control demo implemented using Tkinter in Python. By adjusting a slider representing the feedback stimulus, you can observe the real-time calculation of the derivative term. This demonstration showcases the principles of derivative control and its role in control systems engineering.

Understanding derivative control and its application can be valuable in various fields, such as robotics, industrial automation, and process control. By manipulating the derivative gain and other control parameters, engineers can fine-tune the system’s response to optimize performance, stability, and efficiency.

By experimenting with this derivative control demo and further exploring control systems engineering, you can deepen your understanding of control strategies and their impact on system behavior.

Posted on Leave a comment

Integral Control Demo in Control Systems Engineering Using Slider in Tkinter

Introduction:

Control systems engineering plays a crucial role in regulating and optimizing various processes in industries, robotics, and automation. One fundamental concept in control systems is integral control, which aims to reduce steady-state error and improve system performance. In this blog post, we will explore integral control, its implementation in Python using tkinter, and discuss its importance in control systems.

Understanding Integral Control:

Integral control is a control technique that integrates the error signal over time and uses the accumulated integral term to adjust the control signal. It helps to compensate for any steady-state error and drive the system towards the desired setpoint. The integral control component is typically employed alongside proportional and derivative control, forming the PID control algorithm.

Implementation using Python tkinter:

To better grasp the concept of integral control, let’s examine a Python code snippet that demonstrates its implementation using the tkinter library:

import tkinter as tk
import time
import threading
import webbrowser
# Integral control function
def integral_control(error, integral_sum):
    # Integral gain
    Ki = 0.1
    integral_sum += error
    integral_term = Ki * integral_sum
    return integral_term, integral_sum

# Main loop
def main_loop():
    setpoint = 50  # Desired setpoint
    process_variable = 0  # Initial process variable
    integral_sum = 0  # Accumulated integral sum
    while True:
        # Read process variable from the slider
        process_variable = slider.get()

        # Calculate the error
        error = setpoint - process_variable

        # Apply integral control
        integral_term, integral_sum = integral_control(error, integral_sum)

        # Actuate the control signal (in this example, update the label)
        control_label.configure(text="Integral Term: {:.2f}".format(integral_term))

        time.sleep(0.1)  # Sleep for 0.1 seconds


# Callback function for the slider
def slider_callback(value):
    feedback_label.configure(text="Feedback Stimulus: {:.2f}".format(float(value)))

# Open exasub.com in a web browser
def open_link(event):
    webbrowser.open("http://www.exasub.com")

# Create the main Tkinter window
window = tk.Tk()
window.title("Integral Control Demo")

# Create the slider for adjusting the feedback stimulus
slider = tk.Scale(window, from_=0, to=100, orient=tk.HORIZONTAL, length=300, command=slider_callback)
slider.pack()

# Create a label to display the feedback stimulus value
feedback_label = tk.Label(window, text="Feedback Stimulus: {:.2f}".format(slider.get()))
feedback_label.pack()

# Create a label to display the integral term value
control_label = tk.Label(window, text="Integral Term: ")
control_label.pack()

# Add a link to exasub.com
link = tk.Label(window, text="Visit exasub.com", fg="blue", cursor="hand2", font=("Arial", 14))
link.pack()
link.bind("<Button-1>", open_link)

# Start the main loop in a separate thread
import threading
main_loop_thread = threading.Thread(target=main_loop)
main_loop_thread.start()

# Start the Tkinter event loop
window.mainloop()

Explanation:

In the code snippet, we begin by setting up the graphical user interface (GUI) using tkinter. The GUI consists of a slider for adjusting the feedback stimulus, labels to display the feedback stimulus value and the integral term value, and a link to a website. The slider is used to simulate the process variable, while the labels provide real-time feedback on the control system’s behavior.

The integral control algorithm is implemented within the integral_control function. It calculates the integral term based on the error and the accumulated integral sum. The integral gain, represented by Ki, determines the contribution of the integral term to the control signal. By adjusting the integral gain, the system’s response can be fine-tuned.

The main loop continuously reads the process variable from the slider and calculates the error by comparing it to the desired setpoint. It then calls the integral_control function to compute the integral term. The integral term is used to actuate the control signal or update the label in the GUI, providing a visual representation of the control system’s behavior.

Importance of Integral Control:

Integral control is essential in control systems engineering for several reasons:

  1. Reducing Steady-state Error: Integral control helps to eliminate or minimize any steady-state error, ensuring that the system reaches and maintains the desired setpoint accurately.
  2. System Stability: By continuously adapting the control signal based on the accumulated error, integral control improves the system’s stability and responsiveness. It enables the system to overcome disturbances and maintain optimal performance.
  3. Robustness: Integral control enhances the control system’s robustness by accounting for systematic biases and external disturbances. It enables the system to adapt to changing conditions and maintain accurate control.

Conclusion:

Integral control is a key component of control systems engineering, enabling precise regulation and optimization of processes. By integrating the error over time, integral control reduces steady-state error and enhances system performance. In this blog post, we explored integral control and its implementation using Python’s tkinter library. We also discussed the importance of integral control in achieving robust and stable control systems.

As you delve further into control systems engineering, consider exploring additional control techniques, such as proportional and derivative control, to create more advanced control systems. Experimenting with different control strategies will deepen your understanding of control systems and their practical applications.

Posted on Leave a comment

Proportional Control Demo using Slider in Tkinter

Understanding Proportional Control:
Proportional control is a basic feedback control technique that adjusts the control signal proportionally to the error between a desired setpoint and the process variable. The process variable represents the current state of the system being controlled. By continuously monitoring and adjusting the control signal, the system strives to minimize the error and achieve the desired setpoint.

I have created this simple program using python and tkinter library.

When this program is run. A slider will appear which you can move.

A set point of 50 is given as the default value.
When you start the program the slider will be at 0 position. As you increase your slider you will see a change in the control signal parameter.

This Control Signal will be 0 at your set point which is 50.
As you go past the set point the control signal will become negative.

The system will keep changing the control signal to make the slider reach it’s set point.

Code

import tkinter as tk
import time
import webbrowser

# Proportional control function
def proportional_control(error):
    # Proportional gain
    Kp = 0.5
    control_signal = Kp * error
    return control_signal

# Main loop
def main_loop():
    setpoint = 50  # Desired setpoint
    process_variable = 0  # Initial process variable
    while True:
        # Read process variable from the slider
        process_variable = slider.get()

        # Calculate the error
        error = setpoint - process_variable

        # Apply proportional control
        control_signal = proportional_control(error)

        # Actuate the control signal (in this example, update the label)
        control_label.configure(text="Control Signal: {:.2f}".format(control_signal))

        time.sleep(0.1)  # Sleep for 0.1 seconds


# Callback function for the slider
def slider_callback(value):
    feedback_label.configure(text="Feedback Stimulus: {:.2f}".format(float(value)))

# Open exasub.com in a web browser
def open_link(event):
    webbrowser.open("http://www.exasub.com")

# Create the main Tkinter window
window = tk.Tk()
window.title("Proportional Control Demo")

# Create the slider for adjusting the feedback stimulus
slider = tk.Scale(window, from_=0, to=100, orient=tk.HORIZONTAL, length=300, command=slider_callback)
slider.grid(row=0, column=0, columnspan=2, padx=10, pady=10)

# Create a label to display the feedback stimulus value
feedback_label = tk.Label(window, text="Feedback Stimulus: {:.2f}".format(slider.get()))
feedback_label.grid(row=1, column=0, padx=10, pady=5)

# Create a label to display the control signal value
control_label = tk.Label(window, text="Control Signal: ")
control_label.grid(row=1, column=1, padx=10, pady=5)

# Add a link to exasub.com
link = tk.Label(window, text="Visit exasub.com", fg="blue", cursor="hand2", font=("Arial", 14))
link.grid(row=2, column=0, columnspan=2, padx=10, pady=5)
link.bind("<Button-1>", open_link)

# Start the main loop in a separate thread
import threading
main_loop_thread = threading.Thread(target=main_loop)
main_loop_thread.start()

# Start the Tkinter event loop
window.mainloop()


Let’s dive into the code provided and understand how the proportional control demo works.

# Main loop
def main_loop():
    setpoint = 50  # Desired setpoint
    process_variable = 0  # Initial process variable
    while True:
        # Read process variable from the slider
        process_variable = slider.get()

        # Calculate the error
        error = setpoint - process_variable

        # Apply proportional control
        control_signal = proportional_control(error)

        # Actuate the control signal (in this example, update the label)
        control_label.configure(text="Control Signal: {:.2f}".format(control_signal))

        time.sleep(0.1)  # Sleep for 0.1 seconds

Explanation of the Code:
The provided code demonstrates a simple scenario where the process variable is obtained from a slider widget. Here’s a breakdown of the code’s key components:

  1. Setpoint: The setpoint variable represents the desired value or setpoint that we want the process variable to reach.
  2. Process Variable: The process_variable variable holds the current value of the system being controlled, obtained from the slider widget.
  3. Error Calculation: The error is calculated by subtracting the process variable from the setpoint. The error represents the deviation of the process variable from the desired value.
  4. Proportional Control: The proportional_control function, not provided in the code snippet, applies the proportional control algorithm. This function takes the error as input and computes the control signal accordingly.
  5. Actuation: In this example, the control signal is applied by updating a label (control_label) to display the control signal value. In a real-world scenario, the control signal would be used to actuate a physical system, such as adjusting a motor’s speed or a valve’s position.
  6. Timing: To ensure the control loop operates at a reasonable speed, a small delay of 0.1 seconds is introduced using time.sleep(0.1). This delay allows the control system to stabilize before the next iteration.

Understanding Proportional Control:
Proportional control works by adjusting the control signal in proportion to the error. The control signal can be interpreted as an effort or corrective action to reduce the error. In this demo, the control signal is calculated by the proportional_control function, which is not provided in the code snippet.

The proportional control algorithm typically involves multiplying the error by a constant gain, known as the proportional gain (Kp). The control signal is then obtained by multiplying the error with Kp. The value of Kp determines the system’s responsiveness to the error, and finding the appropriate gain is crucial for stable and efficient control.

Conclusion:
The proportional control demo showcased in this blog post provides a basic understanding of how proportional control operates within a control system. By continuously adjusting the control signal based on the error between the setpoint and the process variable, proportional control helps bring the system closer to the desired state. Proportional control is just one of many control techniques, and understanding its principles is vital for delving into more advanced control strategies.

Remember that proportional control alone may not be sufficient for complex systems, as it lacks the ability to anticipate and account for system dynamics. Nonetheless, it forms the foundation for more advanced control techniques like PID (Proportional-Integral-Derivative) control.

So go ahead, experiment with the demo code, and explore the fascinating world of control systems!

Posted on Leave a comment

How to Generate Combinations of the Component from Four Text Files using Python & tkinter

This program generates a random combination of components. This can be a fun program.
It creates the combination of all the components in the four list.

For example; if each list contains 5 words. Then the total number of combinations would be 5 x 5 x 5 x 5 = 625

Code

import random
import tkinter as tk
from tkinter import messagebox
import itertools
import webbrowser


# Create the GUI window
window = tk.Tk()
window.title("List Shuffler")

# Create the text boxes for file names
micros_textbox = tk.Entry(window, width=50)
micros_textbox.insert(0, "micros.txt")
micros_textbox.grid(row = 0, column = 0, pady = 5)

sensors_textbox = tk.Entry(window, width=50)
sensors_textbox.insert(0, "sensor.txt")
sensors_textbox.grid(row = 1, column = 0, pady = 5)

inputs_textbox = tk.Entry(window, width=50)
inputs_textbox.insert(0, "inputs.txt")
inputs_textbox.grid(row = 2, column = 0, pady = 5)

displays_textbox = tk.Entry(window, width=50)
displays_textbox.insert(0, "displays.txt")
displays_textbox.grid(row = 3, column = 0, pady = 5)

# Create the label for the result
result_label = tk.Text(window, height=10, width=50)
result_label.grid(row = 0, column = 1,rowspan = 5, pady = 5)

# Define the function to shuffle the lists
def shuffle_lists():
    # Open the first file and read in its contents
    with open(micros_textbox.get(), "r") as f:
        A = f.read().splitlines()

    # Open the second file and read in its contents
    with open(sensors_textbox.get(), "r") as f:
        B = f.read().splitlines()

    # Open the third file and read in its contents
    with open(inputs_textbox.get(), "r") as f:
        C = f.read().splitlines()

    with open(displays_textbox.get(), "r") as f:
        D = f.read().splitlines()

    # Shuffle the lists
    random.shuffle(A)
    random.shuffle(B)
    random.shuffle(C)
    random.shuffle(D)

    # Select one item from each list and combine them into a string
    result = A[0] + " + " + B[0] + " + " + C[0] + " + " + D[0] +"\n\n"

    # Update the label with the result
    result_label.insert(tk.INSERT,result)
def generate_combinations():
    # Open the first file and read in its contents
    with open(micros_textbox.get(), "r") as f:
        A = f.read().splitlines()

    # Open the second file and read in its contents
    with open(sensors_textbox.get(), "r") as f:
        B = f.read().splitlines()

    # Open the third file and read in its contents
    with open(inputs_textbox.get(), "r") as f:
        C = f.read().splitlines()

    with open(displays_textbox.get(), "r") as f:
        D = f.read().splitlines()

    # Get all the combinations of the lists
    combinations = list(itertools.product(A, B, C, D))

    # Write the combinations to a text file
    with open("combinations.txt", "w") as f:
        for combination in combinations:
            f.write(' + '.join(combination) + "\n")

    # Show a message box with the number of combinations generated
    messagebox.showinfo("Combinations Generated", f"{len(combinations)} combinations were generated and saved to combinations.txt.")


# Create the button to shuffle the lists
shuffle_button = tk.Button(window, text="Shuffle", command=shuffle_lists)
shuffle_button.grid(row = 4, column = 0, pady = 5)
# Add a button to generate the combinations
generate_button = tk.Button(window, text="Generate Combinations", command=generate_combinations)
generate_button.grid(row = 5, column = 0, pady = 5)

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

link_label = tk.Label(window, 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())
# Run the GUI
window.mainloop()
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 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()
Posted on Leave a comment

What is turtle.Turtle() in python?

In Python, turtle.Turtle() is a function that creates and returns a new turtle object that can be used to draw graphics on a canvas.

The turtle graphics library in Python provides a simple way to create graphics and animations by allowing you to control a virtual turtle that moves on a canvas. The turtle can be moved around the canvas using commands such as forward(), backward(), left(), right(), etc.

To use the turtle graphics library, you first need to import the turtle module. Then, you can create a new turtle object using the turtle.Turtle() function. For example, the following code creates a new turtle and moves it forward by 100 units:

import turtle

t = turtle.Turtle()
t.forward(100)

You can also customize the appearance and behavior of the turtle object by setting various attributes such as its color, size, shape, and speed. For example, the following code creates a red turtle with a size of 5 and a speed of 2:

import turtle

t = turtle.Turtle()
t.color("red")
t.pensize(5)
t.speed(2)
t.forward(100)

Overall, the turtle.Turtle() function is the starting point for creating and controlling turtle objects in the turtle graphics library.

Posted on Leave a comment

How to make comments in python

In Python, you can make comments using the hash symbol (#).

Any text that appears after the hash symbol (#) on the same line is considered a comment and is ignored by the Python interpreter.

For example:

# This is a comment
print("Hello, world!")  # This is also a comment

In the above example, the first line is a comment, and it is ignored by the Python interpreter. The second line is a print statement, which will print “Hello, world!” to the console when executed. The third line is another comment, which is also ignored.

You can also use multi-line comments by enclosing them in triple quotes (“”” “””). For example:

"""
This is a multi-line
comment in Python.
"""

print("Hello, world!")

In this example, the first three lines are a multi-line comment, and they are ignored by the Python interpreter. The fourth line is a print statement, which will print “Hello, world!” to the console when executed.

Posted on Leave a comment

How to make UART Serial Console using Pyserial, Tkinter in python

Screenshot

The serial console is written in a python programming language. The GUI is made using the Tkinter library and the serial interface functions are provided by the pyserial library.

you can install pyserial from command prompt(windows)/terminal(linux)

Python Code

from tkinter import *
from tkinter import ttk
import serial
import serial.tools.list_ports
import datetime
import threading
import multiprocessing
import os

#for printing debugging messages in console
dbg = 0

gRoot = Tk()
#gRoot.geometry("480x280")
gRoot.title("Serial Console")
sty = ttk.Style()
sty.theme_use("alt")
gRoot.columnconfigure(0,weight=1)
gRoot.rowconfigure(0,weight=1)
#sty.configure("gframe.TFrame",background="white")
gFrame = ttk.LabelFrame(gRoot,text="Connection Setting",padding=10)
gFrame.grid(column=1,row=1, sticky=(W,E))

#Frame for COM messages

gFrame21 = ttk.Frame(gRoot,padding=10)
gFrame21.grid(column=2,row=1, sticky=(W))
#gRoot.resizable(0,0)


for x in range(10):
    gFrame.columnconfigure(x,weight = x)
    gFrame.rowconfigure(x,weight = x)
    
label1=ttk.Label(gFrame, text = "Serial Console")
label1.grid(column=2,row=0)
gFrame.rowconfigure(0,weight=2)

sty.configure("label2.TLabel",borderwidth=4,relief="ridge",foreground="red",ipadx=10)
label2=ttk.Label(gFrame,sty="label2.TLabel", text = "Select Com Port")
label2.grid(column=1,row=1, sticky = (N,E,W,S))

"""
Com Port List
"""
#Start
ports = serial.tools.list_ports.comports()
com_port_list = [com[0] for com in ports]
com_port_list.insert(0,"Select an Option")
if dbg == 1:
    print(com_port_list)
#END
com_value_inside = StringVar()
baud_value_inside = StringVar()
baud_menu = ttk.OptionMenu(gFrame,baud_value_inside,"select baud rate","9600",
                           '19200','28800','38400','57600','76800',
                           '115200','128000','153600','230400','256000','460800','921600')
baud_menu.grid(column=3, row=1, sticky = (E))
def com_port_list_update():
    global ports
    global com_port_list
    ports = serial.tools.list_ports.comports()
    com_port_list = [com[0] for com in ports]
    com_port_list.insert(0,"Select an Option")
    if dbg == 1:
        print(com_port_list)
    com_menu = ttk.OptionMenu(gFrame,com_value_inside,*com_port_list)
    com_menu.grid(column=2, row=1, sticky = (E))
    #Frame for the COM LIST
    gRoot_com_list = Toplevel(gRoot)
    x = gRoot.winfo_x()
    y = gRoot.winfo_y()
    gRoot_com_list.geometry("+%d+%d" %(x+200,y+200))
    gFrame01 = ttk.Frame(gRoot_com_list,padding=10)
    gFrame01.grid(column=0,row=1, sticky=(W))
    #Create a horizontal scrollbar
    scrollbar = ttk.Scrollbar(gFrame01, orient= 'horizontal')
    scrollbar.grid(column=1,row=2, sticky=W+E)

    Lb1 = Listbox(gFrame01, xscrollcommand = 1, width = 50, font= ('Helvetica 8 bold'))
    counter = 0;
    for x in ports:
        Lb1.insert(counter, str(x))
    #print (counter)
    counter += 1
    Lb1.grid(column=1,row=1, sticky=W+E)
    Lb1.config(xscrollcommand= scrollbar.set)

    #Configure the scrollbar
    scrollbar.config(command= Lb1.xview)


def serial_print():
    global serFlag
    global ser
    global counter1
    x =""
    #print("Task 1 assigned to thread: {}".format(threading.current_thread().name))
    #print("ID of process running task 1: {}".format(os.getpid()))
    if(serFlag):
        if(ser.in_waiting>0):
            #
            try:
                x = ser.read(ser.in_waiting)
                #x = ser.readline(ser.in_waiting)
                #x = ser.read_until(expected='\n', size=ser.in_waiting)
                #print(x)
                y = str(counter1)+": "+str(datetime.datetime.now())+" -> "+str(x.decode())
                Lb2.insert(counter1, str(y))
                Lb2.see("end")
                #print (counter1)
                counter1 += 1
                #gFrame.after(100,serial_print)
            except:
                pass
        ser.flush()
        gFrame.after(100,serial_print)


ser = serial.Serial()
serFlag = 0
def serial_connect(com_port,baud_rate):
    global ser
    ser.baudrate = baud_rate
    ser.port = com_port
    ser.timeout = 1
    ser._xonxoff=1
    ser.bytesize=serial.EIGHTBITS
    ser.parity=serial.PARITY_NONE
    ser.stopbits=serial.STOPBITS_ONE
    ser.open()
    global serFlag
    serFlag = 1
    
    t1 = threading.Thread(target = serial_print, args = (), daemon=1)
    t1.start()
    #t1.join()
    """
    P1 = multiprocessing.Process(target = serial_print, args=())
    P1.start()
    P1.join()
    """
    #serial_print()
counter1 = 0;


    
def serial_close():
    global ser
    global serFlag
    serFlag = 0
    ser.close()
    
def submit_value():
    if dbg == 1:
        print("selected option: {}".format(com_value_inside.get()))
        print(" Baud Rate {}".format(baud_value_inside.get()))
    serial_connect(com_value_inside.get(),baud_value_inside.get())


Lb2 = Listbox(gFrame21, width = 100, xscrollcommand = 1)
Lb2.grid(column=1, row = 1, sticky = W+E)
Sb2 = ttk.Scrollbar(gFrame21,orient = 'vertical')
Sb2.config(command=Lb2.yview)
Sb2.grid(column = 2,row =1, sticky=N+S)
Sb2v = ttk.Scrollbar(gFrame21,orient = 'horizontal')
Sb2v.grid(column = 1,row =2, sticky=W+E)
Sb2v.config(command = Lb2.xview)
Lb2.configure(xscrollcommand = Sb2v.set, yscrollcommand = Sb2.set)

def clear_listbox():
    Lb2.delete(0,END)
    
subBtn = ttk.Button(gFrame,text="submit",command = submit_value)
subBtn.grid(column=4,row=1, sticky = (E))

RefreshBtn = ttk.Button(gFrame,text="Get List",command = com_port_list_update)
RefreshBtn.grid(column=2,row=2, sticky = (E))



closeBtn = ttk.Button(gFrame,text="Disconnect",command = serial_close)
closeBtn.grid(column=4,row=2, sticky = (E))

clearBtn = ttk.Button(gFrame,text="Clear Messages",command = clear_listbox)
clearBtn.grid(column=3,row=2, sticky = (E))



"""
#Add a Listbox Widget
listbox = Listbox(win, width= 350, font= ('Helvetica 15 bold'))
listbox.pack(side= LEFT, fill= BOTH)

#Add values to the Listbox
for values in range(1,101):
   listbox.insert(END, values)
"""
def donothing():
   filewin = Toplevel(gRoot)
   button = Button(filewin, text="Do nothing button")
   button.pack()

def About_me():
   filewin = Toplevel(gRoot)
   Label1 = Label(filewin, text = "EXASUB.COM").pack()
   button = Button(filewin, text="Quit", command = filewin.destroy)
   button.pack()

menubar = Menu(gRoot)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=donothing)
filemenu.add_command(label="Open", command=donothing)
filemenu.add_command(label="Save", command=donothing)
filemenu.add_command(label="Save as...", command=donothing)
filemenu.add_command(label="Close", command=donothing)

filemenu.add_separator()

filemenu.add_command(label="Exit", command=gRoot.quit)
menubar.add_cascade(label="File", menu=filemenu)
editmenu = Menu(menubar, tearoff=0)
editmenu.add_command(label="Undo", command=donothing)

editmenu.add_separator()

editmenu.add_command(label="Cut", command=donothing)
editmenu.add_command(label="Copy", command=donothing)
editmenu.add_command(label="Paste", command=donothing)
editmenu.add_command(label="Delete", command=donothing)
editmenu.add_command(label="Select All", command=donothing)

menubar.add_cascade(label="Edit", menu=editmenu)
helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="Help Index", command=donothing)
helpmenu.add_command(label="About...", command=donothing)
menubar.add_cascade(label="Help", menu=helpmenu)
menubar.add_command(label = "EXASUB.com", command = About_me)
menubar.add_separator()
menubar.add_command(label = "Quit", command = gRoot.destroy)

gRoot.config(menu=menubar)
gRoot.mainloop()