9

Is there some code I can use to find out what the a chosen serial port's speed is running at ?

  • 1
    Might just be easier to define the speed in a variable :) – Anonymous Penguin Mar 2 '15 at 2:40
  • Do you mean the PC or some other device sets the serial speed, and the Arduino to adjust itself to match? – DaveP Mar 2 '15 at 11:34
7

There is not a top level, easy to use way. Sorry. It is probably easier to just store your chosen baud rate in a variable when you setup the serial port.

Anyway, What you can try to do for the AVR-based, hardware UARTs is undo what Serial.begin does to set up a particular baud rate, but its a bit of a pain. This is the code for setting the baud rate:

  // Try u2x mode first
  uint16_t baud_setting = (F_CPU / 4 / baud - 1) / 2;
  *_ucsra = 1 << U2X0;

  // hardcoded exception for 57600 for compatibility with the bootloader
  // shipped with the Duemilanove and previous boards and the firmware
  // on the 8U2 on the Uno and Mega 2560. Also, The baud_setting cannot
  // be > 4095, so switch back to non-u2x mode if the baud rate is too
  // low.
  if (((F_CPU == 16000000UL) && (baud == 57600)) || (baud_setting >4095))
  {
    *_ucsra = 0;
    baud_setting = (F_CPU / 8 / baud - 1) / 2;
  }

  // assign the baud_setting, a.k.a. ubrr (USART Baud Rate Register)
  *_ubrrh = baud_setting >> 8;
  *_ubrrl = baud_setting;

You can find the results of this by reading the right UCSRA, UBRRH, and UBRRL registers. On an uno those are the correct register names, on an mega its UCSR0A, UBRR0H, UBRR0L for Serial, UCRS1A ... for serial1 and so on. Non-avr boards (and Serial on a leonardo) will be totally different.

There will be a single state for those three registers on an AVR hardware serial port for a particular board (and frequency of that board) at each baud rate. You can try and make an equation to get the original baud rate out, but I recommend just comparing the direct values with a lookup of some kind because the integer arithmetic rounding errors will make it a huge mess.

For example, on my mega UBBR0H, UBBR0L, and UCSR0A are 0, 207, 2 at 9600 baud, but they are 0, 51, 2 at 38400 baud and 0, 16, 0 at 57600 baud.

| improve this answer | |
  • thanks this is the sort of thing i was looking for, but as said it may be more trouble than worth compared with other alternatives. – Hayden Thring Mar 3 '15 at 0:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.