ChatGPT and Interfacing With Digital View LCD Controller Boards

I was interested to see if ChatGPT could help write apps to interface with Digital View LCD controller boards. To set a bit of context, all Digital View LCD controller boards support RS-232, some models have quite extensive command sets with the option for us to add more on a custom engineering basis if needed. I copy pasted the complete RS-232 command set section from the controller board manual to ChatGPT as a starting point.

A PC running Windows or a small custom circuit based on a microcontroller are two examples I thought to start with. Having worked through this with various iterations I then asked it to write the blog below for me, though I should admit I spent some time getting to these results.

UPDATE 18 Jul 2023: Shown below are the initial user interface results from compiling the code ChatGPT provided. There is an omission in the code to the extent that it only provides a one time press, so I am going through another iteration. Also, I asked ChatGPT for suggestions of other capabilities, the results are noted below.

Harnessing the Power of ChatGPT for Serial Communications: Interfacing with Digital View LCD Controllers

In this post, we will explore how to leverage the power of AI, specifically OpenAI’s ChatGPT, to write applications that interface with Digital View LCD controllers, like the SVX-4096. With the help of the language model, we will generate code snippets for different platforms ranging from Windows-based PCs to Microchip-based circuits.

Context: As an example, we’ll use a Python application with a graphical user interface (GUI) that communicates with an SVX-4096 LCD controller board via a serial port to turn the backlight on and off. But don’t worry! We’ll translate this to Visual Basic for Windows PC applications and Microchip PIC assembly language for embedded systems.

Python Application Overview

Before delving into translations, let’s have a look at the Python GUI application that turns the backlight of the LCD on and off. The application has several key features:

  • It allows users to specify the COM port their SVX-4096 board is connected to.
  • It uses a baud rate of 9600 for serial communication.
  • The command 0xe1, ‘0’ is used to turn off the backlight and 0xe1, ‘1’ to turn it on.
  • The application uses the acknowledge command (0xc1) to confirm commands are received, as specified in the SVX-4096 manual.
  • It also includes a visual on/off switch for easy operation.
  • Finally, it incorporates error handling and response reading to ensure that commands are executed correctly.

Compiling Python Application into a Standalone Executable

Let’s conclude with instructions for compiling the Python application into a standalone executable (.exe) file that can run on a Windows-based PC:

  1. Install PyInstaller: First, you’ll need to install PyInstaller. You can do this by running pip install pyinstaller in your command prompt.
  2. Build the Executable: Navigate to the directory of your Python script and use the command pyinstaller --onefile your_script.py replacing your_script.py with the name of your Python file. This will create a single .exe file.
  3. Locate the Executable: The .exe file will be located in the dist folder within your Python script’s directory.

And there you have it! This is how you can use ChatGPT to write applications that leverage the RS-232 functions on Digital View LCD controller boards such as the SVX-4096. The potential applications of AI in streamlining and enhancing software development are immense, and this is just the beginning. So, have fun exploring and pushing the boundaries of what you can do with AI like ChatGPT!

[JH note: The following is the actual ChatGPT prompt I used to write the Python code…

Can you write a Python application with a graphical user interface that communicates with an SVX-4096 LCD controller board via a serial port to turn the backlight on and off? The application should:

  • Allow the user to enter the COM port their SVX-4096 board is connected to. Use a baud rate of 9600 for serial communication. Use the command 0xe1, ‘0’ to turn off the backlight and 0xe1, ‘1’ to turn on the backlight.
  • Enable acknowledgments via the acknowledge command (0xc1), as specified in the SVX-4096 manual.
  • Have a visual on/off switch that corresponds to the function of the app. Include error handling and responses from the SVX-4096 controller to ensure that commands are executed correctly.
  • This should include reading responses from the serial port and verifying the command acknowledge responses.
  • Finally, provide instructions for compiling the Python application into a standalone executable (.exe) file that can run on a Windows-based PC.

I then extended the code with requests to ChatGPT:

  • Add a checkbox for the user to specify whether they want the COM port to stay open while the application is running.
  • Automatically check the validity of the COM port when the application starts and every time the user changes it.
  • Update a status box with information about the COM port’s status and any error messages.
  • Keep the COM port open while the application is running, if the user has checked that option.
  • Include basic error handling and status updates.

As you can see this includes the specific RS-232 command taken from the full instruction set. The results is not a straightforward solution and would take some expertise to complete the process to an application, but it is a starting point. We will continue to experiment with this.]

Here is the GUI based on the code at the bottom of the blog.

Python to Visual Basic

ChatGPT can help us translate this Python code into Visual Basic, making it suitable for Windows-based applications. While a direct one-to-one mapping is not always possible due to differences in language constructs and library support, the general principle remains the same.

You can follow the link provided at the end of this section to access a full code sample translated to Visual Basic.

Here are the key parts of the translation:

  1. Establishing Serial Communication: In Visual Basic, we’ll make use of the SerialPort class in the System.IO.Ports namespace to manage the serial communication.
  2. Implementing the GUI: Visual Basic supports a range of GUI components. We can use the TextBox control for the COM port input and the Button control to trigger the backlight.
  3. Command Execution and Acknowledgment: In VB, commands sent over the serial port are typically strings. We’ll need to ensure that our commands are correctly formatted as byte arrays to match the requirements of the SVX-4096.

[JH: This is the prompt I used:

Can you convert that to Visual Basic, together with appropriate instructions for compiling.

Pretty straightforward, I will update with feedback following compilation tests.]

Python to Microchip PIC Microcontroller Assembly

Next, let’s convert the Python code into an assembly language program for a Microchip PIC microcontroller. This conversion is more intricate due to the low-level nature of assembly language and the differences in working with hardware peripherals like UART (for serial communication).

Key steps of the translation:

  1. Establishing Serial Communication: We’ll set up the UART module in the microcontroller to enable serial communication.
  2. Sending Commands: The commands to control the backlight and request an acknowledgment are sent over the UART.
  3. Command Acknowledgment: We’ll read from the UART to receive the acknowledgment message and act accordingly.
  4. Switch Control: We’ll use a general purpose I/O pin to mimic the switch behavior in the original Python application.

[JH: For this step it would be necessary to use the relevant microcontroller libraries as well as iterate the results with ChatGPT to implement functions relevant to the hardware. For example I gave it the following prompt…

If I had a circuit board with a Microhip processor on it, and a momentary type button, connecting to the SVX-4096 using a serial cable, and wanted to turn the backlight on and off, can you write the code for that?

ChatGPT wrote some generic code but reminded me I would need the specific libraries. It also mentioned the need for code to handle debouncing for the button press. So I asked it to handle that too…

Can you rewrite with debouncing added?

Which it then did. ]

(Note: This blog post is meant to provide a general direction for writing such applications. Some adjustments might be needed based on the specific hardware and software configurations.)


CONCLUSION (by JH, not ChatGPT)

ChatGPT clearly doesn’t remove the need for expertise but it is certainly a powerful assistant. I will follow up on this as I am keen to see where it leads as an enabler to using Digital View products.

I did also try Bard but felt that the responses and results with ChatGPT were better. There are now many code writing tools available, for example CoPilot by GitHub which is based on the OpenAI Codex.

More Functions…

I asked ChatGPT to suggest more functionality, it responded with:

For a basic controller application like the one described, the functionality provided so far should cover the most important aspect: turning the backlight on and off. However, depending on the needs of your project and the capabilities of the SVX-4096 LCD controller board, there are some other functionalities that could be considered:

  1. Input validation: Before sending a command to the board, the application could validate the entered COM port to ensure it’s in the correct format.
  2. Automatic detection of COM port: The application could be programmed to automatically detect and connect to the SVX-4096 controller, if it is plugged in via USB for example.
  3. Brightness control: If the board supports it, the application could provide a slider or a similar interface for adjusting the brightness level of the backlight.
  4. Color control: For boards that support it, the application could allow the user to change the backlight color.
  5. Error logging: Instead of (or in addition to) showing error messages in popups, the application could log errors to a file. This could be useful for debugging and understanding what went wrong if a command fails.
  6. Multiple device control: If you need to control multiple SVX-4096 boards, the application could be extended to support this.
  7. Device status: The application could periodically check the status of the device and update the interface accordingly. This could include whether the device is still connected, the current brightness level or color, and so on.
  8. Saving user preferences: If the user always uses the same COM port, or always uses a certain brightness level or color, the application could save these preferences and automatically apply them the next time it is run.

Please note that some of these functionalities may require additional programming and a more in-depth understanding of the SVX-4096 LCD controller board’s capabilities and the protocols it uses for communication. Always refer to the board’s documentation or contact Digital View if you are unsure.

ai

Python Code

The following is code for the sample Python code:

import tkinter as tk
from tkinter import messagebox
import serial
import time

# GUI Application
class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()

        # Variables
        self.serial_port = tk.StringVar()
        self.serial_port.set('')
        self.backlight_state = False  # False for Off, True for On
        self.keep_open = tk.BooleanVar()
        self.keep_open.set(False)
        self.ser = None

        # Widgets
        self.create_widgets()

        # Status box
        self.status_text = tk.Text(self, height=5, state='disabled')
        self.status_text.pack(side="top", fill='x')

        # COM port validation
        self.check_com_port()

    def create_widgets(self):
        # Entry for COM port
        self.com_label = tk.Label(self, text='COM Port:')
        self.com_label.pack(side="top")

        self.com_entry = tk.Entry(self, textvariable=self.serial_port)
        self.com_entry.pack(side="top")

        # Checkbox for keeping port open
        self.keep_open_checkbox = tk.Checkbutton(self, text="Keep port open while application running", variable=self.keep_open)
        self.keep_open_checkbox.pack(side="top")

        # Button for On/Off
        self.toggle_button = tk.Button(self, text="OFF", command=self.toggle_backlight)
        self.toggle_button.pack(side="top")

        # Check for changes in the COM port entry
        self.serial_port.trace('w', lambda *args: self.check_com_port())

    def check_com_port(self):
        if self.ser and self.ser.is_open and not self.keep_open.get():
            self.ser.close()

        try:
            self.ser = serial.Serial(self.serial_port.get(), 9600, timeout=1)
            self.update_status('COM port is valid')
        except serial.SerialException:
            self.update_status('Invalid COM port')
            self.ser = None

    def toggle_backlight(self):
        if self.ser:
            if self.backlight_state:
                # If backlight is currently On, turn it Off
                self.send_command('0')
                if self.backlight_state == False:
                    # Update button text only if the command succeeded
                    self.toggle_button.config(text="OFF")
            else:
                # If backlight is currently Off, turn it On
                self.send_command('1')
                if self.backlight_state == True:
                    # Update button text only if the command succeeded
                    self.toggle_button.config(text="ON")
        else:
            self.update_status('Cannot send command, COM port is invalid')

    def send_command(self, command):
        # Try/except block to handle errors
        try:
            # Turn on/off command
            self.ser.write(bytes([0xe1, ord(command)]))
            time.sleep(1)

            # Read response
            response = self.ser.read(1)

            # Error handling
            if response != bytes([0xe1]):
                self.update_status('Command failed')
            else:
                # Update backlight_state based on command
                if command == '0':
                    self.backlight_state = False
                elif command == '1':
                    self.backlight_state = True

                self.update_status('Command succeeded')

        except Exception as e:
            self.update_status('Error: ' + str(e))

    def update_status(self, message):
        self.status_text.configure(state='normal')
        self.status_text.insert('end', message + '\n')
        self.status_text.see('end')
        self.status_text.configure(state='disabled')

root = tk.Tk()
app = Application(master=root)
app.mainloop()