When sending a string from Python to Arduino serially, I think that I will write it like this using pyserial.
import serial
ser = serial.Serial()
ser.baudrate = 9600
ser.port = 2 # COM3->2,COM5->4
ser.open()
ser.write("Hello")
Since ser.port changes every time you plug in and unplug the USB, check the port with the Arduino IDE, ser.port =" /dev/tty.usbmodem1451 "
for Mac, and COM3 for Windows It is written as ser.port = 2
, but it is troublesome because it changes every time it is inserted or removed, so such a writing method is also prepared.
import serial
import serial.tools.list_ports
ser = serial.Serial()
ser.baudrate = 9600
ser.port = list(serial.tools.list_ports.comports())[0][0]
ser.open()
ser.write("Hello")
This writing method seems to fail depending on the environment, and if you are on a Mac, you can find it by searching under / dev properly, so when I tried this writing method, it worked fine.
ser = serial.Serial()
ser.baudrate = 9600
for file in os.listdir('/dev'):
if "tty.usbmodem" in file:
ser.port = '/dev/'+file
ser.open()
In the case of Windows, it is specified by a number, so you can write it like this.
ser = serial.Serial()
ser.baudrate = 9600
for i in range(100):
try:
ser.port = i
ser.open()
break
except:
i = i
Recommended Posts