简体   繁体   中英

Reading Real time data from serial port

I am trying to read real time data from an accelerometer. Sampling frequency of the accelerometer is 2650Hz. I am getting proper data from serial port, but unable to match with the sampling frequency. The sampling frequency is varying from 2100Hz to 2400Hz and it is not stable. I am using a stop watch for timing reference.

Here is my code for receiving serial data.

private void toolStripButton12_Click(object sender, EventArgs e)
{
    serialPort1.PortName = comboBox1.Text;
    serialPort1.BaudRate = Convert.ToInt32(115200);

    if (!serialPort1.IsOpen)
    {
        serialPort1.Open();
    }                    
    sw.Start();
    serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(SerialPort1_DataReceived);
}

}


private void SerialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    {
        byteCount = serialPort1.BytesToRead;
        if (byteCount > 4000)
        byteCount = 4000;

        if (e.EventType == SerialData.Eof)
        return;
        byte[] buffer = new byte[byteCount];

        int readBytes = serialPort1.Read(buffer, 0, buffer.Length);

        // FIFO Implementation

        buffer.ToList().ForEach(b => newrecievedData1.Enqueue(b));
        if (newrecievedData1.Count < 4000) return;
        processdata3();

        int i = 0;

        {
            while (i <= packet3.Length-4)
            {
                while (packet3[i++] != 69) ;

                data = packet3[i++];
                a = data << 8;
                b = a + packet3[i++];
                c = b << 8;
                d = c + packet3[i++];
                Port1data.Add(d);


                countbyte[0]++;

                tick = (double)countbyte[0];
            }
        }

        t = (double)sw.Elapsed.TotalSeconds;             
        Sampling frequency = tick / t;
    }

    try
    {
        this.Invoke(new EventHandler(DisplayText));
    }
    catch
    {
    }
}

Int32[] packet3;

private Int32[] processdata3()
{
    if (newrecievedData1.Count >= 4000)
    {
        packet3 = Enumerable.Range(0, 4000).Select(h => newrecievedData1.Dequeue()).ToArray();
    }
    return packet3;
}

I want to exactly get 2650 Hz sampling frequency all the time.Any help is highly appreciated.

That is 0.337 ms per sample. That is really pushing the upper limits of how much code can be done per sample.

Without some major optimization to your algorithms (possibly using custom collections designed specifically for your workload) I don't think your requirements are reachable using managed code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM