我有来自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++;
}
还有另一种方法可以获得26个有趣字节的List<>
吗?考虑到数据在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。这是可能的,我的软件将削减最后一个字节。
答案 0 :(得分:1)
为什么不使用Read有点像这样:
byte[] buffer = new byte[30];
sp.Read(buffer, 0, 30);
通过这种方式,您可以获得字节数组,并且可以测试您需要/不需要的值。