Skip to content

Instantly share code, notes, and snippets.

@tuxmartin
Last active August 8, 2018 17:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tuxmartin/46ca107057c650fbe6f63dcae5ee067d to your computer and use it in GitHub Desktop.
Save tuxmartin/46ca107057c650fbe6f63dcae5ee067d to your computer and use it in GitHub Desktop.
arduino_baud_rate_detection
/*
casy na seriovem portu: https://www.kumari.net/index.php/random/37-determing-unknown-baud-rate
Odmeroval jsem je Saleae logickym analyzatorem
*/
int last_baud_rate = 9600;
int timeout = 1000; // [ms]
int recPin = 0; //the pin receiving the serial input data
long baudRate;
void set_serial_port() {
Serial.end();
digitalWrite (recPin, HIGH); // pull up enabled just for noise protection
baudRate = detRate(recPin); // Function finds a standard baudrate of either
// 1200,2400,4800,9600,14400,19200,28800,38400,57600,115200
// by having sending circuit send "U" characters.
// Returns 0 if none or under 1200 baud
Serial.begin(baudRate);
Serial.println();
Serial.print("Detected baudrate at ");
Serial.println(baudRate);
}
void setup() {
pinMode(recPin, INPUT); // make sure serial in is a input pin
set_serial_port();
}
void loop() {
set_serial_port();
Serial.println("Hello, world!");
delay(2000);
}
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
{
while(digitalRead(recpin) == 1){} // wait for low bit to start
long baud;
long rate = pulseIn(recpin,LOW); // measure zero bit width from character 'U'
if (rate < 0)
baud = 0;
else if (rate < 4)
baud = 500000;
else if (rate < 6)
baud = 230400;
else 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment