I've got problem that makes me crazy - I think that's so easy that I can't even think about what is causing my problems.
I'm sending data (fft of generated acustic wave - frequencies and magnitude) generated by my uC to PC by serialport.
Everything seems to work fine till I try to chart my data with MS Chart Controls - without charting there are no errors when recieving data. I'm always able to chart data once or twice, after that I'm getting error like this:
An unhandled exception of type 'System.OverflowException' occurred in System.Windows.Forms.DataVisualization.dll
Additional information: Value was either too large or too small for a Decimal.
I checked if vaules of data are over limits of "float32" aka Single - I even applied statement where I make values lower when they are too high - it's useless. The part of my with recievedata event and charting is like this:
private byte[] bArray = new byte[20 * numberOfSamples + 4]; // frequencies (512 samples) and magnitudes (512 values) - each is a single precision float so 4 bytes + 4 - "!!!!" at the beginning
private float[] fArray = new float[2 * numberOfSamples + 1]; // float data array
private void SerialP_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
int previouse = counterOfRecBytes;
counterOfRecBytes += sp.BytesToRead;
//if (counterOfRecBytes >= 4104)
sp.Read(bArray, previouse, (counterOfRecBytes - previouse));
if (counterOfRecBytes >= 8 * numberOfSamples + 4)
{
for (uint i = 0; i < 2 * numberOfSamples + 1; i++)
{
fArray[i] = Math.Abs(ByteToFloat(bArray, i));
if (fArray[i] < 0) fArray[i] = 0;
if (fArray[i] > 3.4 * Math.Pow(10, 38) || fArray[i] < -3.4 * Math.Pow(10, 38)) fArray[i] = 0;
}
if (InvokeRequired)
{
Invoke(new MethodInvoker(ChartData));
}
else
{
ChartData();
}
// Set counterOfRecBytes to recieve new data
counterOfRecBytes = 0;
}
}
///// <summary>
///// Changes my recieved bArray to single precision floats
///// </summary>
private float ByteToFloat(byte[] input, UInt32 i)
{
byte[] array = new[] { input[4 * i], input[4 * i + 1], input[4 * i + 2], input[4 * i + 3] };
return BitConverter.ToSingle(array, 0);
}
/// <summary>
/// Setting chart data
/// </summary>
private void ChartData()
{
chart1.Series["Widmo"].Points.Clear();
for(int i = 1; i < numberOfSamples + 1; i++)
{
chart1.Series["Widmo"].Points.AddXY(fArray[i], fArray[i + numberOfSamples]);
}
}