Auto serial baudrate detector/selector

As mentioned in the other post I think you should test for a few pulses, so here's my version of the detRate() function (I don't have access to my hardware at present to test this).

long detRate(int recpin)  // function to return valid received baud rate
                          // Note that the serial monitor has no 600 baud option and 300 baud
                          // doesn't seem to work with version 22 hardware serial library
  {
  long baud, rate = 10000, x;
  for (int i = 0; i < 10; i++) {
      x = pulseIn(recpin,LOW);   // measure the next zero bit width
      rate = x < rate ? x : rate;
  }
   
  if (rate < 12)
      baud = 115200;
      else if (rate < 20)
      baud = 57600;
      else if (rate < 29)
      baud = 38400;
      else if (rate < 40)
      baud = 28800;
      else if (rate < 60)
      baud = 19200;
      else if (rate < 80)
      baud = 14400;
      else if (rate < 150)
      baud = 9600;
      else if (rate < 300)
      baud = 4800;
      else if (rate < 600)
      baud = 2400;
      else if (rate < 1200)
      baud = 1200;
      else
      baud = 0;  
   return baud;
  }

This will need 2-3 bytes to get a result, and can still get the wrong answer of course.

Another problem is that the 10th pulse could occur anywhere in a byte, so the main code probably should wait a short time then flush the rx buffer.

If the data stream is constant this may never sync.


Rob