Skip to content

Enhancement to DAC demo (precise period time & example of simple 'multi task' opportunity) #62225

@rjmaris

Description

@rjmaris

With the samples/drivers/dac demo, timing is - of course - not an issue. Nevertheless I'd suggest a simple improvement that replaces the dumb k_sleep() by sys_timepoint_expired(). Using a Cortex-M4 MCU at 168 MHz, the demo shows a sawtooth period of 4.5 seconds. With the new scheme, I measure approx. just slightly below 4.1 seconds.
Moreover, this demo then also represents a simple sample of how to be able to do a simple sort of doing more than one task at a time. DIFF (with v3.4):

diff --git a/samples/drivers/dac/src/main.c b/samples/drivers/dac/src/main.c
index 308777928b..a802ba3f68 100644
--- a/samples/drivers/dac/src/main.c
+++ b/samples/drivers/dac/src/main.c
@@ -47,12 +47,13 @@ int main(void)
 
        printk("Generating sawtooth signal at DAC channel %d.\n",
                DAC_CHANNEL_ID);
+       k_timepoint_t end;
        while (1) {
                /* Number of valid DAC values, e.g. 4096 for 12-bit DAC */
                const int dac_values = 1U << DAC_RESOLUTION;
 
                /*
-                * 1 msec sleep leads to about 4 sec signal period for 12-bit
+                * 1 msec sleep leads to about 4.1 sec signal period for 12-bit
                 * DACs. For DACs with lower resolution, sleep time needs to
                 * be increased.
                 * Make sure to sleep at least 1 msec even for future 16-bit
@@ -62,13 +63,15 @@ int main(void)
                        4096 / dac_values : 1;
 
                for (int i = 0; i < dac_values; i++) {
+                       end = sys_timepoint_calc((k_timeout_t)K_MSEC(sleep_time));
                        ret = dac_write_value(dac_dev, DAC_CHANNEL_ID, i);
                        if (ret != 0) {
                                printk("dac_write_value() failed with code %d\n", ret);
                                return 0;
                        }
-                       k_sleep(K_MSEC(sleep_time));
-               }
+                       while (!sys_timepoint_expired(end))
+                               /* something else could be done in this idle time,
+                                * e.g. button check for pause/resume  */;              }
        }
        return 0;
 }

The same could be accomplished with e.g. the adc demo.

Metadata

Metadata

Assignees

Labels

EnhancementChanges/Updates/Additions to existing featuresarea: DACDigital-to-Analog Converter

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions