0
Guys, I’m trying to read data from a serial port in c#, but along with the data is being returned too "junk", which makes it impossible to convert the string to integer. Is there any way to make me not lose as much data?
private void SerialCOM_DataReceived(object sender, SerialDataReceivedEventArgs e) //evento datareceived da portaserial atualizado por um timer com intervalo de 3ms
{
if (SerialCOM.IsOpen)
{
SerialPort sData = (SerialPort)sender;
{
sData.DiscardInBuffer();
int data;
if (sData.BytesToRead > 0) RxString += sData.ReadExisting();
var teste = RxString.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
data = Convert.ToInt32(teste[contador]);
}
}
With this code I have in the "test[]" array several integer values in string format, but when I try to convert these numbers to integer it shows the following message: "The input string was not in an incorrect format.". I tried using Tryparse for conversion but lost a lot of data, which cannot happen in my application. Could anyone help me with this problem?
EDIT:
//supondo que RxString seja
RxString = "1234 456 789 1341 1334";
//então teste[] será
teste[0] = 1234
teste[1] = 456
teste[2] = 789
teste[3] = 1341
teste[4] = 1334
The correct would be this, which would be easy to convert, but sometimes comes empty information or trash in the string "Rxstring", which causes error at the time of conversion.
Can you put in your question an example of the information you receive from the door? Basically the content of
teste[]
.– João Martins
yes, just a moment, I’ll update friend.
– Felipe Mateus
Says using the
TryParse
loses a lot of data as well?– João Martins
Since Tryparse returns false when conversion is not possible and true when completed, I can only use the data that has been converted. Those that are not converted due to incorrect format I lose.
– Felipe Mateus
In my application if I lose data I will be compromising another part of the program.
– Felipe Mateus
Right, but if the
TryParse
cannot convert something into number, so it is because thestring
that came is not a valid number, certain?– João Martins
that same friend
– Felipe Mateus
Let’s go continue this discussion in chat.
– João Martins
Lower the baud rate and make sure it improves.
– Marcelo Shiniti Uchimura
Out of curiosity: his Arduino plate has the drawing of the map of Italy, on the back of the plate?
– Marcelo Shiniti Uchimura