Guys

Here is my solution for baud rate detection.

It use a table of most common baud rate (including MIDI)

Comments welcomed

```
// most commonly used baud rate - including 31250 for MIDI
static int[] StandardBaudRate = new int[] { 120, 240, 1200, 2400, 4800, 9600, 19200, 31250, 38400, 56700, 115200, 230400 };
// bit duration for those baud rate in us
static int[] StandardBitLength = new int[] { 8333, 4167, 833, 417, 208, 104, 52, 32, 26, 18, 9, 5 };
// Call this function _before_ openning the SerialPort.
public static int FindBaudRate(Cpu.Pin _rxPin )
{
// capture bits length using PinCapture
uint[] bits = new uint[40];
bool initial = false; // not used
PinCapture pc = new PinCapture( _rxPin, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeBoth );
int n = pc.Read(initial, bits, 0, bits.Length, 2000);
pc.Dispose();
if (n == 0)
return 0;
// search for minimum bit duration, ignoring 1st one which may be incomplete
uint minBit = 1000000000;
for (int bit_index = 1; bit_index < bits.Length; bit_index++)
{
if ( minBit > bits[bit_index] )
minBit = bits[bit_index];
}
// computing mean values of all bits duration which are below 2*min
uint sum = 0, count = 0;
for (int bit_index = 1; bit_index < bits.Length; bit_index++)
{
if (bits[bit_index] < (2 * minBit))
{
sum += bits[bit_index];
++count;
}
}
uint meanBit = sum / count;
// search in table for index which match the best
int baud_found = -1;
int minDiff = 100000;
for (int baud_index = 0; baud_index < StandardBitLength.Length; ++baud_index)
{
int diff = System.Math.Abs(StandardBitLength[baud_index] - (int)meanBit);
if (diff < minDiff)
{
minDiff = diff;
baud_found = baud_index;
}
}
// if not found (souldn't be)
if (baud_found == -1)
return 0;
// return the baudrate
return StandardBaudRate[baud_found];
}
```