V
V
Vasya Borisevich2018-12-26 09:12:12
C++ / C#
Vasya Borisevich, 2018-12-26 09:12:12

How to solve serial port data conversion error?

I receive data from the COM port. The value comes from 0 to 100.
When I try to convert to int, an error pops up (screen is attached).
The code itself:

string inpSerial = serialPort1.ReadExisting();
label1.Text = inpSerial;
int numm = int.Parse(inpSerial);
progressBar1.Value = numm;

Error:
5c231b218654c388104367.png
If you try to get through serialPort1.ReadLine();, and not through serialPort1.ReadExisting();, then the error does not appear, but this option does not suit me because performance drops.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Satisfied IT, 2018-12-26
@ki11k4

What happens inpSerialwhen an error occurs? Obviously not a number.

bool successfullyParsed = int.TryParse(inpSerial, out num);
if (successfullyParsed){
    // ...
}

where num is a parsed number, in case of an error successfullyParsed will contain false
https://docs.microsoft.com/en-us/dotnet/api/system...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question