At the beginning of the stop bit, timer1 is halted. If everything went well, the 16 bit value in timer1 should indicate how many CPU cycles passed while the code waited for the eight data bits. Because the code timed all 8 bits, the value that will be needed for initializing the timer in auto-reload mode is calculated by dividing the CPU cycle count by 128. Care must be taken to avoid a round-off error that will yield an inaccurate baud rate value. This code will select the available baud rate which is the closest to what was received.
Many crystals are available which are exact multiples of the standard baud rates.
Usually these crystals provide faster baud rates than simply switching to a faster crystal. For example, a 4 MHz crystal provides 1200 baud. This code is available as plain text or in a zip file .