在日常的开发中,不同的传感器支持的开发语言常常是不同的。例如Kinect一般是用C++开发的,Leapmotion用JAVA开发比较多。
去年暑假(17年暑假)做的一个项目是:用Leapmotion捕捉人手的五个手指关节信息,然后经过变换,传输给一个同样具有五个手指的机械手。
一开始拿到的开发框架,Leapmotion是用JAVA开发的;机械手AR10是用C#开发。
于是分别通过编程实现,使得JAVA端能够使Leapmotion捕捉人手五个手指10个关节的信息并保存为文本文件;
C#端能够使AR10读取文本文件,转化为各个关节的位置指令,实现同样的动作指令。
然而这样只能做到离线控制,需要通过Socket通信,实现数据的实时传输,才能实现控制。
JAVA端添加的代码:
在一开始添加库:
import java.net.ServerSocket;
import java.net.Socket;
在类里面添加(其中tmp是需要不断被实时发送的数据):
tmp = angleThumb12+" "+angleThumb23+" "+angleIndex01+" "+angleIndex12+" "+angleMiddle01+" "+angleMiddle12+" "+angleRing01+" "+angleRing12+" "+anglePinky01+" "+anglePinky12+" "+" ";
System.out.println("Java Sockets Program has started."); int i=0; try { DatagramSocket socket = new DatagramSocket(); System.out.println("Sending the udp socket..."); // Send the Message "HI" socket.send(toDatagram("",InetAddress.getByName("127.0.0.1"),3800)); //while (true) { System.out.println(tmp); System.out.println("Sending hi " + i); Thread.currentThread(); Thread.sleep(10); socket.send(toDatagram(String.valueOf(tmp),InetAddress.getByName("127.0.0.1"),3800)); i++; } catch (Exception e) { e.printStackTrace(); }
C#端添加的代码
添加包含头文件:
using System.Net;
using System.Net.Sockets;
在C#制作的GUI界面中需要触发接收数据的按钮下,例如
private void button1_Click(object sender, EventArgs e)
{
}
里面添加:
private void button1_Click(object sender, EventArgs e) { string returnData; byte[] receiveBytes; //ConsoleKeyInfo cki = new ConsoleKeyInfo(); using (UdpClient udpClient = new UdpClient(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3800))) { IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3800); while (true) { receiveBytes = udpClient.Receive(ref remoteIpEndPoint); returnData = Encoding.ASCII.GetString(receiveBytes); textBox1.AppendText(returnData + Environment.NewLine); //Console.WriteLine(returnData); float angle1 = 0; float angle2 = 0; float angle3 = 0; float a0 = 0; float a1 = 0; float a2 = 0; float a3 = 0; float a4 = 0; float a5 = 0; float a6 = 0; float a7 = 0; float a8 = 0; float a9 = 0; int k = 0; string[] arr = new string[10]; arr = returnData.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string i in arr) { mainTextBox.AppendText("target: " + k + "s" + i + "s" + Environment.NewLine); if (k == 1) { angle1 = Convert.ToSingle(i); angle2 = angle1 * (-20) + 2219; if (angle2 < 1621) { angle2 = 1621; } if (angle2 > 2000) { angle2 = 2000; } angle3 = angle2 * 4; a1 = angle2; TrySetTarget((byte)11, (ushort)angle3); } //.........//if (k == 9) { angle1 = Convert.ToSingle(i); angle2 = angle1 * (-16) + 2252; if (angle2 < 992) { angle2 = 992; } if (angle2 > 2000) { angle2 = 2000; } angle3 = angle2 * 4; a9 = angle2; TrySetTarget((byte)12, (ushort)angle3); } k = k + 1; } } } }