我有来自 COM 端口的数据流。此流由 30 个字节的集合组成。前 26 个字节是信息,后四个字节是一组0xFFF
. 例如,一组数组是[0xFF,0x5A,0x44,0x15,...,0x5F,0xFF,0xFF,0xFF,0xFF]
. 在前 26 个字节中,不可能得到类似的序列。
因此,我在 C# 中找不到任何方法来“读取直到”。我用来读取串行数据的 C# 代码是:
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++;
}
是否有另一种方法可以获得List<>
26 个有趣的字节?考虑到数据在 Arduino 上,我可以编辑 Arduino 代码,我的 Arduino 每秒发送大约 800 个字节集。如果您有兴趣,Arduino 代码是(此时在 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++;
}
}
编辑以更好地解释我的问题是什么:
如果我设置一个简单的缓冲读取长度,我会得到一部分传入流。因此,结束控制字节可以放置在字节数组中的任何位置(例如,我通常会收到 0x44,0x53,...,0xFF,0xFF,0xFF,0xFF,..,0x55)。另外,假设收到这样的集合:0x22,...,0x00,0xFF,0xFF,0xFF,0xFF,0xFF。这是可能的,我的软件会剪切最后一个字节。