In this chapter I use an Arduino UNO as a terminal device for communication via USB interface. The following sketch should run on this:
1
2
3
4
5
6
7
8
9
void setup() {
Serial.begin(115200);
}
void loop() {
if (Serial.available()) { // If anything comes in Serial (USB),
Serial.write(Serial.read()); // read it and send it out via serial
}
}
With this sketch, the Arduino reads data bytes that are sent from the PC and returns them unchanged to the PC. So the next thing we need is a Python script that sends data to the Arduino and then waits for those bytes to be sent back via USB.
Python for data exchange via USB
In order to be able to use the USB interface in Python, the corresponding module must be installed:
sudo apt-get install python3-serial
Now the following script can be started:
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
#!/usr/bin/python3
import sys # Needed for handling command line parameters
import serial # Needed for USB communication
import time
# Open USB port to Arduino running echo script
usbComm = serial.Serial(
# port = '/dev/ttyUSB0', #Replace ttyS0 with ttyACM0 for Pi1,Pi2,Pi0
port = '/dev/ttyACM0', #Replace ttyACM0 with ttyUSB0 for Pi3 and Pi4
baudrate = 115200,
parity = serial.PARITY_NONE,
stopbits = serial.STOPBITS_ONE,
bytesize = serial.EIGHTBITS,
timeout = 1
)
time.sleep(1.002)# Give port some time to really open...
# Now write the text received from the command line
for arg in sys.argv: # Loop through all command line parameters
command_line = arg + '\r\n' # Add return and new line to argument
print(arg)
usbComm.write(command_line.encode('utf-8'))# Write line to USB
The Python script sends all parameters passed from the command line to the Arduino. After sending a parameter, the response from the Arduino is waited for and the received byte is printed. If a received byte is a letter, lower case letters are converted into upper case letters. The received word is printed by the script as soon as no further byte can be found in the input buffer.