~ekez/tui-webpage

tui-webpage/examples/pyserial.py -rw-r--r-- 1.9 KiB
2ccb2958Zeke Medley Deleniate presentation days 1 year, 4 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# 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)