LwPRINTF instances

LwPRINTF is very flexible and allows multiple instances for output print functions.

Note

Multiple instances with LwPRINTF are useful only with direct print functions, suchs as lwprintf_printf. If application uses only format functions which write to input buffer, it may always use default LwPRINTF instance which is created by the library itself

Use of different instances is useful if application needs different print configurations. Each instance has its own print_output function, allowing application to use multiple debug configurations (as an example)

Tip

Use functions with _ex suffix to direcly work with custom instances. Functions without _ex suffix use default LwPRINTF instance

Custom LwPRINTF instance for output
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include "lwprintf/lwprintf.h"

/* Define application custom instance */
lwprintf_t custom_instance;

/* Define custom output function for print */
int
custom_out(int ch, lwprintf_t* p) {
    /* Do whatever with this character */
    if (ch == '\0') {
        /* This is end of string in current formatting */
        /* Maybe time to start DMA transfer? */
    } else {
        /* Print or send character */
    }

    /* Return character to proceed */
    return ch;
}

/* Define output function for default instance */
int
default_out(int ch, lwprintf_t* p) {
    /* Print function for default instance */

    /* See custom_out function for implementation details */
}

int
main(void) {
    /* Initialize default lwprintf instance with output function */
    lwprintf_init(default_out);
    /* Initialize custom lwprintf instance with output function */
    lwprintf_init_ex(&custom_instance, custom_out);

    /* Print first text over default output */
    lwprintf_printf("Text: %d", 10);
    /* Print text over custom instance */
    lwprintf_printf_ex(&custom_instance, "Custom: %f", 3.2f);
}

Note

It is perfectly valid to use single output function for all application instances. Use check against input parameter for lwprintf_t if it matches your custom LwPRINTF instance memory address

Single output function for all LwPRINTF instances
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include "lwprintf/lwprintf.h"

/* Define application custom instance */
lwprintf_t custom_instance1;
lwprintf_t custom_instance2;

/* Define custom output function for print */
int
my_out(int ch, lwprintf_t* p) {
    if (p == &custom_instance1) {
        /* This is custom instance 1 */
    } else if (p == &custom_instance2) {
        /* This is custom instance 2 */
    } else {
        /* This is default instance */
    }
    return ch;
}

int
main(void) {
    /* Initialize default lwprintf instance with output function */
    lwprintf_init(my_out);
    lwprintf_init_ex(&custom_instance1, my_out);
    lwprintf_init_ex(&custom_instance2, my_out);

    /* Use print functions ... */
}