It's a simple "** Introduction to learning and implementing serial communication **".
Serial communication: A communication method that sequentially transmits digital data bit by bit. Parallel communication: Communication method for simultaneous transmission of multiple bits of digital data
Communication method | Advantages | Disadvantages |
---|---|---|
Serial communication | low cost | slow |
Parallel communication | High cost | fast |
If you want to know more, this article is recommended. I tried to summarize the serial communication method for beginners of electronic work in an easy-to-understand manner
First, hit the following command to install the package. (You don't have to enter $
.)
python
$ pip install pyserial
First, search for devices that can communicate. Try hitting the following command. (The second line is the response from the terminal.)
python
$ ls -l /dev/tty.*
crw-rw-rw- 1 root wheel 18, 0 11 28 17:48 /dev/tty.Bluetooth-Incoming-Port
A device called /dev/tty.Bluetooth-Incoming-Port
was found.
Next, let's read it.
read.py
import serial
readSer = serial.Serial('/dev/tty.Bluetooth-Incoming-Port',9600, timeout=3)
c = readSer.read() # 1 byte
string = readSer.read(10) # 10 byte
line = readSer.readline() # 1 line (upto '\n')
print("Read Serial:")
print(c)
print(string)
print(line)
readSer.close()
serial.Serial (device name, baud rate, timeout)
)write.py
import serial
serialCommand = "test"
writeSer = serial.Serial('/dev/tty.Bluetooth-Incoming-Port',9600, timeout=3)
writeSer.write(serialCommand.encode())
writeSer.close()
serial.Serial (device name, baud rate, timeout)
)main.py
import serial
print("===== Start Program =====\n")
# Set Parameter
deviceName = '/dev/tty.Bluetooth-Incoming-Port' # search by `ls -l /dev/tty.*`
baudrateNum = 9600
timeoutNum = 3
print("===== Set Parameter Complete =====\n")
# # Read Serial
readSer = serial.Serial(deviceName, baudrateNum, timeout=timeoutNum)
c = readSer.read()
string = readSer.read(10)
line = readSer.readline()
print("Read Serial:")
print(c)
print(string)
print(line)
readSer.close()
print("===== Read Serial Complete =====\n")
# Write Serial
serialCommand = "test"
writeSer = serial.Serial(deviceName, baudrateNum, timeout=timeoutNum)
writeSer.write(serialCommand.encode())
writeSer.close()
print("===== Write Serial Complete =====\n")
print("===== End Program =====\n")
-I tried to summarize the serial communication method for beginners of electronic work in an easy-to-understand manner -[Introduction to Python] Explaining how to execute serial communication with pySerial -Serial communication with python
Recommended Posts