# This file contains a number of functions which you can use to
# interact with your Arduino via its serial communication
# system. Example usage with an echo program loaded onto the Arduino:
#
# Python program:
#
# ```
# serial = prompt_for_and_get_serial()
#
# while True:
# send = input('>> ')
# serial.write(bytes(send, 'utf-8'))
# print(serial.readline().decode('utf-8')[:-1])
# ```
#
# Arduino program:
#
# ```
# void setup() {
# Serial.begin(9600);
# }
#
# void loop() {
# if (Serial.available()) {
# String message = Serial.readStringUntil('\n');
# Serial.print(": " + message + "\n");
# }
# }
# ```
import serial
from getch import getch
def get_ports():
"""List all of the avaliable ports on the device."""
import serial.tools.list_ports
return serial.tools.list_ports.comports()
def prompt_for_and_get_port():
"""Prompts the user to select a port. Returns the selected
one.
Input is expected to be a number in [0, num_ports) and is
read from standard in. An input outside of that range will result
in re-prompting until a valid input is provided.
"""
ports = get_ports()
for index, port in enumerate(ports):
print("{}) {}\t{}".format(index, port.device, port.description))
selection = int(input("please input the port number that your port is on: "))
while selection < 0 or selection >= len(ports):
print("error: {} is not between 0 and {}".format(selection, len(ports) - 1))
selection = int(input("please input the port number that your port is on: "))
return ports[selection]
def prompt_for_and_get_serial(baudrate=9600):
"""Prompts the user to select a port and returns a serial object
connected to that port.
By default the returned serial object uses a 9600 baudrate but
this can be modified by passing one to the function.
"""
port = prompt_for_and_get_port()
return serial.Serial(port=port.device, baudrate=baudrate)