Skip to content

Instantly share code, notes, and snippets.

@geekscape
Last active September 2, 2022 23:31
Show Gist options
  • Save geekscape/cb951e201642ffc47d6a0d5c1bb56ffc to your computer and use it in GitHub Desktop.
Save geekscape/cb951e201642ffc47d6a0d5c1bb56ffc to your computer and use it in GitHub Desktop.
Python Serial examples for host and microController
This GitHub Gist can be reached by this short URL: https://tinyurl.com/gs-py-serial
Set-up Python virtual environment
- See https://pythonbasics.org/virtualenv
- Avoids changing operating system installed version of Python environment
Install Python serial module
$ pip install pyserial
Run Thonny IDE and use the Python virtual environment for your host system
- Menu -> Run --> Select interpreter...
- Alternative Python 3 interpreter or virtual environment
- Python executable: $HOME/venv/$VENV_NAME/bin/python
- Load "host_serial.py"
- Menu -> Run --> Run current script
-------------------------------------
To Do
~~~~~
- Convert notes to MarkDown ?
- See https://gist.github.com/ww9/44f08d44327a40d2ab309a349bebec57
- Create proper respository for Python Next workshop / tutorial / examples
#!/usr/bin/env python3
#
# https://stackoverflow.com/questions/676172/full-examples-of-using-pyserial-package
# https://www.varesano.net/serial-rs232-connections-in-python
import time
import serial
# SERIAL_PORTNAME = "/dev/ttyUSB0" # Linux example
SERIAL_PORTNAME = "/dev/tty.usbserial-1440" # Mac OS X example
# SERIAL_PORTNAME = "COM1" # Windows example
serial_port = serial.Serial(port=SERIAL_PORTNAME, baudrate=115200)
print(f"Serial port open: {serial_port.isOpen()}")
def read(serial_port):
buffer = ""
while True:
time.sleep(0.1)
count = serial_port.inWaiting()
if count:
buffer += serial_port.read(count).decode("utf-8")
else:
break
return buffer
def write(serial_port, buffer):
count = serial_port.write(buffer.encode("utf-8"))
return count
def request(serial_port, command):
write_count = write(serial_port, command)
response = read(serial_port)
end = len(response)
if response.endswith(">>> "):
end -= 5
return response[write_count+1:end]
try:
while True:
command = f"{input('> ')}\r"
response = request(serial_port, command)
print(response)
except KeyboardInterrupt:
serial_port.close()
raise SystemExit("KeyboardInterrupt: abort !")
except EOFError:
serial_port.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment