Variadic UART_println
This commit is contained in:
parent
fd45ec264a
commit
3cb2df2468
2 changed files with 41 additions and 5 deletions
44
uart.c
44
uart.c
|
@ -1,6 +1,8 @@
|
|||
#include "uart.h"
|
||||
#include <avr/io.h>
|
||||
#include <util/delay.h>
|
||||
#include <stdarg.h> // va_list, va_start, va_end
|
||||
#include <stdlib.h> // itoa
|
||||
|
||||
// 9600 seems to be the highest the ATmega328P can handle in this config
|
||||
#define BAUD 9600
|
||||
|
@ -23,10 +25,44 @@ void UART_transmit(uint8_t data) {
|
|||
UDR0 = data;
|
||||
}
|
||||
|
||||
void UART_println(const char *str) {
|
||||
// Transmit each character until NULL character is encountered
|
||||
while (*str) UART_transmit(*str++);
|
||||
void UART_println(const char* format, ...) {
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
|
||||
// Iterate through the variadic arguments
|
||||
while (*format != '\0') {
|
||||
if (*format == '%') {
|
||||
format++;
|
||||
if (*format == 'd') {
|
||||
int i = va_arg(args, int);
|
||||
char buffer[12]; // Increase buffer size to accommodate integers and null terminator
|
||||
itoa(i, buffer, 10);
|
||||
// Transmit the string representation of the integer
|
||||
for (int j = 0; buffer[j] != '\0'; j++) {
|
||||
UART_transmit(buffer[j]);
|
||||
}
|
||||
} else if (*format == 's') {
|
||||
char *s = va_arg(args, char *);
|
||||
// Transmit each character of the string
|
||||
while (*s != '\0') {
|
||||
UART_transmit(*s++);
|
||||
}
|
||||
} else if (*format == 'c') {
|
||||
int c = va_arg(args, int);
|
||||
// Transmit the character
|
||||
UART_transmit(c);
|
||||
}
|
||||
} else {
|
||||
// Transmit the character
|
||||
UART_transmit(*format);
|
||||
}
|
||||
// Move to the next format specifier or character
|
||||
format++;
|
||||
}
|
||||
|
||||
// Transmit carriage return and line feed characters
|
||||
UART_transmit('\r');
|
||||
UART_transmit('\n');
|
||||
}
|
||||
|
||||
va_end(args);
|
||||
}
|
2
uart.h
2
uart.h
|
@ -4,4 +4,4 @@
|
|||
|
||||
void initUART();
|
||||
void UART_transmit(uint8_t data);
|
||||
void UART_println(const char *str);
|
||||
void UART_println(const char* format, ...);
|
Loading…
Reference in a new issue