-1

I am displaying the weight from a weighing scale on into a TextBox using C#/.NET.

This weighing scale is linked to my computer thanks to a serial port connection.

To achieve this, I referred to this post.

My problem :

When I create a new serial port connection I need to declare some constants before that :

_serialPort = new SerialPort(portName, BaudRate, Parity.None, DataBits, StopBits.One);

Here are the constants I need to declare :

private const int BaudRate = 9600;
private const int DataBits = 8;

But BaudRate and DataBits values depend on the weighing scale configuration. So everytime I change the weighing scale, the weights are not well displayed anymore.

My question :

How can I automatically detect the weighing scale configuration in order to well display the weights without manually changing the constants' values ?

RyanU
  • 128
  • 1
  • 8
  • You may find your answer [here](https://stackoverflow.com/questions/45647659/how-to-detect-baud-rate-from-data-in-serial-port). Hope this helps – Rex Aug 24 '17 at 13:31
  • I didn't find an answer there, but thanks for your help. – RyanU Aug 24 '17 at 13:39

2 Answers2

1

As far as I know, there is no provided way to detect SerialPort BaudRate and DataBits from the endpoint you're trying to communicate with. You likely have better providing user with SerialPort options choice on UI.

If you REALLY want to auto detect, erm... A random crazy idea : If you're somewhat aware of the data format (for example, always a float within a string such as "56.12") used by your scale, try this : Test every single possible baudrate and databits combinaison in your SerialPort until the data your read on SerialPort have the expected format (with Regex or Parse, maybe ?). This might take a bit of time but this is a one time operation, so this could be what you need.

Note : Use preferably ReadByte or ReadExisting, as ReadLine will not work until you get a newline (which will happen quite... randomly on wrong baudrate/databits).

Kinxil
  • 306
  • 2
  • 11
1

How can I automatically detect the weighing scale configuration ... ?

You can't, because there is no reliable software technique to derive baudrate and frame parameters from a live serial link.
That's a reason why serial ports have disappeared from PCs, where user-friendly interfaces are expected.
The one scheme I've seen for auto-detection of the baudrate depended on the remote unit to transmit a stream of a single, known character.

A solution to your dilemma would be to manually configure each device to a common baudrate and frame configuration.
Then your program would simply always use that one serial-port configuration.
Devices will have a default serial-port configuration, but for most it is not fixed and can be reconfigured. Older devices used to have DIP switches for this purpose, but low-cost LCD screens and NV memory is the modern interface and storage method.

sawdust
  • 16,103
  • 3
  • 40
  • 50