tmd网上有关matlab与robotstudio stocket通讯内容太少,干脆自己写一篇文章,以免以后浪费时间。
参考本文代码:http://t.csdn.cn/02UkD
感谢老板的代码。stocket也可以参考上面的链接。
matlab与robotstudio通信分为两部分代码,matlab作为服务器端,向服务器端发送位置数据robotstudio。首先介绍robotstudio端的代码:
这是一个基础matlab以p10点是基准移动机器人的代码。matlab发送的是p10点xyz轴向偏移量。
MODULE moudle1 !define variables定义变量 VAR socketdev server; VAR socketdev client; VAR string message; VAR string string1:=""; VAR string string2{3}:=["","",""]; VAR num pass:=0; VAR num X:=0; VAR num Y:=0; VAR num Rz:=0; VAR bool flag1:=FALSE; VAR rawbytes data; !定义一个p10点 CONST robtarget p10:=[[0,0,23.72],[0.00796547,0.908649,0.417482,0.[0,-1,1,0]E 09,9E 09,9E 09,9E 09,9E 09,9E 09]]; !定义工具数据 TASK PERS tooldata toolxi:=[TRUE,[0、0、160]、[1、0、0、0]、[1、[1、0、1]、[1、0、0、0]、0、0、0]、 PROC main() a: !create communication建立通信 SocketCreate server; SocketBind server,"127.0.0.1",55000; SocketListen server; SocketAccept server,client; !send a meassage to the client SocketSend client,\Str:="Hello client"; !receive a message from the client SocketReceive client,\Str:=string1; UnpackRawBytes data ,1,message,\ASCII:=16; !close cmmunication SocketClose server; TPErase; TPWrite string1; WaitTime 4; !关键部分:将接收字段的第一位赋值给‘pass第二位向后取8个数赋值x,y string2{1}:=StrPart(string1,1,1); string2{2}:=StrPart(string1,2,8); string2{3}:=StrPart(string1,2,8); flag1:=StrToVal(string2{1},pass); flag1:=StrToVal(string2{2},X); flag1:=StrToVal(string2{3},Y); !根据pass判断运动是否为‘1’ IF pass = 1 AND flag1 THEN !移动到距离p10点x轴方向xmm的位置,y轴方向ymm的位置,z轴方向15mm的位置 MoveL Offs(p10,X,Y,15), v1000, fine, toolxi; MoveL Offs(p10,X,Y,0), v1000, fine, toolxi; WaitTime 0.5; MoveL Offs(p10,X,Y,15), v1000, z50, toolxi; ELSE TPWrite "failed to get the data"; waittime 2; GOTO a; ENDIF SocketClose server; SocketClose client; ENDPROC ENDMODULE
程序中'pass用于判断发送的数据是否给轴偏移量赋值,因此发送的数据必须从‘1’开始。
string2{2}:=StrPart(string1、2、8);表示取字段2位后的8个数,赋值string2{2}变量作为轴的偏移量不宜过大,否则会超出机器人的移动范围,因此2-9位取值应为0000300mm。机器人移动到距离p10点x轴方向300mm,y轴300mm,z轴15mm的位置。
接下来是matlab代码:字符100000300robotstudio。
%%socket communication with robotstudio tc=tcpip('127.0.0.1、55000);%若使用;matlab2021a以上的版本,将tcpip改为tcpclient %open the communication fopen(tc); %recive a message from the robotstudio message=fread(tc); %send a message to the robotstudio fwrite(tc,'100000300');
通信时,首先运行robotstudio端代码,
以下提示出现后启动matlab端代码:
启动matlab打开示教器后,出现以下提示,表示已收到信息。
机器人移动到如图所示的位置。
代码不是最终版本,通信只能移动一次,然后需要连续向机器人发送信息,实现连续运动。