如何读取机器人手臂的位置?救命 [英] How do I read position of the robot arm? Help

查看:98
本文介绍了如何读取机器人手臂的位置?救命的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我希望每个人都享受他们快乐的星期五。我正在编写代码来控制一个机器人手臂,它上面有两个电机可以水平和垂直移动。我发现了类似的代码,但是它在C#中,我将它转换为Vb.net。我可以向后,向前,向上,向下移动手臂,也可以在家用电机上移动。我试图在文本框中读取水平和垂直电机的位置 - textPosH& textPosV。它显示在textPosH中的移动位置,但随后它变为8,所以让我们说如果我向前移动100mm然后在文本框中它将显示100只是一秒钟然后变回8并且那8总是停留在那里而垂直甚至没有显示任何信息。我在下面的代码中包含了两个版本(C#和VB.Net)。如果有人能帮助我阅读水平和垂直电机的实际位置,那将是很好的。我是编程新手。那是我的第一个项目。对于信息,C#版本的代码可以完美地工作并且可以正确显示位置。我正在将该代码更改为vb.net,因为我对它更熟悉,后来我想为应用程序添加更多功能。我只对速度,加速度和原点的位置感兴趣。提前致谢。



我尝试了什么:



VB。代码的净版本 -



 进口系统
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Linq
Imports System.Text
Imports System .Threading.Tasks
Imports System.Windows.Forms



公开 MainMenuForm
继承表格

Const RUN_ACC_H As 整数 = 10
Const RUN_ACC_V 作为 整数 = 10
Const RUN_SPEED_H 作为 整数 = 2000
Const RUN_SPEED_V 作为 整数 = 15



枚举 MOVE_DIRECTION
固定
StationaryMouseDown
MovingBack
MovingFwd
结束 枚举
Dim _tcpClient As System.Net.Sockets.Tc pClient
Dim _tcpStream As System.Net.Sockets.NetworkStream
Dim _logStream As System.IO.FileStream
Dim _readBuffer 作为 字节()
Dim _strBuffer 作为 字符串
Dim _bDisconnecting As Boolean
Dim _movingH As MOVE_DIRECTION
Dim _movingV 作为 MOVE_DIRECTION
公共 Sub 氖w ()
_bDisconnecting = True
_readBuffer = < span class =code-keyword>字节
256 ){}
_logStream = 没什么

_logStream = System.IO.FileStream( RxLog.log,System.IO.FileMode.Append)
_strBuffer =
_movingH = MOVE_DIRECTION.Stationary
_movingV = MOVE_DIRECTION.Stationary
_tcpClient = Nothing
InitializeComponent()
Dim assembly As System.Reflection.Assembly = System.Reflection.Assembly.GetExecutingAssembly()
EnableButtons( False
SettingsForm.hScrollSpeedH.LargeChange = RUN_SPEED_H / 20
SettingsForm.hScrollSpeedH.Maximum = RUN_SPEED_H + SettingsForm.hScrollSpeedH.LargeChange - 1
SettingsForm.hScrollSpeedH.Value = RUN_SPEED_H
SettingsForm.hScrollSpeedH_Scroll( Nothing Nothing
SettingsForm.hScrollSpeedV.LargeChange = RUN_SPEED_V / 10
SettingsForm.hScrollSpeedV.Maximum = RUN_SPEED_V + SettingsForm.hScrollSpeedV.LargeChange - 1
SettingsForm.hScrollSpeedV.Value = RUN_SPEED_V
SettingsForm.hScrollSpeedV_Scroll( Nothing Nothing

结束 Sub

私有 Sub EnableButtons( ByVal enable As Boolean
BtnHome.Enabled = enable
BtnUp.Enabled = enable
BtnDown.Enabled =启用
BtnForword.Enabled =启用
BtnBackword.Enabled =启用
BtnStop.Enabled =启用
BtnStart.Enabled =启用
textPosH .Enabled =启用
textPosV.Enabled =启用
结束 Sub
委托 Sub SetTextCallback( ByVal text < span class =code-keyword>作为 字符串 ByVal 垂直作为 Boolean
委托 Sub SetTextOnlyCallback( ByVal text As String
代理 Sub SetColourCallback( ByVal color 作为颜色, ByVal 垂直作为 Boolean

私有 Sub SetColourPos( ByVal 颜色作为颜色, ByVal 垂直作为 布尔
如果 如果(Vertical,textPosV.InvokeRequired,textPosH.InvokeRequired)然后

尝试
Dim d As SetColourCallback = New SetColourCallback( AddressOf SetColourPos)
Invoke(d, New 对象(){color,Vertical})
Catch __unusedException1__ As 异常
结束 尝试
否则

如果垂直那么
textPosV.BackColor = color
E. lse
textPosH.BackColor = color
结束 如果
结束 如果
结束 Sub


私有 Sub SetTextPos( ByVal text As 字符串 ByVal 垂直作为 布尔
如果 如果(Vertical,textPosV.InvokeRequired,textPosH.InvokeRequired)< span class =code-keyword>然后


尝试
昏暗 d As SetTextCallback = SetTextCallback( AddressOf SetTextPos)
调用(d, 对象(){text,Vertical})
Catch __unusedException1__ As 异常
结束 尝试
否则

如果垂直那么
textPosV.Text = text

如果 Int32 .Parse(text)> = Int32 .Parse(SettingsForm.textMaxPosV .Text)* 0 98 然后
SettingsForm.textMaxPosV.BackColor = Color.Orange
否则
SettingsForm。 textMaxPosV.BackColor = SystemColors.Window
结束 如果
Else
textPosH.Text = text

如果 Int32 .Parse(text)> = Int32 .Parse(SettingsForm.textMaxPosH.Text)* 0 98 然后
SettingsForm.textMaxPosH.BackColor = Color.Orange
Else
SettingsForm.textMaxPosH.BackColor = SystemColors.Window
结束 如果
结束 如果
结束 如果
结束 Sub
私人 < span class =code-keyword>功能 HandleReply( ByVal 回复作为 字符串作为 布尔
Dim 已处理 布尔 = False
Dim pos As 整数 = 0
Dim isV As Boolean =(回复。 IndexOf( 。2)> = 0
' Ux.1 = 8< cr>< lf>移动完成任何移动cmd
' Ux.2 = 8< cr>< lf>移动完成任何移动cmd
' Ux.1 = 0< cr>< lf>电机状态?99.1
' 0 =正在运行,1 =溢出,2 =超速,4 =重载,8 =在位置
如果((pos = reply.IndexOf( Ux。)> = 0 ))然后
Dim posEq As 整数 = reply.IndexOf( = c)
如果(posEq> = 0 那么
Dim res As Integer = 1
Int32 .TryParse(reply.Substring(posEq + 1 ),res)
Dim setColour As Color = Color.Red

如果 res = 0 那么
setColour = Color.Green
ElseIf res = 8 然后
setColour = SystemColors.Control
结束 如果

SetColourPos (setColour,(回复(pos + 3 )= 2 c))
Handled = True
结束 如果

结束 如果

' Px 0.1 = 245< CR>< LF>当前位置?96.1
如果(pos = reply.IndexOf( < span class =code-string> Px。)> = 0 然后
Dim posEq As 整数 = reply.IndexOf( = c)
如果(posEq> = 0 那么
Dim res As 整数 = -999
Int32 .TryParse(reply.Substring((posEq + 1 )),res)
.SetTextPos(res.ToString (),(回复(pos + 3 )= 2 c))
Handled = True
结束 < span class =code-keyword>如果

结束 如果

' Sx.1 = 0< cr>< lf>当前速度?97.1
如果(pos = reply.IndexOf( < span class =code-string> Sx。)> = 0 然后
Dim posEq As 整数 = reply.IndexOf( = c)
如果(posEq> = 0 那么
Dim res As 整数 = -999
Int32 .TryParse(reply.Substring((posEq + 1 )),res)

Handled = True
结束 如果

结束 如果

' IX.1 = 0℃; CR>< LF>当前Acc?98.1
如果((pos = reply.IndexOf( Ix。)> = 0 ))然后
Dim posEq 作为 整数 = reply.IndexOf( = c)
如果(posEq> = 0 那么
Dim res As 整数 = -999
Int32 .TryParse(reply.Substring((posEq + 1 )),res)

Handled = True
结束 如果

结束 如果

' Origin.1 = 909< CR>< LF>找到并设置原点| .1
' Origin.2 = 41< cr>< LF>找到并设置原点| .2
如果(pos = reply.IndexOf( Origin。)> = 0 然后
Dim posEq As 整数 = reply.IndexOf( = c)
如果(posEq> = 0 那么

Handled = True
结束 如果

结束 如果

' 检查回显的命令
选择 案例(reply.Substring( 0 1 ))
案例 | ^ P S
已处理= True
结束 选择

返回已处理
结束 功能
私有 Sub OnDataAvailable( ByVal 结果 As IAsyncResult)
如果 _bDisconnecting 然后

尝试
Dim nRead As Integer = _tcpStream.EndRead(result)

如果 nRead> 0 然后
_strBuffer + = Encoding.ASCII.GetString(_readBuffer, 0 ,nRead)
_logStream.Write(_readBuffer, 0 ,nRead)
Dim [ end ] 作为 整数 = 0

[ end ]> = 0 AndAlso _bDisconnecting
Dim nIgnore As 整数 = 0

while nIgnore< _strBuffer.Length AndAlso (_strBuffer(nIgnore)= vbCr OrElse _strBuffer(nIgnore)= vbLf)
nIgnore + = 1
结束

[ end ] = _strBuffer.IndexOf(vbCrLf,nIgnore)

如果 [ end ]> = 0 然后
Dim sRx As String = _strBuffer.Substring(nIgnore,[ end ] + 2

如果 _strBuffer.Lengt h> [ end ] + 2 然后
_strBuffer = _strBuffer.Substring([ end ] + 2
Else
_strBuffer =
结束 如果

如果 HandleReply(sRx)然后 AppendLog( Rx:& sRx)
结束 如果
结束 虽然
结束 如果

如果 _bDisconnecting 那么 _tcpStream.BeginRead(_readBuffer, 0 256 AsyncCallback( AddressOf OnDataAvailable), Nothing
Catch __unusedException1__ As 异常
结束 尝试
结束 如果
结束 Sub


私人 Sub BtnConnect_Click(发件人作为 对象 ,e As EventArgs)句柄 BtnConnect.Click
如果 BtnConnect.Text = Connect 然后

尝试
_tcpClient = System.Net.Sockets.TcpClient()
_tcpClient.Connect( 193.240.200.203 10001
_tcpStream = _tcpClient.GetStream()
_tcpStream.BeginRead(_readBuffer, 0 256 AsyncCallback( AddressOf OnDataAvailable), Nothing
BtnConnect.Text = 断开
_bDisconnecting = False
EnableButtons( True
SendCmd( S.1 =& SettingsForm.hScrollSpeedH.Value.ToString())
SendCmd( A.1 = & RUN_ACC_H.ToString())
SendCmd( S.2 =& SettingsForm.hScrollSpeedV.Value.ToString())
SendCmd( A.2 = & RUN_ACC_V.ToString())
Catch ex As System.Net.Sockets.SocketException
MessageBox.Show(ex.Message, Socket Exception
< span class =code-keyword>结束
尝试
其他
_bDisconnecting = True
timerQuery.Enabled = False
_tcpClient.Close()
_tcpClient = Nothing
BtnConnect.Text = Connect
EnableButtons( False
结束 如果
结束 Sub
私有 Sub SendCmd( ByVal cmd As String

cmd + = vbCrLf
Dim cmdHok As 布尔值 =(cmd.IndexOf( 。1 )> = 0 )
Dim cmdVok As Boolean = (cmd.IndexOf(\".2\") >= 0)

If True < span class=\"code-keyword\">Then


Select Case cmd(0)
Case \" |\"c

Case Else
End Select
$b$ b Dim send As Byte() = Encoding.ASCII.GetBytes(cmd)
_tcpStream.Write(send, 0, send.Length)
System.Threading.Thread.Sleep(10)
End If
End Sub


Private Sub BtnHome_Click(sender As Object, e As EventArgs) Handles BtnHome.Click
SendCmd(\").1\")
SendCmd(\"(.1\")
SendCmd(\"|.1\")
Se ndCmd(\").2\")
SendCmd(\"(.2\")
SendCmd(\"|.2\")
End Sub


Private Sub BtnForword_Click(sender As Object, e As EventArgs) Handles BtnForword.Click
Dim p As Integer = Int32.Parse(textPosH.Text)
Dim inc As Integer = < span class=\"code-sdkkeyword\">Int32.Parse(SettingsForm.textMoveH.Text)
Dim target As Integer = p + inc
Dim maxVal As Integer = 0


If Int32.TryParse(SettingsForm.textMaxPosH.Text, maxVal) Then
If target > maxVal Then target = maxVal
SendCmd(\"P.1=\" & target.ToString())
SendCmd(\"^.1\")
End If

End Sub



Private Sub BtnBackword_Click(sender As Object, e As EventArgs) Handles BtnBackword.Click
Dim p As Integer = Int32.Parse(textPosH.Text)
Dim inc As Integer = Int32.Parse(SettingsForm.textMoveH.Text)
Dim target As Integer = p - inc
If target < 0 Then target = 0
SendCmd(\"P.1=\" & target.ToString())
SendCmd(\"^.1\")
End Sub

Private Sub BtnUp_Click(sender As Object, e As EventArgs) Handles BtnUp.Click
Dim p As Integer = Int32.Parse(textPosV.Text)
Dim inc As Integer = Int32.Parse(SettingsForm.textMoveV.Text)
Dim target As Integer = p + inc
Dim maxVal As Integer = 0

If Int32.TryParse(SettingsForm.textMaxPosV.Text, maxVal) Then
If target > maxVal Then target = maxVal
SendCmd(\"P.2=\" & target.ToString())
SendCmd(\"^.2\")
End If
End Sub

Private Sub BtnDown_Click(sender As Object, e As EventArgs) Handles BtnDown.Click
Dim p As Integer = Int32.Parse(textPosV.Text)
Dim inc As Integer = Int32.Parse(SettingsForm.textMoveV.Text)
Dim target As Integer = p - inc
If target < 0 Then target = 0
SendCmd(\"P.2=\" & target.ToString())
SendCmd(\"^.2\")
End Sub
Private Sub MainMenu_FormClosed(ByVal sender As Object, ByVal e As FormClosedEventArgs)
_logStream.Close()
End Sub

Private Sub HineMotorSetup_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs)
_bDisconnecting = True

If BtnConnect.Text = \"Disconnect\" Then
BtnConnect_Click(sender, Nothing)
System.Threading.Thread.Sleep(100)
End If
End Sub



Private Sub EXITToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EXITToolStripMenuItem.Click

End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles TimerQuery.Tick

SendCmd(\"?97.1\")
SendCmd(\"?96.1\")
SendCmd(\"?97.2\")
SendCmd(\"?96.2\")

End Sub

Private Sub BtnStop_Click(sender As Object, e As EventArgs) Handles BtnStop.Click
SendCmd(\").1\")
SendCmd(\").2\")
End Sub


Private Sub BtnStart_Click(sender As Object, e As EventArgs) Handles BtnStart.Click
SendCmd(\"(.1 \")
SendCmd(\"(.2\")
End Sub

Private Sub ExitToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem1.Click
End

End Sub

Private Sub SettingsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SettingsToolStripMenuItem.Click $ b$b SettingsForm.Show()
End Sub

Private Sub AppendLog(p1 As String)
Throw New NotImplementedException
End Sub



End Class



----------------------------------------------------------------------------------

C# version of the code -



#define HINEMOTORSETUP_LOG_ALL_RX 
#define HINEMOTORSETUP_DISABLE_CORNERS

using System;
使用 System.Collections.Generic;
使用 System.ComponentModel;
使用 System.Data;
使用 System.Drawing;
使用 System.Linq;
使用 System.Text;
使用 System.Threading.Tasks;
使用 System.Windows.Forms;

namespace HineMotorSetup
{
public partial class HineMotorSetup : Form
{

const int JOYSTICK_SIZE = 5;
const int JOYSTICK_CENTRE = 10;
const int RUN_ACC_H = 10;
const int RUN_ACC_V = 10;
const int JOYSTICK_ACC_H = 1;
const int JOYSTICK_ACC_V = 1;
const int RUN_SPEED_H = 2000;
const int RUN_SPEED_V = 15;

enum MOVE_DIRECTION
{
Stationary,
StationaryMouseDown,
MovingBack,
MovingFwd
};

private System.Net.Sockets.TcpClient _tcpClient;
private System.Net.Sockets.NetworkStream _tcpStream;
private System.IO.FileStream _logStream;
private Byte[] _readBuffer;
private String _strBuffer;
private MOVE_DIRECTION _movingH;
private MOVE_DIRECTION _movingV;
private bool _bDisconnecting;

public HineMotorSetup()
{
_bDisconnecting = true;
_readBuffer = new Byte[256];
_logStream = null;
#if (HINEMOTORSETUP_LOG_ALL_RX)
_logStream = new System.IO.FileStream(\"RxLog.log\", System.IO.FileMode.Append);
#endif

_strBuffer = \"\";
_movingH = MOVE_DIRECTION.Stationary;
_movingV = MOVE_DIRECTION.Stationary;
_tcpClient = null;

InitializeComponent();
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
Text = \"Hine Motor Setup v\" + assembly.GetName().Version;
EnableButtons(false);
hScrollSpeedH.LargeChange = RUN_SPEED_H / 20;
hScrollSpeedH.Maximum = RUN_SPEED_H + hScrollSpeedH.LargeChange - 1;
hScrollSpeedH.Value = RUN_SPEED_H;
hScrollSpeedH_Scroll(null, null);
hScrollSpeedV.LargeChange = RUN_SPEED_V / 10;
hScrollSpeedV.Maximum = RUN_SPEED_V + hScrollSpeedV.LargeChange - 1;
hScrollSpeedV.Value = RUN_SPEED_V;
hScrollSpeedV_Scroll(null, null);
}

public static DialogResult InputBox(string title, string promptText, ref string value)
{
Form form = new Form();
Label label = new Label();
TextBox textBox = new TextBox();
Button buttonOk = new Button();
Button buttonCancel = new Button();

form.Text = title;
label.Text = promptText;
textBox.Text = value;

buttonOk.Text = \"OK\";
buttonCancel.Text = \"Cancel\";
buttonOk.DialogResult = DialogResult.OK;
buttonCancel.DialogResult = DialogResult.Cancel;

label.SetBounds(9, 20, 372, 13);
textBox.SetBounds(12, 36, 372, 20);
buttonOk.SetBounds(228, 72, 75, 23);
buttonCancel.SetBounds(309, 72, 75, 23);

label.AutoSize = true;
textBox.Anchor = textBox.Anchor | AnchorStyles.Right;
buttonOk.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;

form.ClientSize = new Size(396, 107);
form.Controls.AddRange(new Control[] { label, textBox, buttonOk, buttonCancel });
form.ClientSize = new Size(Math.Max(300, label.Right + 10), form.ClientSize.Height);
form.FormBorderStyle = FormBorderStyle.FixedDialog;
form.StartPosition = FormStartPosition.CenterScreen;
form.MinimizeBox = false;
form.MaximizeBox = false;
form.AcceptButton = buttonOk;
form.CancelButton = buttonCancel;

DialogResult dialogResult = form.ShowDialog();
value = textBox.Text;
return dialogResult;
}

private void EnableButtons(bool enable)
{
btnHome.Enabled = enable;
btnJogDn.Enabled = enable;
btnJogUp.Enabled = enable;
btnJogExtend.Enabled = enable;
btnJogRetract.Enabled = enable;
btnSend.Enabled = enable;
btnStop.Enabled = enable;
btnEnableMotors.Enabled = enable;
textPosH.Enabled = enable;
textPosV.Enabled = enable;
}

delegate void SetTextOnlyCallback(string text);
delegate void SetTextCallback(string text, bool Vertical);
delegate void SetColourCallback(Color colour, bool Vertical);

private void AppendLog(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (textLog.InvokeRequired)
{
try
{
SetTextOnlyCallback d = new SetTextOnlyCallback(AppendLog);
Invoke(d, new object[] { text });
}
catch (Exception)
{
}
}
else
{
textLog.Text += text;
textLog.Select(textLog.Text.Length, 0);
textLog.ScrollToCaret();
}
}

private void SetTextOrig(string text, bool Vertical)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (Vertical ? textOrigV.InvokeRequired : textOrigH.InvokeRequired)
{
try
{
SetTextCallback d = new SetTextCallback(SetTextOrig);
Invoke(d, new object[] { text, Vertical });
}
catch (Exception)
{
}
}
else
{
if (Vertical)
textOrigV.Text = text;
else
textOrigH.Text = text;
}
}

private void SetColourPos(Color colour, bool Vertical)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (Vertical ? textPosV.InvokeRequired : textPosH.InvokeRequired)
{
try
{
SetColourCallback d = new SetColourCallback(SetColourPos);
Invoke(d, new object[] { colour, Vertical });
}
catch (Exception)
{
}
}
else
{
if (Vertical)
textPosV.BackColor = colour;
else
textPosH.BackColor = colour;
}
}

private void SetTextPos(string text, bool Vertical)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (Vertical ? textPosV.InvokeRequired : textPosH.InvokeRequired)
{
try
{
SetTextCallback d = new SetTextCallback(SetTextPos);
Invoke(d, new object[] { text, Vertical });
}
catch (Exception)
{
}
}
else
{
if (Vertical)
{
textPosV.Text = text;
if (Int32.Parse(text) >= Int32.Parse(textMaxPosV.Text) * 0.98)
{
textMaxPosV.BackColor = Color.Orange;
}
else
{
textMaxPosV.BackColor = SystemColors.Window;
}
}
else
{
textPosH.Text = text;
if (Int32.Parse(text) >= Int32.Parse(textMaxPosH.Text)*0.98)
{
textMaxPosH.BackColor = Color.Orange;
}
else
{
textMaxPosH.BackColor = SystemColors.Window;
}
}
}
}

private void SetTextSpeed(string text, bool Vertical)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (Vertical ? textSpeedV.InvokeRequired : textSpeedH.InvokeRequired)
{
try
{
SetTextCallback d = new SetTextCallback(SetTextSpeed);
Invoke(d, new object[] { text, Vertical });
}
catch (Exception)
{
}
}
else
{
if (Vertical)
textSpeedV.Text = text;
else
textSpeedH.Text = text;
}
}

private void SetTextAccel(string text, bool Vertical)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (Vertical ? textAccelV.InvokeRequired : textAccelH.InvokeRequired)
{
try
{
SetTextCallback d = new SetTextCallback(SetTextAccel);
Invoke(d, new object[] { text, Vertical });
}
catch (Exception)
{
}
}
else
{
if (Vertical)
textAccelV.Text = text;
else
textAccelH.Text = text;
}
}

private bool HandleReply(String reply)
{
bool Handled = false;
int pos = 0;
bool isV = reply.IndexOf(\".2\") >= 0;

//Ux.1=8<cr><lf> Movement complete any movement cmd
//Ux.2=8<cr><lf> Movement complete any movement cmd
//Ux.1=0<cr><lf> Motor Status ?99.1
// 0=Running, 1=overflow, 2=overspeed, 4=overload, 8=In position
if ((pos = reply.IndexOf(\"Ux.\")) >= 0)
{
int posEq = reply.IndexOf('=');
if (posEq >= 0)
{
int res = 1;
Int32.TryParse(reply.Substring(posEq + 1), out res);
Color setColour = Color.Red;
if (res == 0)
setColour = Color.Green;
else if (res == 8)
{
setColour = SystemColors.Control;
}

SetColourPos(setColour, (reply[pos + 3] == '2'));
Handled = true;
}
}

//Px.1=245<cr><lf> Current Pos ?96.1
if ((pos = reply.IndexOf(\"Px.\")) >= 0)
{
int posEq = reply.IndexOf('=');
if (posEq >= 0)
{
int res = -999;
Int32.TryParse(reply.Substring(posEq + 1), out res);

SetTextPos(res.ToString(), (reply[pos + 3] == '2'));
Handled = true;
}
}

//Sx.1=0<cr><lf> Current Speed ?97.1
if ((pos = reply.IndexOf(\"Sx.\")) >= 0)
{
int posEq = reply.IndexOf('=');
if (posEq >= 0)
{
int res = -999;
Int32.TryParse(reply.Substring(posEq + 1), out res);

SetTextSpeed(res.ToString(), (reply[pos + 3] == '2'));
Handled = true;
}
}

//Ix.1=0<cr><lf> Current Acc ?98.1
if ((pos = reply.IndexOf(\"Ix.\")) >= 0)
{
int posEq = reply.IndexOf('=');
if (posEq >= 0)
{
int res = -999;
Int32.TryParse(reply.Substring(posEq + 1), out res);

SetTextAccel(res.ToString(), (reply[pos + 3] == '2'));
Handled = true;
}
}


//Origin.1=909<cr><lf> Found and set origin |.1
//Origin.2=41<cr><lf> Found and set origin |.2
else if ((pos = reply.IndexOf(\"Origin.\")) >= 0)
{
int posEq = reply.IndexOf('=');
if (posEq >= 0)
{
SetTextOrig(reply.Substring(posEq + 1), (reply[pos + 7] == '2'));
Handled = true;
}
}

//Check for echoed commands
switch (reply.Substring(0,1))
{
case \"?\":
case \"(\":
case \")\":
case \"|\":
case \"^\":
case \"A\":
case \"P\":
case \"S\":
Handled = true;
break ;
}
return Handled;
}

private void OnDataAvailable(IAsyncResult result)
{
if (!_bDisconnecting)
{
try
{
int nRead = _tcpStream.EndRead(result);

if (nRead > 0)
{
_strBuffer += Encoding.ASCII.GetString(_readBuffer, 0, nRead);
#if (HINEMOTORSETUP_LOG_ALL_RX)
_logStream.Write(_readBuffer, 0, nRead);
#endif

int end = 0;
while (end >= 0 && !_bDisconnecting)
{
//Ignore leading /r/n
int nIgnore = 0;
while (nIgnore < _strBuffer.Length && (_strBuffer[nIgnore] == '\r' || _strBuffer[nIgnore] == '\n'))
nIgnore++;
end = _strBuffer.IndexOf(\"\r\n\", nIgnore);
if (end >= 0)
{
String sRx = _strBuffer.Substring(nIgnore, end + 2);
if (_strBuffer.Length > end + 2)
_strBuffer = _strBuffer.Substring(end + 2);
else
_strBuffer = \"\";

if (!HandleReply(sRx))
AppendLog(\"Rx: \" + sRx);
}
}
}
//Setup the Async Read again for the next data received.
if (!_bDisconnecting)
_tcpStream.BeginRead(_readBuffer, 0, 256, new AsyncCallback(OnDataAvailable), null);
}
catch (Exception)
{

}
}
}

private void btnConnect_Click(object sender, EventArgs e)
{
if (btnConnect.Text == \"Connect\")
{
try
{
_tcpClient = new System.Net.Sockets.TcpClient();
_tcpClient.Connect(\"193.240.200.203\", 10001);
_tcpStream = _tcpClient.GetStream();
_tcpStream.BeginRead(_readBuffer, 0, 256, new AsyncCallback(OnDataAvailable), null);
btnConnect.Text = \"Disconnect\";
EnableButtons(true);
timerQuery.Enabled = true;
_bDisconnecting = false;

//Set Dynamic Command speed and acceleration
SendCmd(\"S.1=\" + hScrollSpeedH.Value.ToString());
SendCmd(\"A.1=\" + RUN_ACC_H.ToString());
SendCmd(\"S.2=\" + hScrollSpeedV.Value.ToString());
SendCmd(\"A.2=\" + RUN_ACC_V.ToString());
}
catch (System.Net.Sockets.SocketException ex)
{
MessageBox.Show(ex.Message, \"Socket Exception\");
}
}
else
{
_bDisconnecting = true;
timerQuery.Enabled = false;
EnableButtons(false);
_tcpClient.Close();
_tcpClient = null;
btnConnect.Text = \"Connect\";
}
}

private void SendCmd(String cmd)
{
if (!_bDisconnecting)
{
cmd += \"\r\n\";
bool cmdHok = (cmd.IndexOf(\".1\") >= 0);
bool cmdVok = (cmd.IndexOf(\".2\") >= 0);
{
switch (cmd[0])
{
case '|':
if (cmdHok)
{
SetColourPos(Color.Orange, cmdVok);
}
else if (cmdVok)
{
SetColourPos(Color.Orange, cmdVok);
}
break;
default:
break;
}

byte[] send = Encoding.ASCII.GetBytes(cmd);
_tcpStream.Write(send, 0, send.Length);
System.Threading.Thread.Sleep(10); //Seems to stop overlapping replies!
}
}
}

private void btnHome_Click(object sender, EventArgs e)
{
SendCmd(\").1\");
SendCmd(\"(.1\");
SendCmd(\"|.1\");
SendCmd(\").2\");
SendCmd(\"(.2\");
SendCmd(\"|.2\");
}

private void btnSend_Click(object sender, EventArgs e)
{
SendCmd(textSend.Text);
}

private void timerQuery_Tick(object sender, EventArgs e)
{
SendCmd(\"?99.1\"); //Motor status
SendCmd(\"?98.1\"); //Motor acceleration
SendCmd(\"?97.1\"); //Motor speed
SendCmd(\"?96.1\"); //Motor position
SendCmd(\"?99.2\");
SendCmd(\"?98.2\");
SendCmd(\"?97.2\");
SendCmd(\"?96.2\");

}

private void btnEnableMotors_Click(object sender, EventArgs e)
{
SendCmd(\"(.1\");
SendCmd(\"(.2\");
}

private void btnStop_Click(object sender, EventArgs e)
{
SendCmd(\").1\");
SendCmd(\").2\");
}

private void btnJogExtend_Click(object sender, EventArgs e)
{
int p = Int32.Parse(textPosH.Text);
int inc = Int32.Parse(textJogH.Text);
int target = p + inc;
int maxVal = 0;
if (Int32.TryParse(textMaxPosH.Text, out maxVal))
{
if (target > maxVal)
target = maxVal;
SendCmd(\"P.1=\" + target.ToString());
SendCmd(\"^.1\");
}
}

private void btnJogRetract_Click(object sender, EventArgs e)
{
int p = Int32.Parse(textPosH.Text);
int inc = Int32.Parse(textJogH.Text);
int target = p - inc;
if (target < 0)
target = 0;
SendCmd(\"P.1=\" + target.ToString());
SendCmd(\"^.1\");
}

private void btnJogUp_Click(object sender, EventArgs e)
{
int p = Int32.Parse(textPosV.Text);
int inc = Int32.Parse(textJogV.Text);
int target = p + inc;
int maxVal = 0;
if (Int32.TryParse(textMaxPosV.Text, out maxVal))
{
if (target > maxVal)
target = maxVal;
SendCmd(\"P.2=\" + target.ToString());
SendCmd(\"^.2\");
}
}

private void btnJogDn_Click(object sender, EventArgs e)
{
int p = Int32.Parse(textPosV.Text);
int inc = Int32.Parse(textJogV.Text);
int target = p - inc;
if (target < 0)
target = 0;
SendCmd(\"P.2=\" + target.ToString());
SendCmd(\"^.2\");
}

private void imgJoystick_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawRectangle(Pens.Red, imgJoystick.Width / 2 - JOYSTICK_CENTRE, imgJoystick.Height / 2 - JOYSTICK_CENTRE, JOYSTICK_CENTRE * 2, JOYSTICK_CENTRE*2);

int xpos = imgJoystick.Width / 2 - JOYSTICK_SIZE;
if (_movingH == MOVE_DIRECTION.MovingBack)
xpos = 0;
else if (_movingH == MOVE_DIRECTION.MovingFwd)
xpos = imgJoystick.Width - JOYSTICK_SIZE * 2 - 2;

int ypos = imgJoystick.Height / 2 - JOYSTICK_SIZE;
if (_movingV == MOVE_DIRECTION.MovingBack)
ypos = imgJoystick.Height - JOYSTICK_SIZE * 2 - 2;
else if (_movingV == MOVE_DIRECTION.MovingFwd)
ypos = 0;

e.Graphics.FillEllipse(Brushes.Black, xpos, ypos, JOYSTICK_SIZE * 2, JOYSTICK_SIZE * 2);
}

private void imgJoystick_MouseDown(object sender, MouseEventArgs e)
{
_movingH = MOVE_DIRECTION.StationaryMouseDown;
_movingV = MOVE_DIRECTION.StationaryMouseDown;
SendCmd(\"S.1=\" + RUN_SPEED_H.ToString());
SendCmd(\"S.2=\" + RUN_SPEED_V.ToString());
SendCmd(\"A.1=\" + JOYSTICK_ACC_H.ToString());
SendCmd(\"A.2=\" + JOYSTICK_ACC_V.ToString());
imgJoystick_MouseMove(sender, e);
}

private void imgJoystick_MouseUp(object sender, MouseEventArgs e)
{
_movingH = MOVE_DIRECTION.Stationary;
_movingV = MOVE_DIRECTION.Stationary;
SendCmd(\").1\");
SendCmd(\"(.1\");
SendCmd(\").2\");
SendCmd(\"(.2\");
SendCmd(\"S.1=\" + hScrollSpeedH.Value.ToString());
SendCmd(\"S.2=\" + hScrollSpeedV.Value.ToString());
SendCmd(\"A.1=\" + RUN_ACC_H.ToString());
SendCmd(\"A.2=\" + RUN_ACC_V.ToString());
imgJoystick.Refresh();
}

private void imgJoystick_MouseMove(object sender, MouseEventArgs e)
{
if (_movingH != MOVE_DIRECTION.Stationary)
{
MOVE_DIRECTION prevH = _movingH;
int mid = imgJoystick.Width / 2;
if (e.X < mid - JOYSTICK_CENTRE
#if HINEMOTORSETUP_DISABLE_CORNERS
&& _movingV == MOVE_DIRECTION.StationaryMouseDown
#endif
)
{
_movingH = MOVE_DIRECTION.MovingBack;
}
else if (e.X > mid + JOYSTICK_CENTRE
#if HINEMOTORSETUP_DISABLE_CORNERS
&& _movingV == MOVE_DIRECTION.StationaryMouseDown
#endif
)
{
_movingH = MOVE_DIRECTION.MovingFwd;
}
else
{
_movingH = MOVE_DIRECTION.StationaryMouseDown;
}

if (prevH != _movingH)
{
if (_movingH == MOVE_DIRECTION.MovingFwd)
{
SendCmd(\"P.1=\" + textMaxPosH.Text);
SendCmd(\"^.1\");
}
else if (_movingH == MOVE_DIRECTION.MovingBack)
{
SendCmd(\"P.1=0\");
SendCmd(\"^.1\");
}
else
{
SendCmd(\").1\");
SendCmd(\"(.1\");
}
}
}
if (_movingV != MOVE_DIRECTION.Stationary)
{
MOVE_DIRECTION prevV = _movingV;
int mid = imgJoystick.Height / 2;
if (e.Y > mid + JOYSTICK_CENTRE
#if HINEMOTORSETUP_DISABLE_CORNERS
&& _movingH == MOVE_DIRECTION.StationaryMouseDown
#endif
)
{
_movingV = MOVE_DIRECTION.MovingBack;
}
else if (e.Y < mid - JOYSTICK_CENTRE
#if HINEMOTORSETUP_DISABLE_CORNERS
&& _movingH == MOVE_DIRECTION.StationaryMouseDown
#endif
)
{
_movingV = MOVE_DIRECTION.MovingFwd;
}
else
{
_movingV = MOVE_DIRECTION.StationaryMouseDown;
}

if (prevV != _movingV)
{
if (_movingV == MOVE_DIRECTION.MovingFwd)
{
SendCmd(\"P.2=\" + textMaxPosV.Text);
SendCmd(\"^.2\");
}
else if (_movingV == MOVE_DIRECTION.MovingBack)
{
SendCmd(\"P.2=0\");
SendCmd(\"^.2\");
}
else
{
SendCmd(\").2\");
SendCmd(\"(.2\");
}
}
}
imgJoystick.Refresh();
}

private void textPosH_Click(object sender, EventArgs e)
{
String rtn = \"\";
if (InputBox(\"Move Horizontal\", \"Enter target value:\", ref rtn) == DialogResult.OK)
{
int val = 0;
int maxVal = 0; $ b$b if (Int32.TryParse(rtn, out val) && Int32.TryParse(textMaxPosH.Text, out maxVal))
{
if (val > maxVal)
val = maxVal;
SendCmd(\"P.1=\" + val.ToString());
SendCmd(\"^.1\");
}
}
}

private void textPosV_Click(object sender, EventArgs e)
{
String rtn = \"\";
if (InputBox(\"Move Vertical\", \"Enter target value:\", ref rtn) == DialogResult.OK)
{
int val = 0;
int maxVal = 0;
if (Int32.TryParse(rtn, out val) && Int32.TryParse(textMaxPosV.Text, out maxVal))
{
if (val > maxVal)
val = maxVal;
SendCmd(\"P.2=\" + val.ToString());
SendCmd(\"^.2\");
}
}
}

private void hScrollSpeedH_Scroll(object sender, ScrollEventArgs e)
{
labelSetSpeedH.Text = \"Set Speed = \" + hScrollSpeedH.Value.ToString();
SendCmd(\"S.1=\" + hScrollSpeedH.Value.ToString());
}

private void hScrollSpeedV_Scroll(object sender, ScrollEventArgs e)
{
labelSetSpeedV.Text = \"Set Speed = \" + hScrollSpeedV.Value.ToString();
SendCmd(\"S.2=\" + hScrollSpeedV.Value.ToString());
}

private void HineMotorSetup_Deactivate(object sender, EventArgs e)
{
imgJoystick_MouseUp(sender, null);
}

private void HineMotorSetup_FormClosed(object sender, FormClosedEventArgs e)
{
#if (HINEMOTORSETUP_LOG_ALL_RX)
_logStream.Close();
#endif
}

private void HineMotorSetup_FormClosing(object sender, FormClosingEventArgs e)
{
_bDisconnecting = true;
if (btnConnect.Text == \"Disconnect\")
{
btnConnect_Click(sender, null);
System.Threading.Thread.Sleep(100);
}
}

private void HineMotorSetup_Load(object sender, EventArgs e)
{

}


private void textOrigH_TextChanged(object sender, EventArgs e)
{

}

private void imgJoystick_Click(object sender, EventArgs e)
{

}

private void textMaxPosH_TextChanged(object sender, EventArgs e)
{

}

}
}

解决方案

The problem of the not updated vertical value is sourced by a wrong C# to VB conversion for the line:

// C# 
SetTextPos(res.ToString(), (reply[pos + 3] == ’2’));

The second parameter of SetTextPos is a bool which is determined by comparing two characters. With VB you can use the Char.Equals method to get the required Boolean result to be passed:

' VB 
' Px.1 = horizontal, Px.2 = vertical
Me.SetTextPos(res.ToString(), \"2\"c.Equals(reply(pos + 3)))





When the robot always sends both positions after a movement, that should also solve your problem with the changing horizontal value. With your code, the robots sends the horizontal value (100) first and is displayed. When it sends the vertical value (8) afterwards that will be wrongly put into the horizontal text box staying there until the next pair of postions is send.

[/EDIT]


Quote:

How do I read position of the robot arm? Help



Since we don’t have the robot, we have no way to run this code, you are the only one able to do it.

-----

Your code do not behave the way you expect, or you don’t understand why !



There is an almost universal solution: Run your code on debugger step by step, inspect variables.

The debugger is here to show you what your code is doing and your task is to compare with what it should do.

There is no magic in the debugger, it don’t know what your is supposed to do, it don’t find bugs, it just help you to by showing you what is going on.当代码没有达到预期的效果时,你就接近了一个错误。

要查看你的代码在做什么:只需设置断点并查看代码是否正常运行,调试器允许你执行第1行第1行并在执行时检查变量。



此解决方案的缺点:

- 这是一个DIY,你是跟踪问题并找到根源的那个,这导致了解决方案。

这个解决方案的优点:

- 它也是一个很好的学习工具,因为它告诉你现实,你可以看到哪种期望与现实相符。



次要效果

- 你会为自己找到虫子感到自豪。

- 你的学习技巧会提高。



你应该很快就会发现什么是错的。



调试器 - 维基百科,免费的百科全书 [ ^ ]



掌握Visual Studio 2010中的调试 - 初学者指南 [ ^ ]

使用Visual Studio 2010进行基本调试 - YouTube [ ^ ]

Visual Basic / Visual Studio视频教程 - 基本调试 - YouTube [ ^ ]

初学者的Visual Basic .NET编程 - 断点和调试工具 [ ^ ]

调试器仅显示您的代码正在执行的操作,您的任务是与应该执行的操作进行比较


Hi Guys,

I Hope everyone is enjoying their happy Friday. I'm writing code to control a Robot Arm that has two motors on it to move Horizontal and vertical. I found similar code but it's in C# and I'm converting it into Vb.net. I'm able to move the arm backward, forward, up, down and can also home motors. I'm trying to read the position of the both Horizontal and vertical motors in textbox - textPosH & textPosV. It shows moved position in textPosH but then it changes to 8 so let's say if I moved forward 100mm then in text box it will show 100 just for a second then changes back to 8 and that 8 always stays in there while vertical doesn't even show any info. I'm including the both version ( C# and VB.Net) of code below. If anyone can help me to read the actual live position of both Horizontal and vertical motors that would be great. I'm new to programming. That's my first project. For the information C# version of the code works perfectly and shows positions live and correctly. I'm changing that code into vb.net because I'm more familiar with it and later on I want to add some more features to the application. I'm only interested in the position not in the speed, acceleration and origin. Thanks in advance.

What I have tried:

VB.Net version of the code -

Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.Windows.Forms



Public Class MainMenuForm
    Inherits Form

    Const RUN_ACC_H As Integer = 10
    Const RUN_ACC_V As Integer = 10
    Const RUN_SPEED_H As Integer = 2000
    Const RUN_SPEED_V As Integer = 15



    Enum MOVE_DIRECTION
        Stationary
        StationaryMouseDown
        MovingBack
        MovingFwd
    End Enum
    Dim _tcpClient As System.Net.Sockets.TcpClient
    Dim _tcpStream As System.Net.Sockets.NetworkStream
    Dim _logStream As System.IO.FileStream
    Dim _readBuffer As Byte()
    Dim _strBuffer As String
    Dim _bDisconnecting As Boolean
    Dim _movingH As MOVE_DIRECTION
    Dim _movingV As MOVE_DIRECTION
    Public Sub New()
        _bDisconnecting = True
        _readBuffer = New Byte(256) {}
        _logStream = Nothing

        _logStream = New System.IO.FileStream("RxLog.log", System.IO.FileMode.Append)
        _strBuffer = ""
        _movingH = MOVE_DIRECTION.Stationary
        _movingV = MOVE_DIRECTION.Stationary
        _tcpClient = Nothing
        InitializeComponent()
        Dim assembly As System.Reflection.Assembly = System.Reflection.Assembly.GetExecutingAssembly()
        EnableButtons(False)
        SettingsForm.hScrollSpeedH.LargeChange = RUN_SPEED_H / 20
        SettingsForm.hScrollSpeedH.Maximum = RUN_SPEED_H + SettingsForm.hScrollSpeedH.LargeChange - 1
        SettingsForm.hScrollSpeedH.Value = RUN_SPEED_H
        SettingsForm.hScrollSpeedH_Scroll(Nothing, Nothing)
        SettingsForm.hScrollSpeedV.LargeChange = RUN_SPEED_V / 10
        SettingsForm.hScrollSpeedV.Maximum = RUN_SPEED_V + SettingsForm.hScrollSpeedV.LargeChange - 1
        SettingsForm.hScrollSpeedV.Value = RUN_SPEED_V
        SettingsForm.hScrollSpeedV_Scroll(Nothing, Nothing)

    End Sub

    Private Sub EnableButtons(ByVal enable As Boolean)
        BtnHome.Enabled = enable
        BtnUp.Enabled = enable
        BtnDown.Enabled = enable
        BtnForword.Enabled = enable
        BtnBackword.Enabled = enable
        BtnStop.Enabled = enable
        BtnStart.Enabled = enable
        textPosH.Enabled = enable
        textPosV.Enabled = enable
    End Sub
    Delegate Sub SetTextCallback(ByVal text As String, ByVal Vertical As Boolean)
    Delegate Sub SetTextOnlyCallback(ByVal text As String)
    Delegate Sub SetColourCallback(ByVal colour As Color, ByVal Vertical As Boolean)
    
    Private Sub SetColourPos(ByVal colour As Color, ByVal Vertical As Boolean)
        If If(Vertical, textPosV.InvokeRequired, textPosH.InvokeRequired) Then

            Try
                Dim d As SetColourCallback = New SetColourCallback(AddressOf SetColourPos)
                Invoke(d, New Object() {colour, Vertical})
            Catch __unusedException1__ As Exception
            End Try
        Else

            If Vertical Then
                textPosV.BackColor = colour
            Else
                textPosH.BackColor = colour
            End If
        End If
    End Sub


    Private Sub SetTextPos(ByVal text As String, ByVal Vertical As Boolean)
        If If(Vertical, textPosV.InvokeRequired, textPosH.InvokeRequired) Then

            Try
                Dim d As SetTextCallback = New SetTextCallback(AddressOf SetTextPos)
                Invoke(d, New Object() {text, Vertical})
            Catch __unusedException1__ As Exception
            End Try
        Else

            If Vertical Then
                textPosV.Text = text

                If Int32.Parse(text) >= Int32.Parse(SettingsForm.textMaxPosV.Text) * 0.98 Then
                    SettingsForm.textMaxPosV.BackColor = Color.Orange
                Else
                    SettingsForm.textMaxPosV.BackColor = SystemColors.Window
                End If
            Else
                textPosH.Text = text

                If Int32.Parse(text) >= Int32.Parse(SettingsForm.textMaxPosH.Text) * 0.98 Then
                    SettingsForm.textMaxPosH.BackColor = Color.Orange
                Else
                    SettingsForm.textMaxPosH.BackColor = SystemColors.Window
                End If
            End If
        End If
    End Sub
    Private Function HandleReply(ByVal reply As String) As Boolean
        Dim Handled As Boolean = False
        Dim pos As Integer = 0
        Dim isV As Boolean = (reply.IndexOf(".2") >= 0)
        'Ux.1=8<cr><lf>          Movement complete       any movement cmd
        'Ux.2=8<cr><lf>          Movement complete       any movement cmd
        'Ux.1=0<cr><lf>          Motor Status            ?99.1
        '                          0=Running, 1=overflow, 2=overspeed, 4=overload, 8=In position
        If ((pos = reply.IndexOf("Ux.") >= 0)) Then
            Dim posEq As Integer = reply.IndexOf("="c)
            If (posEq >= 0) Then
                Dim res As Integer = 1
                Int32.TryParse(reply.Substring(posEq + 1), res)
                Dim setColour As Color = Color.Red

                If res = 0 Then
                    setColour = Color.Green
                ElseIf res = 8 Then
                    setColour = SystemColors.Control
                End If

                SetColourPos(setColour, (reply(pos + 3) = "2"c))
                Handled = True
            End If

        End If

        'Px.1=245<cr><lf>        Current Pos             ?96.1
        If (pos = reply.IndexOf("Px.") >= 0) Then
            Dim posEq As Integer = reply.IndexOf("="c)
            If (posEq >= 0) Then
                Dim res As Integer = -999
                Int32.TryParse(reply.Substring((posEq + 1)), res)
                Me.SetTextPos(res.ToString(), (reply(pos + 3) = "2"c))
                Handled = True
            End If

        End If

        'Sx.1=0<cr><lf>          Current Speed           ?97.1
        If (pos = reply.IndexOf("Sx.") >= 0) Then
            Dim posEq As Integer = reply.IndexOf("="c)
            If (posEq >= 0) Then
                Dim res As Integer = -999
                Int32.TryParse(reply.Substring((posEq + 1)), res)

                Handled = True
            End If

        End If

        'Ix.1=0<cr><lf>          Current Acc             ?98.1
        If ((pos = reply.IndexOf("Ix.") >= 0)) Then
            Dim posEq As Integer = reply.IndexOf("="c)
            If (posEq >= 0) Then
                Dim res As Integer = -999
                Int32.TryParse(reply.Substring((posEq + 1)), res)

                Handled = True
            End If

        End If

        'Origin.1=909<cr><lf>    Found and set origin    |.1
        'Origin.2=41<cr><lf>     Found and set origin    |.2
        If (pos = reply.IndexOf("Origin.") >= 0) Then
            Dim posEq As Integer = reply.IndexOf("="c)
            If (posEq >= 0) Then

                Handled = True
            End If

        End If

        'Check for echoed commands
        Select Case (reply.Substring(0, 1))
            Case "?", "(", ")", "|", "^", "A", "P", "S"
                Handled = True
        End Select

        Return Handled
    End Function
    Private Sub OnDataAvailable(ByVal result As IAsyncResult)
        If Not _bDisconnecting Then

            Try
                Dim nRead As Integer = _tcpStream.EndRead(result)

                If nRead > 0 Then
                    _strBuffer += Encoding.ASCII.GetString(_readBuffer, 0, nRead)
                    _logStream.Write(_readBuffer, 0, nRead)
                    Dim [end] As Integer = 0

                    While [end] >= 0 AndAlso Not _bDisconnecting
                        Dim nIgnore As Integer = 0

                        While nIgnore < _strBuffer.Length AndAlso (_strBuffer(nIgnore) = vbCr OrElse _strBuffer(nIgnore) = vbLf)
                            nIgnore += 1
                        End While

                        [end] = _strBuffer.IndexOf(vbCrLf, nIgnore)

                        If [end] >= 0 Then
                            Dim sRx As String = _strBuffer.Substring(nIgnore, [end] + 2)

                            If _strBuffer.Length > [end] + 2 Then
                                _strBuffer = _strBuffer.Substring([end] + 2)
                            Else
                                _strBuffer = ""
                            End If

                            If Not HandleReply(sRx) Then AppendLog("Rx: " & sRx)
                        End If
                    End While
                End If

                If Not _bDisconnecting Then _tcpStream.BeginRead(_readBuffer, 0, 256, New AsyncCallback(AddressOf OnDataAvailable), Nothing)
            Catch __unusedException1__ As Exception
            End Try
        End If
    End Sub


    Private Sub BtnConnect_Click(sender As Object, e As EventArgs) Handles BtnConnect.Click
        If BtnConnect.Text = "Connect" Then

            Try
                _tcpClient = New System.Net.Sockets.TcpClient()
                _tcpClient.Connect("193.240.200.203", 10001)
                _tcpStream = _tcpClient.GetStream()
                _tcpStream.BeginRead(_readBuffer, 0, 256, New AsyncCallback(AddressOf OnDataAvailable), Nothing)
                BtnConnect.Text = "Disconnect"
                _bDisconnecting = False
                EnableButtons(True)
                SendCmd("S.1=" & SettingsForm.hScrollSpeedH.Value.ToString())
                SendCmd("A.1=" & RUN_ACC_H.ToString())
                SendCmd("S.2=" & SettingsForm.hScrollSpeedV.Value.ToString())
                SendCmd("A.2=" & RUN_ACC_V.ToString())
            Catch ex As System.Net.Sockets.SocketException
                MessageBox.Show(ex.Message, "Socket Exception")
            End Try
        Else
            _bDisconnecting = True
            timerQuery.Enabled = False
            _tcpClient.Close()
            _tcpClient = Nothing
            BtnConnect.Text = "Connect"
            EnableButtons(False)
        End If
    End Sub
    Private Sub SendCmd(ByVal cmd As String)

        cmd += vbCrLf
        Dim cmdHok As Boolean = (cmd.IndexOf(".1") >= 0)
        Dim cmdVok As Boolean = (cmd.IndexOf(".2") >= 0)

        If True Then

            Select Case cmd(0)
                Case "|"c

                Case Else
            End Select

            Dim send As Byte() = Encoding.ASCII.GetBytes(cmd)
            _tcpStream.Write(send, 0, send.Length)
            System.Threading.Thread.Sleep(10)
        End If
    End Sub


    Private Sub BtnHome_Click(sender As Object, e As EventArgs) Handles BtnHome.Click
        SendCmd(").1")
        SendCmd("(.1")
        SendCmd("|.1")
        SendCmd(").2")
        SendCmd("(.2")
        SendCmd("|.2")
    End Sub


    Private Sub BtnForword_Click(sender As Object, e As EventArgs) Handles BtnForword.Click
        Dim p As Integer = Int32.Parse(textPosH.Text)
        Dim inc As Integer = Int32.Parse(SettingsForm.textMoveH.Text)
        Dim target As Integer = p + inc
        Dim maxVal As Integer = 0


        If Int32.TryParse(SettingsForm.textMaxPosH.Text, maxVal) Then
            If target > maxVal Then target = maxVal
            SendCmd("P.1=" & target.ToString())
            SendCmd("^.1")
        End If

    End Sub



    Private Sub BtnBackword_Click(sender As Object, e As EventArgs) Handles BtnBackword.Click
        Dim p As Integer = Int32.Parse(textPosH.Text)
        Dim inc As Integer = Int32.Parse(SettingsForm.textMoveH.Text)
        Dim target As Integer = p - inc
        If target < 0 Then target = 0
        SendCmd("P.1=" & target.ToString())
        SendCmd("^.1")
    End Sub

    Private Sub BtnUp_Click(sender As Object, e As EventArgs) Handles BtnUp.Click
        Dim p As Integer = Int32.Parse(textPosV.Text)
        Dim inc As Integer = Int32.Parse(SettingsForm.textMoveV.Text)
        Dim target As Integer = p + inc
        Dim maxVal As Integer = 0

        If Int32.TryParse(SettingsForm.textMaxPosV.Text, maxVal) Then
            If target > maxVal Then target = maxVal
            SendCmd("P.2=" & target.ToString())
            SendCmd("^.2")
        End If
    End Sub

    Private Sub BtnDown_Click(sender As Object, e As EventArgs) Handles BtnDown.Click
        Dim p As Integer = Int32.Parse(textPosV.Text)
        Dim inc As Integer = Int32.Parse(SettingsForm.textMoveV.Text)
        Dim target As Integer = p - inc
        If target < 0 Then target = 0
        SendCmd("P.2=" & target.ToString())
        SendCmd("^.2")
    End Sub
    Private Sub MainMenu_FormClosed(ByVal sender As Object, ByVal e As FormClosedEventArgs)
        _logStream.Close()
    End Sub

    Private Sub HineMotorSetup_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs)
        _bDisconnecting = True

        If BtnConnect.Text = "Disconnect" Then
            BtnConnect_Click(sender, Nothing)
            System.Threading.Thread.Sleep(100)
        End If
    End Sub



    Private Sub EXITToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EXITToolStripMenuItem.Click

    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles TimerQuery.Tick

        SendCmd("?97.1")
        SendCmd("?96.1")
        SendCmd("?97.2")
        SendCmd("?96.2")

    End Sub

    Private Sub BtnStop_Click(sender As Object, e As EventArgs) Handles BtnStop.Click
        SendCmd(").1")
        SendCmd(").2")
    End Sub


    Private Sub BtnStart_Click(sender As Object, e As EventArgs) Handles BtnStart.Click
        SendCmd("(.1")
        SendCmd("(.2")
    End Sub

    Private Sub ExitToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem1.Click
        End

    End Sub

    Private Sub SettingsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SettingsToolStripMenuItem.Click
        SettingsForm.Show()
    End Sub

    Private Sub AppendLog(p1 As String)
        Throw New NotImplementedException
    End Sub



End Class


----------------------------------------------------------------------------------
C# version of the code -

#define HINEMOTORSETUP_LOG_ALL_RX
#define HINEMOTORSETUP_DISABLE_CORNERS

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HineMotorSetup
{
  public partial class HineMotorSetup : Form
  {

    const int JOYSTICK_SIZE = 5;
    const int JOYSTICK_CENTRE = 10;
    const int RUN_ACC_H = 10;
    const int RUN_ACC_V = 10;
    const int JOYSTICK_ACC_H = 1;
    const int JOYSTICK_ACC_V = 1;
    const int RUN_SPEED_H = 2000;
    const int RUN_SPEED_V = 15;

    enum MOVE_DIRECTION
    {
      Stationary,
      StationaryMouseDown,
      MovingBack,
      MovingFwd
    };

    private System.Net.Sockets.TcpClient _tcpClient;
    private System.Net.Sockets.NetworkStream _tcpStream;
    private System.IO.FileStream _logStream;
    private Byte[] _readBuffer;
    private String _strBuffer;
    private MOVE_DIRECTION _movingH;
    private MOVE_DIRECTION _movingV;
    private bool _bDisconnecting;

    public HineMotorSetup()
    {
      _bDisconnecting = true;
      _readBuffer = new Byte[256];
      _logStream = null;
#if (HINEMOTORSETUP_LOG_ALL_RX)
        _logStream = new System.IO.FileStream("RxLog.log", System.IO.FileMode.Append);
#endif

      _strBuffer = "";
      _movingH = MOVE_DIRECTION.Stationary;
      _movingV = MOVE_DIRECTION.Stationary;
      _tcpClient = null;

      InitializeComponent();
      System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
      Text = "Hine Motor Setup v" + assembly.GetName().Version; 
      EnableButtons(false);
      hScrollSpeedH.LargeChange = RUN_SPEED_H / 20;
      hScrollSpeedH.Maximum = RUN_SPEED_H + hScrollSpeedH.LargeChange - 1;
      hScrollSpeedH.Value = RUN_SPEED_H;
      hScrollSpeedH_Scroll(null, null);
      hScrollSpeedV.LargeChange = RUN_SPEED_V / 10;
      hScrollSpeedV.Maximum = RUN_SPEED_V + hScrollSpeedV.LargeChange - 1;
      hScrollSpeedV.Value = RUN_SPEED_V;
      hScrollSpeedV_Scroll(null, null);
    }

    public static DialogResult InputBox(string title, string promptText, ref string value)
    {
      Form form = new Form();
      Label label = new Label();
      TextBox textBox = new TextBox();
      Button buttonOk = new Button();
      Button buttonCancel = new Button();

      form.Text = title;
      label.Text = promptText;
      textBox.Text = value;

      buttonOk.Text = "OK";
      buttonCancel.Text = "Cancel";
      buttonOk.DialogResult = DialogResult.OK;
      buttonCancel.DialogResult = DialogResult.Cancel;

      label.SetBounds(9, 20, 372, 13);
      textBox.SetBounds(12, 36, 372, 20);
      buttonOk.SetBounds(228, 72, 75, 23);
      buttonCancel.SetBounds(309, 72, 75, 23);

      label.AutoSize = true;
      textBox.Anchor = textBox.Anchor | AnchorStyles.Right;
      buttonOk.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
      buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;

      form.ClientSize = new Size(396, 107);
      form.Controls.AddRange(new Control[] { label, textBox, buttonOk, buttonCancel });
      form.ClientSize = new Size(Math.Max(300, label.Right + 10), form.ClientSize.Height);
      form.FormBorderStyle = FormBorderStyle.FixedDialog;
      form.StartPosition = FormStartPosition.CenterScreen;
      form.MinimizeBox = false;
      form.MaximizeBox = false;
      form.AcceptButton = buttonOk;
      form.CancelButton = buttonCancel;

      DialogResult dialogResult = form.ShowDialog();
      value = textBox.Text;
      return dialogResult;
    }

    private void EnableButtons(bool enable)
    {
      btnHome.Enabled = enable;
      btnJogDn.Enabled = enable;
      btnJogUp.Enabled = enable;
      btnJogExtend.Enabled = enable;
      btnJogRetract.Enabled = enable;
      btnSend.Enabled = enable;
      btnStop.Enabled = enable;
      btnEnableMotors.Enabled = enable;
      textPosH.Enabled = enable;
      textPosV.Enabled = enable;
    }

    delegate void SetTextOnlyCallback(string text);
    delegate void SetTextCallback(string text, bool Vertical);
    delegate void SetColourCallback(Color colour, bool Vertical);

    private void AppendLog(string text)
    {
      // InvokeRequired required compares the thread ID of the
      // calling thread to the thread ID of the creating thread.
      // If these threads are different, it returns true.
      if (textLog.InvokeRequired)
      {
        try
        {
          SetTextOnlyCallback d = new SetTextOnlyCallback(AppendLog);
          Invoke(d, new object[] { text });
        }
        catch (Exception)
        {
        }
      }
      else
      {
        textLog.Text += text;
        textLog.Select(textLog.Text.Length, 0);
        textLog.ScrollToCaret();
      }
    }

    private void SetTextOrig(string text, bool Vertical)
    {
      // InvokeRequired required compares the thread ID of the
      // calling thread to the thread ID of the creating thread.
      // If these threads are different, it returns true.
      if (Vertical ? textOrigV.InvokeRequired : textOrigH.InvokeRequired)
      {
        try 
        { 
          SetTextCallback d = new SetTextCallback(SetTextOrig);
          Invoke(d, new object[] { text, Vertical });
        }
        catch (Exception)
        {
        }
      }
      else
      {
        if (Vertical)
          textOrigV.Text = text;
        else
          textOrigH.Text = text;
      }
    }

    private void SetColourPos(Color colour, bool Vertical)
    {
      // InvokeRequired required compares the thread ID of the
      // calling thread to the thread ID of the creating thread.
      // If these threads are different, it returns true.
      if (Vertical ? textPosV.InvokeRequired : textPosH.InvokeRequired)
      {
        try
        { 
          SetColourCallback d = new SetColourCallback(SetColourPos);
          Invoke(d, new object[] { colour, Vertical });
        }
        catch (Exception)
        {
        }
      }
      else
      {
        if (Vertical)
          textPosV.BackColor = colour;
        else
          textPosH.BackColor = colour;
      }
    }

    private void SetTextPos(string text, bool Vertical)
    {
      // InvokeRequired required compares the thread ID of the
      // calling thread to the thread ID of the creating thread.
      // If these threads are different, it returns true.
      if (Vertical ? textPosV.InvokeRequired : textPosH.InvokeRequired)
      {
        try
        {
          SetTextCallback d = new SetTextCallback(SetTextPos);
          Invoke(d, new object[] { text, Vertical });
        }
        catch (Exception)
        {
        }
      }
      else
      {
        if (Vertical)
        {
          textPosV.Text = text;
          if (Int32.Parse(text) >= Int32.Parse(textMaxPosV.Text) * 0.98)
          {
            textMaxPosV.BackColor = Color.Orange;
          }
          else
          {
            textMaxPosV.BackColor = SystemColors.Window;
          }
        }
        else
        {
          textPosH.Text = text;
          if (Int32.Parse(text) >= Int32.Parse(textMaxPosH.Text)*0.98)
          {
            textMaxPosH.BackColor = Color.Orange;
          }
          else
          {
            textMaxPosH.BackColor = SystemColors.Window;
          }
        }
      }
    }

    private void SetTextSpeed(string text, bool Vertical)
    {
      // InvokeRequired required compares the thread ID of the
      // calling thread to the thread ID of the creating thread.
      // If these threads are different, it returns true.
      if (Vertical ? textSpeedV.InvokeRequired : textSpeedH.InvokeRequired)
      {
        try
        {
          SetTextCallback d = new SetTextCallback(SetTextSpeed);
          Invoke(d, new object[] { text, Vertical });
        }
        catch (Exception)
        {
        }
      }
      else
      {
        if (Vertical)
          textSpeedV.Text = text;
        else
          textSpeedH.Text = text;
      }
    }

    private void SetTextAccel(string text, bool Vertical)
    {
      // InvokeRequired required compares the thread ID of the
      // calling thread to the thread ID of the creating thread.
      // If these threads are different, it returns true.
      if (Vertical ? textAccelV.InvokeRequired : textAccelH.InvokeRequired)
      {
        try
        {
          SetTextCallback d = new SetTextCallback(SetTextAccel);
          Invoke(d, new object[] { text, Vertical });
        }
        catch (Exception)
        {
        }
      }
      else
      {
        if (Vertical)
          textAccelV.Text = text;
        else
          textAccelH.Text = text;
      }
    }

    private bool HandleReply(String reply)
    {
      bool Handled = false;
      int pos = 0;
      bool isV = reply.IndexOf(".2") >= 0;

      //Ux.1=8<cr><lf>          Movement complete       any movement cmd
      //Ux.2=8<cr><lf>          Movement complete       any movement cmd
      //Ux.1=0<cr><lf>          Motor Status            ?99.1
      //                          0=Running, 1=overflow, 2=overspeed, 4=overload, 8=In position
      if ((pos = reply.IndexOf("Ux.")) >= 0)
      {
        int posEq = reply.IndexOf('=');
        if (posEq >= 0)
        {
          int res = 1;
          Int32.TryParse(reply.Substring(posEq + 1), out res);
          Color setColour = Color.Red;
          if (res == 0)
            setColour = Color.Green;
          else if (res == 8)
          {
            setColour = SystemColors.Control;
          }

          SetColourPos(setColour, (reply[pos + 3] == '2'));
          Handled = true;
        }
      }

      //Px.1=245<cr><lf>        Current Pos             ?96.1
      if ((pos = reply.IndexOf("Px.")) >= 0)
      {
        int posEq = reply.IndexOf('=');
        if (posEq >= 0)
        {
          int res = -999;
          Int32.TryParse(reply.Substring(posEq + 1), out res);

          SetTextPos(res.ToString(), (reply[pos + 3] == '2'));
          Handled = true;
        }
      }

      //Sx.1=0<cr><lf>          Current Speed           ?97.1
      if ((pos = reply.IndexOf("Sx.")) >= 0)
      {
        int posEq = reply.IndexOf('=');
        if (posEq >= 0)
        {
          int res = -999;
          Int32.TryParse(reply.Substring(posEq + 1), out res);

          SetTextSpeed(res.ToString(), (reply[pos + 3] == '2'));
          Handled = true;
        }
      }

      //Ix.1=0<cr><lf>          Current Acc             ?98.1
      if ((pos = reply.IndexOf("Ix.")) >= 0)
      {
        int posEq = reply.IndexOf('=');
        if (posEq >= 0)
        {
          int res = -999;
          Int32.TryParse(reply.Substring(posEq + 1), out res);

          SetTextAccel(res.ToString(), (reply[pos + 3] == '2'));
          Handled = true;
        }
      }


      //Origin.1=909<cr><lf>    Found and set origin    |.1
      //Origin.2=41<cr><lf>     Found and set origin    |.2
      else if ((pos = reply.IndexOf("Origin.")) >= 0)
      {
        int posEq = reply.IndexOf('=');
        if (posEq >= 0)
        {
          SetTextOrig(reply.Substring(posEq + 1), (reply[pos + 7] == '2'));
          Handled = true;
        }
      }

      //Check for echoed commands
      switch (reply.Substring(0,1))
      {
        case "?":
        case "(":
        case ")":
        case "|":
        case "^":
        case "A":
        case "P":
        case "S":
        Handled = true;
        break;
      }
      return Handled;
    }
    
    private void OnDataAvailable(IAsyncResult result)
    {
      if (!_bDisconnecting)
      {
        try
        {
          int nRead = _tcpStream.EndRead(result);

          if (nRead > 0)
          {
            _strBuffer += Encoding.ASCII.GetString(_readBuffer, 0, nRead);
#if (HINEMOTORSETUP_LOG_ALL_RX)
            _logStream.Write(_readBuffer, 0, nRead);
#endif

            int end = 0;
            while (end >= 0 && !_bDisconnecting)
            {
              //Ignore leading /r/n
              int nIgnore = 0;
              while (nIgnore < _strBuffer.Length && (_strBuffer[nIgnore] == '\r' || _strBuffer[nIgnore] == '\n'))
                nIgnore++;
              end = _strBuffer.IndexOf("\r\n", nIgnore);
              if (end >= 0)
              {
                String sRx = _strBuffer.Substring(nIgnore, end + 2);
                if (_strBuffer.Length > end + 2)
                  _strBuffer = _strBuffer.Substring(end + 2);
                else
                  _strBuffer = "";

                if (!HandleReply(sRx))
                  AppendLog("Rx: " + sRx);
              }
            }
          }
          //Setup the Async Read again for the next data received.
          if (!_bDisconnecting)
            _tcpStream.BeginRead(_readBuffer, 0, 256, new AsyncCallback(OnDataAvailable), null);
        }
        catch (Exception)
        {

        }
      }
    }

    private void btnConnect_Click(object sender, EventArgs e)
    {
      if (btnConnect.Text == "Connect")
      {
        try
        {
          _tcpClient = new System.Net.Sockets.TcpClient();
          _tcpClient.Connect("193.240.200.203", 10001);
          _tcpStream = _tcpClient.GetStream();
          _tcpStream.BeginRead(_readBuffer, 0, 256, new AsyncCallback(OnDataAvailable), null);
          btnConnect.Text = "Disconnect";
          EnableButtons(true);
          timerQuery.Enabled = true;
          _bDisconnecting = false;

          //Set Dynamic Command speed and acceleration
          SendCmd("S.1=" + hScrollSpeedH.Value.ToString());
          SendCmd("A.1=" + RUN_ACC_H.ToString());
          SendCmd("S.2=" + hScrollSpeedV.Value.ToString());
          SendCmd("A.2=" + RUN_ACC_V.ToString());
        }
        catch (System.Net.Sockets.SocketException ex)
        {
          MessageBox.Show(ex.Message, "Socket Exception");
        }
      }
      else
      {
        _bDisconnecting = true;
        timerQuery.Enabled = false;
        EnableButtons(false);
        _tcpClient.Close();
        _tcpClient = null;
        btnConnect.Text = "Connect";
      }
    }

    private void SendCmd(String cmd)
    {
      if (!_bDisconnecting)
      {
        cmd += "\r\n";
        bool cmdHok = (cmd.IndexOf(".1") >= 0);
        bool cmdVok = (cmd.IndexOf(".2") >= 0);
        {
          switch (cmd[0])
          {
            case '|':
              if (cmdHok)
              {
                SetColourPos(Color.Orange, cmdVok);
              }
              else if (cmdVok)
              {
                SetColourPos(Color.Orange, cmdVok);
              }
              break;
            default:
              break;
          }

          byte[] send = Encoding.ASCII.GetBytes(cmd);
          _tcpStream.Write(send, 0, send.Length);
          System.Threading.Thread.Sleep(10); //Seems to stop overlapping replies!
        }
      }
    }

    private void btnHome_Click(object sender, EventArgs e)
    {
      SendCmd(").1");
      SendCmd("(.1");
      SendCmd("|.1");
      SendCmd(").2");
      SendCmd("(.2");
      SendCmd("|.2");
    }

    private void btnSend_Click(object sender, EventArgs e)
    {
      SendCmd(textSend.Text);
    }

    private void timerQuery_Tick(object sender, EventArgs e)
    {
      SendCmd("?99.1"); //Motor status
      SendCmd("?98.1"); //Motor acceleration
      SendCmd("?97.1"); //Motor speed
      SendCmd("?96.1"); //Motor position
      SendCmd("?99.2");
      SendCmd("?98.2");
      SendCmd("?97.2");
      SendCmd("?96.2");

    }

    private void btnEnableMotors_Click(object sender, EventArgs e)
    {
      SendCmd("(.1");
      SendCmd("(.2");
    }

    private void btnStop_Click(object sender, EventArgs e)
    {
      SendCmd(").1");
      SendCmd(").2");
    }

    private void btnJogExtend_Click(object sender, EventArgs e)
    {
      int p = Int32.Parse(textPosH.Text);
      int inc = Int32.Parse(textJogH.Text);
      int target = p + inc;
      int maxVal = 0;
      if (Int32.TryParse(textMaxPosH.Text, out maxVal))
      {
        if (target > maxVal)
          target = maxVal;
        SendCmd("P.1=" + target.ToString());
        SendCmd("^.1");
      }
    }

    private void btnJogRetract_Click(object sender, EventArgs e)
    {
      int p = Int32.Parse(textPosH.Text);
      int inc = Int32.Parse(textJogH.Text);
      int target = p - inc;
      if (target < 0) 
        target = 0;
      SendCmd("P.1=" + target.ToString());
      SendCmd("^.1");
    }

    private void btnJogUp_Click(object sender, EventArgs e)
    {
      int p = Int32.Parse(textPosV.Text);
      int inc = Int32.Parse(textJogV.Text);
      int target = p + inc;
      int maxVal = 0;
      if (Int32.TryParse(textMaxPosV.Text, out maxVal))
      {
        if (target > maxVal)
          target = maxVal;
        SendCmd("P.2=" + target.ToString());
        SendCmd("^.2");
      }
    }

    private void btnJogDn_Click(object sender, EventArgs e)
    {
      int p = Int32.Parse(textPosV.Text);
      int inc = Int32.Parse(textJogV.Text);
      int target = p - inc;
      if (target < 0) 
        target = 0;
      SendCmd("P.2=" + target.ToString());
      SendCmd("^.2");
    }

    private void imgJoystick_Paint(object sender, PaintEventArgs e)
    {
      e.Graphics.DrawRectangle(Pens.Red, imgJoystick.Width / 2 - JOYSTICK_CENTRE, imgJoystick.Height / 2 - JOYSTICK_CENTRE, JOYSTICK_CENTRE * 2, JOYSTICK_CENTRE*2);

      int xpos = imgJoystick.Width / 2 - JOYSTICK_SIZE;
      if (_movingH == MOVE_DIRECTION.MovingBack)
        xpos = 0;
      else if (_movingH == MOVE_DIRECTION.MovingFwd)
        xpos = imgJoystick.Width - JOYSTICK_SIZE * 2 - 2;

      int ypos = imgJoystick.Height / 2 - JOYSTICK_SIZE;
      if (_movingV == MOVE_DIRECTION.MovingBack)
        ypos = imgJoystick.Height - JOYSTICK_SIZE * 2 - 2;
      else if (_movingV == MOVE_DIRECTION.MovingFwd)
        ypos = 0;

      e.Graphics.FillEllipse(Brushes.Black, xpos, ypos, JOYSTICK_SIZE * 2, JOYSTICK_SIZE * 2);
    }

    private void imgJoystick_MouseDown(object sender, MouseEventArgs e)
    {
      _movingH = MOVE_DIRECTION.StationaryMouseDown;
      _movingV = MOVE_DIRECTION.StationaryMouseDown;
      SendCmd("S.1=" + RUN_SPEED_H.ToString());
      SendCmd("S.2=" + RUN_SPEED_V.ToString());
      SendCmd("A.1=" + JOYSTICK_ACC_H.ToString());
      SendCmd("A.2=" + JOYSTICK_ACC_V.ToString());
      imgJoystick_MouseMove(sender, e);
    }

    private void imgJoystick_MouseUp(object sender, MouseEventArgs e)
    {
      _movingH = MOVE_DIRECTION.Stationary;
      _movingV = MOVE_DIRECTION.Stationary;
      SendCmd(").1");
      SendCmd("(.1");
      SendCmd(").2");
      SendCmd("(.2");
      SendCmd("S.1=" + hScrollSpeedH.Value.ToString());
      SendCmd("S.2=" + hScrollSpeedV.Value.ToString());
      SendCmd("A.1=" + RUN_ACC_H.ToString());
      SendCmd("A.2=" + RUN_ACC_V.ToString());
      imgJoystick.Refresh();
    }

    private void imgJoystick_MouseMove(object sender, MouseEventArgs e)
    {
      if (_movingH != MOVE_DIRECTION.Stationary)
      {
        MOVE_DIRECTION prevH = _movingH;
        int mid = imgJoystick.Width / 2;
        if (e.X < mid - JOYSTICK_CENTRE
        #if HINEMOTORSETUP_DISABLE_CORNERS
         && _movingV == MOVE_DIRECTION.StationaryMouseDown
        #endif
        )
        {
          _movingH = MOVE_DIRECTION.MovingBack;
        }
        else if (e.X > mid + JOYSTICK_CENTRE
        #if HINEMOTORSETUP_DISABLE_CORNERS
         && _movingV == MOVE_DIRECTION.StationaryMouseDown
        #endif
        )
        {
          _movingH = MOVE_DIRECTION.MovingFwd;
        }
        else
        {
          _movingH = MOVE_DIRECTION.StationaryMouseDown;
        }

        if (prevH != _movingH)
        {
          if (_movingH == MOVE_DIRECTION.MovingFwd)
          {
            SendCmd("P.1=" + textMaxPosH.Text);
            SendCmd("^.1");
          }
          else if (_movingH == MOVE_DIRECTION.MovingBack)
          {
            SendCmd("P.1=0");
            SendCmd("^.1");
          }
          else 
          {
            SendCmd(").1");
            SendCmd("(.1");
          }
        }
      }
      if (_movingV != MOVE_DIRECTION.Stationary)
      {
        MOVE_DIRECTION prevV = _movingV;
        int mid = imgJoystick.Height / 2;
        if (e.Y > mid + JOYSTICK_CENTRE
        #if HINEMOTORSETUP_DISABLE_CORNERS
         && _movingH == MOVE_DIRECTION.StationaryMouseDown
        #endif
        )
        {
          _movingV = MOVE_DIRECTION.MovingBack;
        }
        else if (e.Y < mid - JOYSTICK_CENTRE
        #if HINEMOTORSETUP_DISABLE_CORNERS
         && _movingH == MOVE_DIRECTION.StationaryMouseDown
        #endif
        )
        {
          _movingV = MOVE_DIRECTION.MovingFwd;
        }
        else
        {
          _movingV = MOVE_DIRECTION.StationaryMouseDown;
        }

        if (prevV != _movingV)
        {
          if (_movingV == MOVE_DIRECTION.MovingFwd)
          {
            SendCmd("P.2=" + textMaxPosV.Text);
            SendCmd("^.2");
          }
          else if (_movingV == MOVE_DIRECTION.MovingBack)
          {
            SendCmd("P.2=0");
            SendCmd("^.2");
          }
          else
          {
            SendCmd(").2");
            SendCmd("(.2");
          }
        }
      }
      imgJoystick.Refresh();
    }

    private void textPosH_Click(object sender, EventArgs e)
    {
      String rtn = "";
      if (InputBox("Move Horizontal", "Enter target value:", ref rtn) == DialogResult.OK)
      {
        int val = 0;
        int maxVal = 0;
        if (Int32.TryParse(rtn, out val) && Int32.TryParse(textMaxPosH.Text, out maxVal))
        {
          if (val > maxVal)
            val = maxVal;
          SendCmd("P.1=" + val.ToString());
          SendCmd("^.1");
        }
      }
    }

    private void textPosV_Click(object sender, EventArgs e)
    {
      String rtn = "";
      if (InputBox("Move Vertical", "Enter target value:", ref rtn) == DialogResult.OK)
      {
        int val = 0;
        int maxVal = 0;
        if (Int32.TryParse(rtn, out val) && Int32.TryParse(textMaxPosV.Text, out maxVal))
        {
          if (val > maxVal)
            val = maxVal;
          SendCmd("P.2=" + val.ToString());
          SendCmd("^.2");
        }
      }
    }

    private void hScrollSpeedH_Scroll(object sender, ScrollEventArgs e)
    {
      labelSetSpeedH.Text = "Set Speed = " + hScrollSpeedH.Value.ToString();
      SendCmd("S.1=" + hScrollSpeedH.Value.ToString());
    }

    private void hScrollSpeedV_Scroll(object sender, ScrollEventArgs e)
    {
      labelSetSpeedV.Text = "Set Speed = " + hScrollSpeedV.Value.ToString();
      SendCmd("S.2=" + hScrollSpeedV.Value.ToString());
    }

    private void HineMotorSetup_Deactivate(object sender, EventArgs e)
    {
      imgJoystick_MouseUp(sender, null);
    }

    private void HineMotorSetup_FormClosed(object sender, FormClosedEventArgs e)
    {
#if (HINEMOTORSETUP_LOG_ALL_RX)
        _logStream.Close();
#endif
    }

    private void HineMotorSetup_FormClosing(object sender, FormClosingEventArgs e)
    {
      _bDisconnecting = true;
      if (btnConnect.Text == "Disconnect")
      {
        btnConnect_Click(sender, null);
        System.Threading.Thread.Sleep(100);
      }
    }

    private void HineMotorSetup_Load(object sender, EventArgs e)
    {

    }

   
    private void textOrigH_TextChanged(object sender, EventArgs e)
    {

    }

    private void imgJoystick_Click(object sender, EventArgs e)
    {

    }

    private void textMaxPosH_TextChanged(object sender, EventArgs e)
    {

    }

  }
}

解决方案

The problem of the not updated vertical value is sourced by a wrong C# to VB conversion for the line:

// C#
SetTextPos(res.ToString(), (reply[pos + 3] == '2'));

The second parameter of SetTextPos is a bool which is determined by comparing two characters. With VB you can use the Char.Equals method to get the required Boolean result to be passed:

' VB
' Px.1 = horizontal, Px.2 = vertical
Me.SetTextPos(res.ToString(), "2"c.Equals(reply(pos + 3)))


[EDIT]
When the robot always sends both positions after a movement, that should also solve your problem with the changing horizontal value. With your code, the robots sends the horizontal value (100) first and is displayed. When it sends the vertical value (8) afterwards that will be wrongly put into the horizontal text box staying there until the next pair of postions is send.
[/EDIT]


Quote:

How do I read position of the robot arm? Help


Since we don't have the robot, we have no way to run this code, you are the only one able to do it.
-----
Your code do not behave the way you expect, or you don't understand why !

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

The downside of this solution:
- It is a DIY, you are the one tracking the problem and finding its roots, which lead to the solution.
The upside of this solution:
- It is also a great learning tool because it show you reality and you can see which expectation match reality.

secondary effects
- Your will be proud of finding bugs yourself.
- Your learning skills will improve.

You should find pretty quickly what is wrong.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]
Visual Basic / Visual Studio Video Tutorial - Basic Debugging - YouTube[^]
Visual Basic .NET programming for Beginners - Breakpoints and Debugging Tools[^]
The debugger is here to only show you what your code is doing and your task is to compare with what it should do.


这篇关于如何读取机器人手臂的位置?救命的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆