Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Buffering Serial Port Data

Status
Not open for further replies.

danielkelly

IS-IT--Management
Aug 13, 2006
28
AU
Hi All,

Im hoping someone can assist me with a project I am working on. I have a device connected to the serial port which is continuously sending data. I have included relevant code below.

I am trying to read this data into a buffer for processing as I will be looking for certain characters within the buffer to indicate a new message (this device does not use a "End of Line" character but rather a start of line.

So far I have the following :-

//Class Wide Variable - [0] is just an arbitrary value at this stage.
private byte[] _currentBuffer = new byte[0];

//Method for Receiving Data

void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
//Write The Data into The Com Buffer

//See How Many Bytes are Available
int newBytes = comPort.BytesToRead;

//Create a New Array of Bytes
byte[] newBuffer = new byte[newBytes];
comPort.Read(newBuffer, 0, newBytes);

//Add The Old Array to New Array

//Send the Data of For Processing To Look For Characters.

//If messages are found in buffer, remove from buffer and start again

}
catch (Exception exc)
{
DisplayData(MessageType.Error, exc.Message);
}
}

I am fine with adding the arrays etc and processing, my problem really comes down to where to store the "old data". The idea was to store it in a class wide variable but since you cant dynamically resize an array of bytes, I cant add to the original array.

My issue appears to be with the design and not really the coding side. The original thought was to continually increase / decrease the size of the class wide array so the processing functions can access it.

Can anyone offer some suggestions as to a solid design principle.

THanks in advance,

Daniel
 
2 thoughts.
1. use a List<byte> to store the bytes
Code:
private readonly List<byte> all = new List<byte>();
...
var length = comPort.BytesToRead;
var result = new byte[length];
comPort.Read(result, 0, length);
all.AddRange(result);
...
all.Clear(); //when you need to reset.
2. store the current results in a local array and overwrite the array with a larger one.
Code:
private byte[] all = new byte[0];
...
var length = comPort.BytesToRead;
var result = new byte[length];
comPort.Read(result, 0, length);

var tmp = new byte[all.Length + length];
all.Copy(tmp, 0, all.Length);
result.Copy(tmp, all.Lenght+1, length);
all = tmp;

...
all = new byte[0]; //when you need to reset.
something like that anyway.

Jason Meckley
Programmer

faq855-7190
faq732-7259
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top