array's indexes in c# start from 0.
this code line is your problem and the reason to the failure:
data[3] = Int32.Parse(serialPort.ReadLine());
change your code to:
int[] data = new int[3];
data[2] = Int32.Parse(serialPort.ReadLine());
data[1] = Int32.Parse(serialPort.ReadLine());
data[0] = Int32.Parse(serialPort.ReadLine());
Edit: (answer to the comment...)
This class provide you 2 extensions method one for unknown sequence length(but you have to create a stop condition) use the second method if you know the exact number of ints.
Note:
4 years ago i used SerialPort with a graphical tablet.
I used the event: DataReceived as a reading trigger.
for more information see this example.
//to use extension methods do: serialPort.ReadKnownLength(3);
public static class SerialPortExtensions
{
public static int[] ReadUnknownLength(this SerialPort serialPort)
{
var list = new List<int>();
while (true)
{
try
{
var input = serialPort.ReadLine();
//change the condition to your own break condition
if (String.IsNullOrEmpty(input))
break;
list.Add(int.Parse(input));
}
catch (TimeoutException)
{
}
}
// if you don't need to reorder
//return list.ToArray();
var result = new int[list.Count];
for (var i = 0; i < result.Length; i++)
{
//reorder the input(you did it in your question...)
result[i] = list[list.Count - (i + 1)];
}
return result;
}
//match your question behavior
public static int[] ReadKnownLength(this SerialPort serialPort, int length)
{
var result = new int[length];
for (int i = length - 1; i >= 0; i--)
{
result[i] = Int32.Parse(serialPort.ReadLine());
}
return result;
}
}