import serial
import time
import socket
def serial_communication():
try:
while True:
#端口
portx="DM1"
#波特率
bps=9600
#等待时间
timex=1
# 创建serial
ser = serial.Serial(portx,bps,timeout=timex)
#发送stop
data = ser.read(5)
print(data)
ser.close()
if len(data) == 5:
# 1.创建socket
tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 2. 链接服务器
server_addr = ("127.0.0.1", 9001)
tcp_socket.connect(server_addr)
# 3. 发送数据
send_data = data
tcp_socket.send(send_data)
# 4. 关闭套接字
tcp_socket.close()
except Exception as e:
print("异常",e)