I have a stream of data from a COM port. This stream is composed of sets of 30 bytes. The first 26 bytes are the information and the last four is a set of 0xFFF
. For example, a set of array is [0xFF,0x5A,0x44,0x15,...,0x5F,0xFF,0xFF,0xFF,0xFF]
. In the first 26 byte there is no possibility to get a similar sequence.
Thus, I do not find any method in C# in order to "read until".
The piece of C# code that I use to read serial data is:
public static int count;
public static void Main()
{
SerialPort mySerialPort = new SerialPort("COM8");
mySerialPort.BaudRate = 250000;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.DtrEnable = true;
mySerialPort.RtsEnable = true;
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
mySerialPort.Open();
count = 0;
Console.WriteLine("Press any key to continue...");
Console.WriteLine();
Console.ReadKey();
mySerialPort.Close();
}
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
count++;
}
Is there another way in order to get a List<>
of 26 interesting bytes? Considering that the data are on an Arduino and I can edit the Arduino code and my Arduino sends around 800 bytes sets each second. The Arduino code, if you are interested, is (at this moment run under Arduino Due):
#define MAX_ADC_RESOLUTION 12
int val;
void setup() {
Serial.begin(250000);
analogReadResolution(MAX_ADC_RESOLUTION); //
adc_init(ADC, SystemCoreClock, ADC_FREQ_MAX*2, 4); //~220000 samples per second, A/D readings OK
val = 0;
}
void loop() {
int start = millis();
int num_samples = 0; //This identify the sample frequency
while( millis() - start < 1000 )
{
for(int channel=0;channel<12;channel++){ //loop for each analog (0-11)
val = analogRead(channel);
val++;
Serial.write((unsigned char)((val & 0xFF00) >> 8));
Serial.write(((unsigned char)(val & 0x00FF)));
}
Serial.write((unsigned char)((num_samples & 0xFF00) >> 8));
Serial.write(((unsigned char)(num_samples & 0x00FF)));
Serial.write(0xFF);
Serial.write(0xFF);
Serial.write(0xFF);
Serial.write(0xFF);
num_samples++;
}
}
Edit in order to explain better what is my problem:
If I set a simply length of buffered read I get a part of the incoming flow. So, the end control bytes can be placed everywhere in the array of bytes (e.g. I typically receive 0x44,0x53,...,0xFF,0xFF,0xFF,0xFF,..,0x55). In addition, suppose to receive a set as this: 0x22,...,0x00,0xFF,0xFF,0xFF,0xFF,0xFF. It is possible and my software will cut the last byte.