Visual Studio windows form application C# serial communication receive data? - c#

I need a code that will receive serial data from arduino and display them in text boxes .
I am receiving int type data separated by commas .
Arduino serial data sample : 250,389,123,232,255,536,366,455,...
I need first six data to be displayed in six separate text boxes and then the consecutive data must replace the already existing values in those text boxes.
I tried several times but everything went in vain. Some one help me.

I assume you're using System.IO.Ports namespace and SerialPort class for communication. I also hope that BaudRate and other communication settings are as expected by the device.
If yes, then further if you receive the data repeatedly, you may capture it by using ReadTo method and giving it a comma as parameter. Such reading loop may look like this:
while(true) // replace it with some wiser condition
{
string textRead = serialPort.ReadTo(",");
// do the rest here
}
Now, you may also want to capture some larger amounts of data at once. Of course you can (say, capture 100 characters), but then you should:
- split the string with comma;
- leave the last item of string array (which will be the result of splitting method) and insert at 0 position of next received pack of characters;
- repeat those steps in loop like above.
Now, to the TextBox'es. If there are N of them and we take the first capturing method into account, you may do it like this:
TextBox[] tboxes = new TextBox[N]; // your number is 6, I know
int boxIndex = 0;
while(true) // again, use a reasonable condition
{
string textRead = serialPort.ReadTo(",");
tboxes[boxIndex].Text = textRead.Trim(',');
if(++boxIndex >= tboxes.Length)
boxIndex = 0;
}
This should do the job.

Related

correct way to parse serial port data?

I'm testing out a program right now that is supposed to receive data from a serial port and parse it, and continually update certain variables tied to that parsed data. I'm having trouble with the actual parsing itself.
The data string output of the port I'm using is: 8 data bits, 1 start bit, 1 stop bit, and no parity. A message starts with the colon symbol : and ends with . An example - : 3.00 20.45 2355 1000 554
First question: Is there any method for setting the start bit? I know there's a .StopBits which I have equal to StopBits.One, but I haven't found anything for a start bit.
In regards to the parsing-
In the code method below:
serial.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(Receive);
private void Receive(object sender, SerialDataReceivedEventArgs e)
{
// Collecting the characters received to our 'buffer' (string).
received_Data = serial.ReadExisting();
}
Would the best way be to set up a string array = received_Data.Split, then use a for loop to go through each "split" and assign it to the correct variable? I've never worked with ports before so this is all new to me. After looking around there seems to be several ways to do this, not sure what the best way would be though.

Limit Event Handler

Apologies if my 'lingo' doesn't make sense... I'm fairly new to this and coding!
I am working on a project which involves a RFID reader and a Bluetooth module communicating with a C# windows form.
The com port event handler sends the RFID tag's unique ID continuously. Is there a way for it to be sent just once?
Is there a way for the program to just receive the ID once, so it can be processed; as opposed to receiving the ID numerous times.
Thanks in advance! :)
My code so far is as follows.
I have the serial port open from somewhere else
private void port_DataRecieved(object sender, System.IO.Ports.SerialDataRecievedEventArgs e)
{
string data = serialPort.ReadExisting(); // read what came from the RFID reader
if (data.Length > 9) // check if the string if bigger than 9 characters
{
CODE = data.Substring(0, 9); // if string is bigger than 9 characters trim the ending characters until it is only 9 long
}
else
{
CODE = data; // if less that 9 characters use however many it gets
}
}
Don't use ReadExisting. Instead check whether there are 9 bytes yet.
If not, return immediately.
If yes, read only 9 and leave the others for the next event.
You probably should have some resynchronization logic also.
Also, received data needs to be in a byte[], not a string. The Microsoft-provided serial port class always leads people to use the wrong approach.

Creating an Integer Format?

I'm venturing into networking using C# and I'm trying to create a clean way to send my packets, right now though I'm not going to worry with all of the Packets enclosed in special characters stuff that I've been reading about, instead the packet is three digit number dedicated to the front of the data passed to the client. For example, a data string may be the following.
LoginPacket is packet 000.
LoginPacket Data would be "000Username~Password"
I've tried to clean this up, so I could just write things in a cleaner manner, and try something like this
SendPacket(000, new string { "data", "parameters" });
However, sending the integer 000 is instantly converted to zero.
Is there a way around this, or would I be better off storing it all in a string, such as
SendPacket(new string { "000", "data", "params" } );
When you convert the number to text you need to specify the number of digits. The number 000 and 0 are both zero. However the string "000" and "0" are different strings.
Use
n.ToString("000");
To ensure you get three digits.
I would suggest you go with a Command Type followed by a Length followed by the Payload
Then your payloads can be of a similar structure.. so the login command (0) would use a structure that began with a length byte followed by username followed by a second length byte and finally followed by a password.
For example:
0155Dan-o8password
Remember that this all comes over the wire as a byte array.. so you read the first 4 bytes (Int32, Command Type)
Then read the next Int32 to figure out the length of the payload.. that's how many bytes you will read in your third read.
Now that you know the Command is login you can implement login-specific reading.
In addition I would suggest you create some extension methods to make this easier.
like: Stream.ReadByte, Stream.ReadInt32, Stream.ReadInt64, Stream.ReadString(length)
Then some application-specific extensions.. like Stream.ReadLogin

How to start 2 times winform and read different ID`s from same file in c#

first of all I want to apologize about Title.
I have one winform which make post requests reading from text file line by line through 1-200. I want to put one textbox on form and when I run second time to write in this textbox from which line to start reading.
For example:
I run my app and start read and post from 1-200.
Then I start second time app and put in textbox 100 and start reading same file from line 100-200.
You have few lines, so you can use this code.
It's not the best, but it's easy
int skip_count = Int32.Parse(TextBox1.Text) - 1;
string[] lines = File.ReadAllLines(your_file_path)
.Skip(skip_count)
.Take(200 - skip_count)
.ToArray();
Note that you MUST check textbox input... mine is just an easy example...
UPDATED after OP comment:
int skip_count;
if (!Int32.TryParse(TextBox1.Text, out skip_count))
skip_count = 0;
string[] lines = File.ReadAllLines(your_file_path)
.Skip(skip_count)
.Take(200 - skip_count)
.ToArray();
You could also check KeyDown textbox event and accept only digits...

Best practice for formatting a string which needs to be send via TCP/IP

I have a couple of parameters, which need to be sent to a client app via TCP/IP.
For example:
//inside C++ program
int Temp = 10;
int maxTemp = 100;
float Pressure = 2.3;
Question: What is the best practice to format a string? I need to make sure that the whole string is received by the client and it should be easier at the client end to decode the string.
Basically, I want to know, what should be the format of the string, which I am going to send?
PS: Client app is in C# and the sender's app is in Qt (C++).
This is pretty subjective, but if it will always be as simple as described, then: keep it simple:
ASCII, space delimited, invariant (culture-independent) format integers in their fully expanded form (no E etc), CR as the end sentinel, so:
10 100 2
(with a CR at the end) This scales to any number of records, and will be easy to decode from just about any platform.
If it gets more nuanced: use a serializer built for the job, and just share details of what serialization format you are using.
Use ASCII, of the form paramName paramValue, space delimited, culture-independent format and use integers in their full form (no E notation) and a carriage return at the end, for example: T 10 P 100 mT 2 with CR at the end. In the other side, you can simply split the string by white spaces and note that even indices are parameters and odds indices are parameter values. Note that for every even parameter name index i then i+1 is its corresponding odd index parameter value. Also mind the CR at the end.

Categories