我使用官方文档里的read_serial_port方法和write_serial_port来进行arduino串口通讯,现在的问题是可以向串口写入,arduino可以接受到指令并完成动作,但是我在arduino指定的完成动作后向串口Serial.println(msg)将一个字符串发送到串口,我接受不到该有的信息,而这个信息可以在串口监视器里看到。我需要这个串口的信息。下面是我的julia脚本,请求指教,固件我放在附件里
using TyBaseEx
using LibSerialPort
打开串口设备
function open_serial_port(port_name::String, baud_rate::Int)
try
# 使用 LibSerialPort.open 函数打开串口
device = LibSerialPort.open(port_name, baud_rate)
println("成功打开串行端口: $port_name")
return device
catch e
println("无法打开串行端口: $port_name. 错误信息: $e")
return nothing
end
end
写入串口命令
function write_serial_port(device, data::String)
try
# 确保命令以换行符结尾
if !endswith(data, "\n")
data *= "\n"
end
# 直接写入字符串
LibSerialPort.write(device, data)
println("写入命令: $data")
catch e
println("写入串口失败. 错误信息: $e")
end
end
逐字节读取串口响应,直到遇到换行符
function read_serial_port(device)
try
# 初始化变量
buffer = UInt8[] # 用于存储接收到的字节
timeout = time() + 2.0 # 设置超时时间为 2 秒
while time() < timeout
try
# 尝试读取一个字节
byte = LibSerialPort.read(device, 1, "UInt8")[1]
# 如果接收到换行符,表示消息结束
if byte == UInt8('\n')
response_str = String(buffer) # 将字节数组转换为字符串
println("读取到的响应: $response_str")
return strip(response_str) # 去掉多余的空白字符
else
push!(buffer, byte) # 将字节添加到缓冲区
end
catch e
# 如果读取失败(可能是无数据),继续循环
continue
end
end
# 超时后返回空字符串
println("读取超时,未收到完整响应")
return ""
catch e
println("读取串口失败. 错误信息: $e")
return ""
end
end
发送命令并读取响应
function send_command(device, command::String)
# 写入命令,使用 ASCII 数据格式
write_serial_port(device, command) # 添加换行符作为命令终止符
# 立即尝试读取响应
sleep(0.1) # 等待 Arduino 处理命令
response = read_serial_port(device)
return response
end
主函数:实现所有功能
function main()
# 定义串口号和波特率
port_name = "COM4"
baud_rate = 115200
# 打开串口
device = open_serial_port(port_name, baud_rate)
if device === nothing
return
end
try
# 示例:软件重启
println("发送命令: A")
response = send_command(device, "A")
println("响应: $response")
# 示例:设置 LED 亮度
println("发送命令: LED 50")
response = send_command(device, "LED 50")
println("响应: $response")
# 示例:设置加热器 1 功率限制
println("发送命令: P1 200")
response = send_command(device, "P1 200")
println("响应: $response")
# 示例:设置加热器 1 功率
println("发送命令: Q1 75")
response = send_command(device, "Q1 75")
println("响应: $response")
# 示例:扫描所有状态
println("发送命令: SCAN")
response = send_command(device, "SCAN")
println("响应: $response")
# 示例:停止操作
println("发送命令: X")
response = send_command(device, "X")
println("响应: $response")
finally
# 关闭串口
LibSerialPort.close(device)
println("关闭串行端口: $port_name")
end
end
调用主函数
main()