{solved} Unusual Serial behaviour

so i am using serial communication and programming it in C .
here is what i use

#define USART_BAUDRATE 9600
#define BAUD_PRESCALE (((20000000 / (USART_BAUDRATE * 20UL))) - 1)

and then use those in the code , i did put 20000000 because i overclocked the arduino UNO to 20Mhz , the thing is , with that same setting , when i use a 16Mhz osc serial communication runs fine at 9600 even with that 20000000 implemented in the code , the thing is when i put the 20Mhz osc Serial starts returning incorrect data sometimes , with a 16mhz osc the data flows good enough .
i am not using the lib , just working around it in C . as long as it works fine with 16Mhz but not with 20Mhz it must be a clock problem . (btw it's all programmed in C with the USART registers so the main arduino setup should not be the problem here)

It's defined in your sketch? Which #defines does the compiler see first? The ones in #include files, or the ones in your sketch? :slight_smile:

Thank you guys , aarg -> the constants defined in my code does not have matches by the IDE
the serial code does not use any library or anything . just some C code using the UART
registers like i said .

Where did you get that formula? Its not the correct one:
from HardwareSerial.cpp:

  if (use_u2x) {
    *_ucsra = 1 << _u2x;
    baud_setting = (F_CPU / 4 / baud - 1) / 2;
  } else {
    *_ucsra = 0;
    baud_setting = (F_CPU / 8 / baud - 1) / 2;
  }

I think you changed 16 to 20 when you changed 16000000 to 20000000.

MarkT:
Where did you get that formula? Its not the correct one:
from HardwareSerial.cpp:

  if (use_u2x) {

*_ucsra = 1 << _u2x;
    baud_setting = (F_CPU / 4 / baud - 1) / 2;
  } else {
    *_ucsra = 0;
    baud_setting = (F_CPU / 8 / baud - 1) / 2;
  }




I think you changed 16 to 20 when you changed 16000000 to 20000000.

at first i did try it with 16UL and 20000000 and it did not work . the weird bit is , even with that formula 20000000 and 20UL serial works with with 16Mhz UNO using the code ... unusual

The 16 is definitely 16, its a divide ratio nothing to do with the clock speed. In the
code from HardwareSerial you'll see a divide by 8 and a divide by 2, that's the 16 in your code.

The formula you use is the wrong one anyway, as I've pointed out. Go and look in
HardwareSerial.cpp in your Arduino sources (theres more than the snippet I gave),
and read the datasheet for the UART prescaling details.

thank you MarkT and aarg . :slight_smile: