Welcome to Hackster!
Hackster is a community dedicated to learning hardware, from beginner to pro. Join us, it's free!
Dhrumil Mistry
Published © MIT

Serial Terminal Using Python3

Creating a Custom Serial Terminal for Arduino using Python3

BeginnerProtip10 minutes113
Serial Terminal Using Python3

Things used in this project

Story

Read more

Schematics

Connect Cable to the Arduino Board

Connect cable to the board, flash Arduino sketch and start terminal.py to communicate with Arduino.

Code

Python Program

Python
Create a python file terminal.py and paste below program in terminal.py file. Connect Arduino to the computer and check on which port it is connected to. Assume it is connected on COM PORT 10 then replace [Port_No] with 10, changing line 55 to
ardterm = Terminal("COM10")

run python file after uploading Arduino sketch using
python terminal.py (for Windows Users)
python3 terminal.py (for Linux/MacOS Users)
import serial
import time
import threading


class Terminal:
    def __init__(self, com_port, baud_rate=9600, timeout=0.0) -> None:
        self.connected = False
        self.prompt = "Arduino >> "
        self.encoding = 'utf-8'
        self.is_reader_alive = False
        self.reader = threading.Thread(target=self.receive_reply, name='rx')
        self.reader.daemon = True
        self.arduino = serial.Serial(com_port,
                                     baud_rate,
                                     timeout=timeout)

    def send_message(self):
        message = input(self.prompt).encode(self.encoding)
        self.arduino.write(message)

        if message == b'exit!':
            self.connected = False
            self.is_reader_alive = False
            self.reader.join()


    def receive_reply(self):
        while self.connected and self.is_reader_alive:
            reply = self.arduino.readline().decode(self.encoding)
            time.sleep(0.2)
            try:
                is_valid = ord(reply) != 32 and ord(reply) != 13
            except TypeError:
                is_valid = True
            if reply and is_valid:
                print(f"\nReply --> {reply}\n{self.prompt}", end='')


    def start_terminal(self):
        try:
            self.connected = True
            self.is_reader_alive = True
            self.reader.start()

            while self.connected:
                self.send_message()
                time.sleep(0.3)

        except Exception as e:
            print("[X] Exception :", e)


if __name__ == "__main__":
    ardterm = Terminal("COM[Port_No]")
    ardterm.start_terminal()

Arduino Sketch

C/C++
Upload Arduino Sketch to Arduino Board and then run terminal.py program.
String message;

void setup() {
  Serial.begin(9600);
}

void loop() {
  while (!Serial.available());
  message = Serial.readString();
  Serial.print("Received Message: ");
  Serial.println(message);
}

Credits

Dhrumil Mistry
2 projects • 1 follower
Contact

Comments

Please log in or sign up to comment.