├── .vscode └── settings.json ├── LICENSE ├── README.md ├── arduino_serial_port ├── .gitignore ├── .vscode │ └── extensions.json ├── include │ └── README ├── lib │ └── README ├── platformio.ini ├── src │ └── main.cpp └── test │ └── README ├── python_serial_port ├── icon.png ├── main.py └── simple_terminal.py └── requirements.txt /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.formatting.provider": "black" 3 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Meysam Parvizi 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python Serial Port + Tkinter GUI 2 | 3 | A simple serial port monitor application in Python using [pySerial](https://pypi.org/project/pyserial/). The GUI is designed using [Tkinter](https://docs.python.org/3/library/tkinter.html). 4 | 5 | To test the performance of our Python program, an Arduino program is written to send data on serial port at the baudrate of 921600. 6 | 7 | ## Install dependencies 8 | 9 | Python Version: 3.8.10 10 | 11 | ```console 12 | pip install -r requirements.txt 13 | ``` 14 | 15 | ## Tutorials 16 | 17 | - [Tkinter Basic Widgets](https://tkdocs.com/tutorial/widgets.html) 18 | - [tkinter.scrolledtext — Scrolled Text Widget](https://docs.python.org/3/library/tkinter.scrolledtext.html) 19 | - [PySerial Short Introduction](https://pyserial.readthedocs.io/en/latest/shortintro.html) 20 | - [An Intro to Threading in Python](https://realpython.com/intro-to-python-threading/) 21 | 22 | ## License 23 | 24 | This project is licensed under the MIT license. 25 | -------------------------------------------------------------------------------- /arduino_serial_port/.gitignore: -------------------------------------------------------------------------------- 1 | .pio 2 | .vscode/.browse.c_cpp.db* 3 | .vscode/c_cpp_properties.json 4 | .vscode/launch.json 5 | .vscode/ipch 6 | -------------------------------------------------------------------------------- /arduino_serial_port/.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | // See http://go.microsoft.com/fwlink/?LinkId=827846 3 | // for the documentation about the extensions.json format 4 | "recommendations": [ 5 | "platformio.platformio-ide" 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /arduino_serial_port/include/README: -------------------------------------------------------------------------------- 1 | 2 | This directory is intended for project header files. 3 | 4 | A header file is a file containing C declarations and macro definitions 5 | to be shared between several project source files. You request the use of a 6 | header file in your project source file (C, C++, etc) located in `src` folder 7 | by including it, with the C preprocessing directive `#include'. 8 | 9 | ```src/main.c 10 | 11 | #include "header.h" 12 | 13 | int main (void) 14 | { 15 | ... 16 | } 17 | ``` 18 | 19 | Including a header file produces the same results as copying the header file 20 | into each source file that needs it. Such copying would be time-consuming 21 | and error-prone. With a header file, the related declarations appear 22 | in only one place. If they need to be changed, they can be changed in one 23 | place, and programs that include the header file will automatically use the 24 | new version when next recompiled. The header file eliminates the labor of 25 | finding and changing all the copies as well as the risk that a failure to 26 | find one copy will result in inconsistencies within a program. 27 | 28 | In C, the usual convention is to give header files names that end with `.h'. 29 | It is most portable to use only letters, digits, dashes, and underscores in 30 | header file names, and at most one dot. 31 | 32 | Read more about using header files in official GCC documentation: 33 | 34 | * Include Syntax 35 | * Include Operation 36 | * Once-Only Headers 37 | * Computed Includes 38 | 39 | https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html 40 | -------------------------------------------------------------------------------- /arduino_serial_port/lib/README: -------------------------------------------------------------------------------- 1 | 2 | This directory is intended for project specific (private) libraries. 3 | PlatformIO will compile them to static libraries and link into executable file. 4 | 5 | The source code of each library should be placed in a an own separate directory 6 | ("lib/your_library_name/[here are source files]"). 7 | 8 | For example, see a structure of the following two libraries `Foo` and `Bar`: 9 | 10 | |--lib 11 | | | 12 | | |--Bar 13 | | | |--docs 14 | | | |--examples 15 | | | |--src 16 | | | |- Bar.c 17 | | | |- Bar.h 18 | | | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html 19 | | | 20 | | |--Foo 21 | | | |- Foo.c 22 | | | |- Foo.h 23 | | | 24 | | |- README --> THIS FILE 25 | | 26 | |- platformio.ini 27 | |--src 28 | |- main.c 29 | 30 | and a contents of `src/main.c`: 31 | ``` 32 | #include 33 | #include 34 | 35 | int main (void) 36 | { 37 | ... 38 | } 39 | 40 | ``` 41 | 42 | PlatformIO Library Dependency Finder will find automatically dependent 43 | libraries scanning project source files. 44 | 45 | More information about PlatformIO Library Dependency Finder 46 | - https://docs.platformio.org/page/librarymanager/ldf.html 47 | -------------------------------------------------------------------------------- /arduino_serial_port/platformio.ini: -------------------------------------------------------------------------------- 1 | ; PlatformIO Project Configuration File 2 | ; 3 | ; Build options: build flags, source filter 4 | ; Upload options: custom upload port, speed and extra flags 5 | ; Library options: dependencies, extra library storages 6 | ; Advanced options: extra scripting 7 | ; 8 | ; Please visit documentation for the other options and examples 9 | ; https://docs.platformio.org/page/projectconf.html 10 | 11 | [env:uno] 12 | platform = atmelavr 13 | board = uno 14 | framework = arduino 15 | 16 | ; Monitor Serial Port Baud-Rate 17 | monitor_speed = 921600 -------------------------------------------------------------------------------- /arduino_serial_port/src/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | long int counter; 4 | 5 | // put your setup code here, to run once: 6 | void setup() { 7 | 8 | counter = 100000; 9 | 10 | Serial.begin(921600); 11 | Serial.println("[ Serial Communication Started ]"); 12 | } 13 | 14 | // put your main code here, to run repeatedly: 15 | void loop() { 16 | // Increment the counter by 1 17 | counter += 1; 18 | 19 | // Send numbers to serial port 20 | Serial.print("#"); 21 | Serial.println(counter); 22 | 23 | //delay(10); 24 | } -------------------------------------------------------------------------------- /arduino_serial_port/test/README: -------------------------------------------------------------------------------- 1 | 2 | This directory is intended for PlatformIO Unit Testing and project tests. 3 | 4 | Unit Testing is a software testing method by which individual units of 5 | source code, sets of one or more MCU program modules together with associated 6 | control data, usage procedures, and operating procedures, are tested to 7 | determine whether they are fit for use. Unit testing finds problems early 8 | in the development cycle. 9 | 10 | More information about PlatformIO Unit Testing: 11 | - https://docs.platformio.org/page/plus/unit-testing.html 12 | -------------------------------------------------------------------------------- /python_serial_port/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/m3y54m/python-serial-port-gui/c6626ca56a3e112af818dbb8a9a5131a41d852ca/python_serial_port/icon.png -------------------------------------------------------------------------------- /python_serial_port/main.py: -------------------------------------------------------------------------------- 1 | # GUI design 2 | import tkinter as tk 3 | from tkinter import scrolledtext 4 | 5 | # Communication with serial port 6 | import serial 7 | from serial.tools import list_ports 8 | 9 | # Multi-threading 10 | import threading 11 | 12 | # Get path 13 | import os 14 | 15 | # Use realpath if you want the real path (symlinks are resolved) 16 | # file_path = os.path.realpath(__file__) 17 | FILE_PATH = os.path.abspath(__file__) 18 | ICON_PATH = os.path.join(os.path.dirname(__file__), "icon.png") 19 | 20 | 21 | class GUI: 22 | # GUI main class 23 | def __init__(self, title): 24 | 25 | self.portNamesList = [] 26 | self.baudRatesList = [ 27 | 1200, 28 | 2400, 29 | 4800, 30 | 9600, 31 | 19200, 32 | 38400, 33 | 57600, 34 | 115200, 35 | 230400, 36 | 460800, 37 | 576000, 38 | 921600, 39 | ] 40 | self.isAnyPortAvailable = False 41 | self.isStarted = False 42 | self.serialPortName = None 43 | self.serialPortBaud = 9600 44 | 45 | self.serialPortManager = SerialPortManager(self.serialPortBaud) 46 | self.get_available_serial_ports() 47 | 48 | self.guiUpdateInterval = 40 49 | 50 | self.window = tk.Tk() 51 | # Title of application window 52 | self.window.title(title) 53 | # Icon of application window 54 | self.window.iconphoto(False, tk.PhotoImage(file=ICON_PATH)) 55 | 56 | self.topFrame = tk.Frame(self.window, bg="#cccccc") 57 | 58 | self.scanButton = tk.Button( 59 | self.topFrame, 60 | text="Scan Serial Ports", 61 | bg="#0051ff", 62 | fg="#ffffff", 63 | border=0, 64 | highlightbackground="#ffffff", 65 | highlightthickness=2, 66 | activebackground="#1f7cff", 67 | activeforeground="#ffffff", 68 | font=("Sans", "10", "bold"), 69 | command=self.scan_button_command, 70 | ) 71 | 72 | # Define a tk.StringVar for storing selected item in OptionMenu 73 | self.selectedPort = tk.StringVar() 74 | # Set default value of selectedPort 75 | if self.isAnyPortAvailable == False: 76 | self.portNamesList = ["No ports available"] 77 | self.selectedPort.set(self.portNamesList[0]) 78 | 79 | self.portsOptionMenu = tk.OptionMenu( 80 | self.topFrame, self.selectedPort, *self.portNamesList 81 | ) 82 | 83 | self.portsOptionMenu.configure( 84 | bg="#ffffff", 85 | fg="#222222", 86 | border=0, 87 | highlightbackground="#aaaaaa", 88 | activebackground="#eeeeee", 89 | activeforeground="#111111", 90 | direction="left", 91 | font=("Sans", "10", "bold"), 92 | ) 93 | if self.isAnyPortAvailable == False: 94 | self.portsOptionMenu.configure(state="disabled") 95 | 96 | # Define a tk.IntVar for storing selected item in OptionMenu 97 | self.selectedBaudRate = tk.IntVar() 98 | # Set default value of selectedBaudRate 99 | self.selectedBaudRate.set(self.baudRatesList[3]) 100 | self.baudRatesOptionMenu = tk.OptionMenu( 101 | self.topFrame, self.selectedBaudRate, *self.baudRatesList 102 | ) 103 | 104 | self.baudRatesOptionMenu.configure( 105 | bg="#ffffff", 106 | fg="#222222", 107 | border=0, 108 | highlightbackground="#aaaaaa", 109 | activebackground="#eeeeee", 110 | activeforeground="#111111", 111 | direction="left", 112 | font=("Sans", "10", "bold"), 113 | ) 114 | if self.isAnyPortAvailable == False: 115 | self.baudRatesOptionMenu.configure(state="disabled") 116 | 117 | self.connectButton = tk.Button( 118 | self.topFrame, 119 | text="Connect", 120 | bg="#00a832", 121 | fg="#ffffff", 122 | border=0, 123 | highlightbackground="#ffffff", 124 | highlightthickness=2, 125 | activebackground="#3fcc69", 126 | activeforeground="#ffffff", 127 | font=("Sans", "10", "bold"), 128 | command=self.start_button_command, 129 | ) 130 | if self.isAnyPortAvailable == False: 131 | self.connectButton.configure( 132 | state="disabled", bg="#bbbbbb", highlightbackground="#aaaaaa" 133 | ) 134 | 135 | self.textBox = scrolledtext.ScrolledText( 136 | self.topFrame, 137 | bg="#222222", 138 | fg="#eeeeee", 139 | border=0, 140 | wrap="none", 141 | highlightbackground="#aaaaaa", 142 | highlightthickness=2, 143 | font=("Sans", "10", "bold"), 144 | ) 145 | 146 | # Start updating textbox in GUI 147 | self.recursive_update_textbox() 148 | 149 | ############################### 150 | ## Widgets size and position ## 151 | ############################### 152 | 153 | spacing = 10 154 | padding = 10 155 | widget_width = 800 156 | window_width = widget_width + 2 * padding 157 | window_height = 500 158 | 159 | # Size of application window 160 | self.window.geometry("{}x{}".format(window_width, window_height)) 161 | # Don't allow resizing in the x or y direction 162 | self.window.resizable(False, False) 163 | 164 | self.topFrame.configure(padx=padding, pady=padding) 165 | self.topFrame.place(x=0, y=0, width=window_width, height=window_height) 166 | 167 | self.scanButton.configure(width=widget_width, padx=padding, pady=padding) 168 | self.scanButton.pack(pady=(0, spacing)) 169 | 170 | self.portsOptionMenu.configure(width=widget_width, padx=padding, pady=padding) 171 | self.portsOptionMenu.pack(pady=(0, spacing)) 172 | 173 | self.baudRatesOptionMenu.configure(width=widget_width, padx=padding, pady=padding) 174 | self.baudRatesOptionMenu.pack(pady=(0, spacing)) 175 | 176 | self.connectButton.configure(width=widget_width, padx=padding, pady=padding) 177 | self.connectButton.pack(pady=(0, spacing)) 178 | 179 | self.textBox.configure(width=widget_width, padx=padding, pady=padding) 180 | self.textBox.pack() 181 | 182 | self.window.protocol("WM_DELETE_WINDOW", self.close_window) 183 | # Blocking loop for GUI (Always put at the end) 184 | self.window.mainloop() 185 | 186 | def start_button_command(self): 187 | 188 | if self.isStarted == False: 189 | self.isStarted = True 190 | self.connectButton.configure( 191 | bg="#ba0020", 192 | highlightbackground="#ffffff", 193 | activebackground="#cf324d", 194 | text="Disconnect", 195 | ) 196 | # Get desired serial port name 197 | self.serialPortName = self.selectedPort.get() 198 | # Get desired serial port baud rate 199 | self.serialPortBaud = self.selectedBaudRate.get() 200 | # Start Serial Port Communication 201 | self.serialPortManager.set_name(self.serialPortName) 202 | self.serialPortManager.set_baud(self.serialPortBaud) 203 | self.serialPortManager.start() 204 | # Start updating textbox in GUI 205 | self.recursive_update_textbox() 206 | 207 | else: 208 | self.isStarted = False 209 | self.connectButton.configure( 210 | bg="#00a832", 211 | highlightbackground="#ffffff", 212 | activebackground="#3fcc69", 213 | text="Connect", 214 | ) 215 | self.serialPortManager.stop() 216 | 217 | def scan_button_command(self): 218 | self.portNamesList = self.get_available_serial_ports() 219 | 220 | if len(self.portNamesList) == 0: 221 | self.isAnyPortAvailable = False 222 | self.portNamesList = ["No ports available"] 223 | self.portsOptionMenu.configure(state="disabled") 224 | self.baudRatesOptionMenu.configure(state="disabled") 225 | self.connectButton.configure( 226 | state="disabled", bg="#bbbbbb", highlightbackground="#aaaaaa" 227 | ) 228 | else: 229 | self.isAnyPortAvailable = True 230 | self.portsOptionMenu.configure(state="normal") 231 | self.baudRatesOptionMenu.configure(state="normal") 232 | if self.isStarted: 233 | self.connectButton.configure( 234 | bg="#ba0020", 235 | highlightbackground="#ffffff", 236 | activebackground="#cf324d", 237 | state="normal", 238 | ) 239 | else: 240 | self.connectButton.configure( 241 | bg="#00a832", 242 | highlightbackground="#ffffff", 243 | activebackground="#3fcc69", 244 | state="normal", 245 | ) 246 | 247 | self.update_option_menu(self.portNamesList) 248 | 249 | def get_available_serial_ports(self): 250 | # Clear portNames list 251 | portNames = [] 252 | # Get a list of available serial ports 253 | portsList = list_ports.comports() 254 | # Sort based on port names 255 | portsList = sorted(portsList) 256 | 257 | for port in portsList: 258 | portNames.append(port.device) 259 | 260 | return portNames 261 | 262 | def update_option_menu(self, portNames): 263 | # Remove old items 264 | self.portsOptionMenu["menu"].delete(0, "end") 265 | # Add new items 266 | for portName in portNames: 267 | self.portsOptionMenu["menu"].add_command( 268 | label=portName, command=tk._setit(self.selectedPort, portName) 269 | ) 270 | # Set default value of selectedPort 271 | self.selectedPort.set(portNames[0]) 272 | 273 | def recursive_update_textbox(self): 274 | serialPortBuffer = self.serialPortManager.read_buffer() 275 | # Update textbox in a kind of recursive function using Tkinter after() method 276 | self.textBox.insert(tk.INSERT, serialPortBuffer.decode("ascii")) 277 | # autoscroll to the bottom 278 | self.textBox.see(tk.END) 279 | # Recursively call recursive_update_textbox using Tkinter after() method 280 | if self.serialPortManager.isRunning: 281 | self.window.after(self.guiUpdateInterval, self.recursive_update_textbox) 282 | 283 | def close_window(self): 284 | if self.isStarted: 285 | self.serialPortManager.stop() 286 | self.window.destroy() 287 | 288 | 289 | class SerialPortManager: 290 | # A class for management of serial port data in a separate thread 291 | def __init__(self, serialPortBaud=9600): 292 | self.isRunning = False 293 | self.serialPortName = None 294 | self.serialPortBaud = serialPortBaud 295 | self.serialPort = serial.Serial() 296 | # Create a byte array to store incoming data 297 | self.serialPortBuffer = bytearray() 298 | 299 | def set_name(self, serialPortName): 300 | self.serialPortName = serialPortName 301 | 302 | def set_baud(self, serialPortBaud): 303 | self.serialPortBaud = serialPortBaud 304 | 305 | def start(self): 306 | self.isRunning = True 307 | self.serialPortThread = threading.Thread(target=self.thread_handler) 308 | self.serialPortThread.start() 309 | 310 | def stop(self): 311 | self.isRunning = False 312 | 313 | def thread_handler(self): 314 | 315 | while self.isRunning: 316 | 317 | if not self.serialPort.isOpen(): 318 | 319 | self.serialPort = serial.Serial( 320 | port=self.serialPortName, 321 | baudrate=self.serialPortBaud, 322 | bytesize=8, 323 | timeout=2, 324 | stopbits=serial.STOPBITS_ONE, 325 | ) 326 | else: 327 | # Wait until there is data waiting in the serial buffer 328 | while self.serialPort.in_waiting > 0: 329 | # Read only one byte from serial port 330 | serialPortByte = self.serialPort.read(1) 331 | self.serialPortBuffer.append(int.from_bytes(serialPortByte, byteorder='big')) 332 | # Process incoming bytes 333 | self.main_process(serialPortByte) 334 | 335 | if self.serialPort.isOpen(): 336 | self.serialPort.close() 337 | 338 | def read_buffer(self): 339 | # Return a copy of serial port buffer 340 | buffer = self.serialPortBuffer 341 | # Clear serial port buffer 342 | self.serialPortBuffer = bytearray() 343 | return buffer 344 | 345 | def __del__(self): 346 | if self.serialPort.isOpen(): 347 | self.serialPort.close() 348 | 349 | def main_process(self, inputByte): 350 | # Print the received byte in Python terminal 351 | try: 352 | character = inputByte.decode("ascii") 353 | except UnicodeDecodeError: 354 | pass 355 | else: 356 | print(character, end="") 357 | 358 | 359 | if __name__ == "__main__": 360 | 361 | # Create the GUI 362 | gui = GUI("Serial Port + Tkinter GUI") 363 | -------------------------------------------------------------------------------- /python_serial_port/simple_terminal.py: -------------------------------------------------------------------------------- 1 | import serial 2 | 3 | serialPort = serial.Serial(port="COM1", baudrate=9600) 4 | 5 | while True: 6 | # Read only one byte from serial port 7 | serialPortByte = serialPort.read(1) 8 | 9 | try: 10 | # Convert byte to string (character) 11 | char = serialPortByte.decode("ascii") 12 | except UnicodeDecodeError: 13 | # Don't raise error if byte is not ASCII 14 | pass 15 | else: 16 | # Print the received byte in Python terminal 17 | print(char, end="") 18 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pyserial==3.5 2 | --------------------------------------------------------------------------------