Question

I am using ATmega128 and I need two serial ports for communication. I have been using printf from "stdio.h" header file to send data through USART 0. I also need to send data through USART 1 to lcd and I am curious about using formatted input function. I have been thinking that connecting same printf function to USART 1 and USART 0 makes the compiler confused so I haven't tried it.

Can anyone suggest how to make another printf say "Lprintf" to send data through USART 1 ??

Was it helpful?

Solution

What you want to do here is to use fprintf(). See the documentation on avr-libc for the function. Essentially, you want to have a fputc() function for UART1 and one for UART0. Then, based on that, you can create two FILE buffers. Once you do so, you are free to use fprintf() on each. Optionally, you can point stdout to one of these buffers, as to be able to use printf().

FILE uart1_out = FDEV_SETUP_STREAM(uart1_putc, 0, _FDEV_SETUP_WRITE);
FILE uart0_out = FDEV_SETUP_STREAM(uart0_putc, 0, _FDEV_SETUP_WRITE);

fprintf(&uart1_out, "printing to UART1");
fprintf(&uart0_out, "printing %d to UART0", 0);

stdout = &uart1_out;
stderr = &uart0_out;

printf("This string will be printed thru UART1");
fprintf(stderr, "This string will be printed thru UART0");

You just need to provide the implementation for int uart1_putc(int, FILE*) and int uart0_putc(int, FILE*) to manipulate data as you wish.

Hope this helps.

Cheers.

OTHER TIPS

Depending on how you've linked it, there are two alternatives that are possibly simpler:

  1. Use sprintf() to write your formatted text to a string, and then use your own putchar() or putstring() to send it to the desired USART.

  2. If you're using the FILE struct to link your USARTs to the stdio functions (likely), you can use fprintf() to direct the results to a particular stream.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top