christop wrote:
If my math is right, the CPU clock speed would have to be exactly 3.5MHz to achieve that bit rate:
F_CPU = bitrate * 16 * (UBRR + 1)
3500000 = 31250 * 16 * (6 + 1)
If the clock rate is what it was previously (3.6864Mhz), the actual bit rate is slightly higher:
bitrate = F_CPU / (UBRR + 1) / 16
32914.3 = 3686400 / (6 + 1) / 16
Any error in the rate above a few percent will give you some garbage data as you saw. (32914.3/31250 = 1.053 = 5.3% too fast)
As an aside, the clock rate 3.6864MHz is used as it is an integer multiple of common (standard) serial bit rates:
115200 = 3686400 / (1 + 1) / 16
57600 = 3686400 / (3 + 1) / 16
38400 = 3686400 / (5 + 1) / 16
9600 = 3686400 / (23 + 1) / 16
(And obviously many more common bit rates are possible)
UBRR would be set to 1, 3, 5, or 23 for those bit rates.
Edit: if the bit rate has to be exactly 31250, I would use a CPU clock source that is an integer multiple of 500000 (31250*16), such as 4MHz (with a UBRR value of 7).
F_CPU = bitrate * 16 * (UBRR + 1)
3500000 = 31250 * 16 * (6 + 1)
If the clock rate is what it was previously (3.6864Mhz), the actual bit rate is slightly higher:
bitrate = F_CPU / (UBRR + 1) / 16
32914.3 = 3686400 / (6 + 1) / 16
Any error in the rate above a few percent will give you some garbage data as you saw. (32914.3/31250 = 1.053 = 5.3% too fast)
As an aside, the clock rate 3.6864MHz is used as it is an integer multiple of common (standard) serial bit rates:
115200 = 3686400 / (1 + 1) / 16
57600 = 3686400 / (3 + 1) / 16
38400 = 3686400 / (5 + 1) / 16
9600 = 3686400 / (23 + 1) / 16
(And obviously many more common bit rates are possible)
UBRR would be set to 1, 3, 5, or 23 for those bit rates.
Edit: if the bit rate has to be exactly 31250, I would use a CPU clock source that is an integer multiple of 500000 (31250*16), such as 4MHz (with a UBRR value of 7).
Yeah, I kinda realized that this morning, so i have an ATtiny85 generating a 4Mhz clock source, which should be able to do that baud rate with 0% (more or less) error. Fingers crossed!