I wrote up a function to connect via UART and print a string for debugging purposes. But my logic does not add up somehow... I see the line "Random Number" printed in the console but blazingly fast... no matter what I add for a _delay_ms value, it is not usable. Did I miss out on anything?

Why is my delay function not having any influence on the output on the serial terminal?

void initUSART(void) {

    #define BAUDRATE ((F_CPU) / (BAUD * 8UL)-1) // Set Baud Rate Value for UBRR

    // Set register
    UBRR0H = (BAUDRATE >> 8);
    UCSR0A |= (1 << U2X0);  
    // Enable USART transmitter and receiver
    UCSR0B = (1 << TXEN0) | (1 << RXEN0);
    // Set 8 data bits and 1 stop bit
    UCSR0C = (1 << UCSZ01) | (1 << UCSZ00);

void transmitByte(uint8_t data) {
    // Wait for empty transmit buffer
    loop_until_bit_is_set(UCSR0A, UDRE0);
    UDR0 = data;

void printString(const char myString[]) {
    uint8_t i = 0;
    while (myString[i]) {

int main(void)

    while (1) 
        printString("Random Number:\n");

    return (0);

When I use \r\nat the end of the string, the output gets really strange:

enter image description here

  • 2
    \$\begingroup\$ Check the _delay_ms() documentation, there are tricky limits to its input. Have you tried smaller values? Also, what's your F_CPU defined to? Try making your own delay loop with nops or something. Try different enabling or disabling optimizations. As for your \r output problem, could it be a problem with the terminal program? Check if the problem persists with a different program. \$\endgroup\$ – marcelm May 3 '17 at 19:49
  • 1
    \$\begingroup\$ The number 100000 is too big for a 16-bit value. Use a smaller delay time (like 100ms) and enclose that delay within a for loop \$\endgroup\$ – MarkU May 3 '17 at 20:49
  • \$\begingroup\$ @MarkU Did you look at the documentation for _ms_delay() I linked in my previous comment? Its argument is a double, not a 16-bit integer. He should limit its value, but for different reasons. \$\endgroup\$ – marcelm May 3 '17 at 22:00

Your Answer

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

Browse other questions tagged or ask your own question.