3

I am working on a program that process data from a scale. The Scale is connected via USB serial Port. I am using the code from this Question: How to display weight from weighing scale into a textbox via serial port RS-232 or usb converter?. So the most important part is working. I get the weight from the scale as a string.

My problem is, when the scale is sending the weight values (10/s) to the computer I am getting the following values for example:

13,0g; 13,0g; 12,9g; ,8g; 12,7g; 2,6g; 12,5g; 12,4g; ,3g; 2,2g; 12,1g;

You can see, some of the values are corrupted, sometimes the first character is missing, or sometimes the first 2 characters... When I try to read the values by using an other program from the scale manufacturer, its working fine, all values are correct.

So what is the problem?

I tried different baud rates and other settings, nothing helped. Hope someone can help me.

Here is the Code I use to read the data from serial port from the linked page.

using System;
using System.IO.Ports;          //<-- necessary to use "SerialPort"
using System.Windows.Forms;

namespace ComPortTests
{
    public partial class Form1 : Form
    {
        private SerialPort _serialPort;         //<-- declares a SerialPort Variable to be used throughout the form
        private const int BaudRate = 9600;      //<-- BaudRate Constant. 9600 seems to be the scale-units default value
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string[] portNames = SerialPort.GetPortNames();     //<-- Reads all available comPorts
            foreach (var portName in portNames)
            {
                comboBox1.Items.Add(portName);                  //<-- Adds Ports to combobox
            }
            comboBox1.SelectedIndex = 0;                        //<-- Selects first entry (convenience purposes)
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //<-- This block ensures that no exceptions happen
            if(_serialPort != null && _serialPort.IsOpen)
                _serialPort.Close();
            if (_serialPort != null)
                _serialPort.Dispose();
            //<-- End of Block

            _serialPort = new SerialPort(comboBox1.Text, BaudRate, Parity.None, 8, StopBits.One);       //<-- Creates new SerialPort using the name selected in the combobox
            _serialPort.DataReceived += SerialPortOnDataReceived;       //<-- this event happens everytime when new data is received by the ComPort
            _serialPort.Open();     //<-- make the comport listen
            textBox1.Text = "Listening on " + _serialPort.PortName + "...\r\n";
        }

        private delegate void Closure();
        private void SerialPortOnDataReceived(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs)
        {
            if (InvokeRequired)     //<-- Makes sure the function is invoked to work properly in the UI-Thread
                BeginInvoke(new Closure(() => { SerialPortOnDataReceived(sender, serialDataReceivedEventArgs); }));     //<-- Function invokes itself
            else
            {
                int dataLength = _serialPort.BytesToRead;
                byte[] data = new byte[dataLength];
                int nbrDataRead = _serialPort.Read(data, 0, dataLength);
                if (nbrDataRead == 0)
                    return;
                string str = System.Text.Encoding.UTF8.GetString(data);
                textBox1.Text = str.ToString();
            }
        }
}
Community
  • 1
  • 1
Sardar Agabejli
  • 423
  • 8
  • 32
  • Can you describe how you get from this code to the semicolon-delimited list in your question? One likely cause of missing data at the beginning of a 'message' is that you read some of the data for the 'next' message as part of a single read, but end up discarding it somehow. This would cause the next read to be missing some of its initial characters. – Dan Bryant Mar 22 '17 at 16:24
  • The values were shown in the textBox one after an other... – Sardar Agabejli Mar 22 '17 at 16:28
  • "This would cause the next read to be missing some of its initial characters" So what do I have to do to prevent this? Using stopbits? parity? Flow control? – Sardar Agabejli Mar 22 '17 at 16:30
  • 3
    You'd have to store the data you're discarding now. Look for a semi-colon in `str` and save everything after it to prepend to the next read. – itsme86 Mar 22 '17 at 16:33
  • OK, I have read out "str" String into a text file. When you take a look at it, you can see that sometimes the line breaks too early, so that some single values are corrupted. what could cause this problem?!?! – Sardar Agabejli Mar 22 '17 at 16:55
  • 2
    What line break? This is the first time a line break has been mentioned anywhere in this question. – itsme86 Mar 22 '17 at 17:15
  • I mean the line break when I write "str" String into a textfile on every new str. Value... – Sardar Agabejli Mar 22 '17 at 17:32

1 Answers1

2

I just had to add the following lines to buffer the values in a cache file.

Now it works fine! Thanks at all

        File.AppendAllText("buffer1.txt", str);

        string strnew = File.ReadLines("buffer1.txt").Last();

        textBox5.Text = strnew;
Sardar Agabejli
  • 423
  • 8
  • 32