调用树莓派USB口输出Gcode给arduino

def main():
    import serial  
    from time import sleep
    ser = serial.Serial('/dev/ttyACM0', 115200, timeout=0.1)#打开USB0口 串口号ttyACM0 波特率115200 超时2秒
    ser.timeout=40#读超时设置
    ser.writeTimeout=2#写超时
    line = '$G\n'#查看信息命令
    print(line)#打印命令数据
    cmd = line.encode()#对数据unicode编码成bytes
    ser.write(cmd)#发送命令
    data = ser.readline()#读取返回数据 10s超时
    print(data)#打印返回数据
    f = open('/home/pi/Desktop/output_new.nc','r')#只读模式打开文档打开Gcode文档
    while True:    
        # 获取数据
        line = f.readline()#按行读取
        if not line:#读到最后文档结尾
            f.close() #关闭文档
            break#退出循环
        print(line)#打印数据
        cmd = line.encode()#对数据unicode编码成bytes
        ser.write(cmd)#发送命令
        data = ser.readline() #读取返回数据 10s超时
        print(data)#打印返回数据
    print('发送完成')
        

if __name__ == '__main__':
    main()

注意,这里用串口发送数据是,需要先将字符串unicode编码变成byte编码
cmd = line.encode()#对数据unicode编码成bytes

参考
python serial模块
Python3中内置类型bytes和str用法及byte和string之间各种编码转换
Python逐行读取文件,到最后一行结束
使用python来调试串口

猜你喜欢

转载自blog.csdn.net/cool_bot/article/details/89702413