I'm facing some problems when receiving data from Mettler Toledo (IND560) scale device using C#.
When I send "taring" command (T) to device, it's working properly but there is nothing in response. The BytesToRead is always empty and the "while" is in infinite loop.
When I send "send stable weight value" command (S), I face the same infinite loop issue. I guess the command is running properly but not responding.
Here is the code:
private decimal? BalancaIND560(string porta, string comando) {
SerialPort SerialObj = new SerialPort(porta);
if (!SerialObj.IsOpen)
SerialObj.Open();
string retorno = "";
try {
SerialObj.BaudRate = 9600;
SerialObj.Parity = Parity.Even;
SerialObj.DataBits = 7;
SerialObj.StopBits = StopBits.One;
SerialObj.Handshake = Handshake.XOnXOff;
SerialObj.DiscardInBuffer();
SerialObj.DiscardOutBuffer();
SerialObj.Write(comando);
while ((SerialObj.BytesToRead == 0))
Application.DoEvents();
Thread.Sleep(500);
retorno = SerialObj.ReadExisting();
SerialObj.DiscardInBuffer();
SerialObj.DiscardOutBuffer();
} finally {
try { SerialObj.Close(); } catch { }
}
decimal? resultado = null;
try {
string[] aux = retorno.Split(' '); //"S S 100.52 kg"
StringBuilder sb = new StringBuilder();
for (int i = 0; i < aux.Length; i++)
sb.Append(String.Format("aux[{0}]: {1}" + Environment.NewLine, i, aux[i]));
MessageBox.Show(sb.ToString());
decimal peso = 0.0M;
if (!Decimal.TryParse(aux[6].Trim(), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out peso))
Decimal.TryParse(aux[7].Trim(), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out peso);
resultado = peso;
} catch { }
return resultado;
}
// Sending command
try {
decimal? peso = BalancaIND560("COM1", "S");
if (peso.HasValue)
MessageBox.Show(String.Format("Peso: {0}", peso.Value));
else
MessageBox.Show("Peso não foi encontrado", "ATENÇÃO", MessageBoxButtons.OK, MessageBoxIcon.Warning);
} catch {
MessageBox.Show("Erro ao executar comando", "ERRO", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
I found the solution! I just had to change a scale configuration and it's WORKING!!! If someone face the same problem, just change
COM
configuration (Configuration > Comunication > Conections
) toSICS
in the device and my code is working wonderfully!! Tks All!