How to Output Analog Voltage Using DAC in Embedded C
To output analog voltage using
DAC in embedded C, initialize the DAC peripheral, set the desired digital value corresponding to the voltage, and start the DAC conversion. The DAC converts the digital value to an analog voltage on its output pin.Syntax
The basic steps to output analog voltage using DAC in embedded C are:
- Initialize DAC: Set up the DAC peripheral and configure its output pin.
- Set DAC value: Write a digital value to the DAC data register that corresponds to the desired analog voltage.
- Start DAC: Enable the DAC to begin conversion and output the voltage.
The digital value depends on the DAC resolution and reference voltage.
c
DAC_Init(); DAC_SetValue(value); DAC_Start();
Example
This example shows how to output approximately 1.65V on a 12-bit DAC with 3.3V reference voltage.
c
#include <stdint.h> #include "dac_driver.h" // hypothetical DAC driver header int main(void) { uint16_t dac_resolution = 4095; // 12-bit DAC max value float vref = 3.3f; // Reference voltage float desired_voltage = 1.65f; // Desired output voltage // Calculate digital value for desired voltage uint16_t dac_value = (uint16_t)((desired_voltage / vref) * dac_resolution); DAC_Init(); // Initialize DAC peripheral DAC_SetValue(dac_value); // Set DAC output value DAC_Start(); // Enable DAC output while(1) { // Keep output stable } return 0; }
Output
No console output; DAC outputs ~1.65V on hardware pin
Common Pitfalls
- Not initializing DAC: Forgetting to initialize the DAC peripheral causes no output.
- Wrong digital value: Using a value outside DAC range or not scaling voltage properly leads to incorrect output voltage.
- Not enabling DAC: Setting value without starting DAC means no analog output.
- Ignoring reference voltage: Always use correct reference voltage to calculate digital value.
c
/* Wrong way: No initialization or start */ DAC_SetValue(2048); // mid-scale value /* Right way: Initialize and start DAC */ DAC_Init(); DAC_SetValue(2048); DAC_Start();
Quick Reference
Tips for using DAC in embedded C:
- Always check your microcontroller's DAC resolution (e.g., 8, 10, 12 bits).
- Calculate digital value as:
value = (desired_voltage / reference_voltage) * max_dac_value. - Initialize and enable DAC before setting values.
- Use hardware datasheet for pin configuration and DAC registers.
Key Takeaways
Initialize and enable the DAC peripheral before setting output values.
Calculate the DAC digital value based on desired voltage and reference voltage.
Use the correct DAC resolution to scale your digital value properly.
Always start the DAC to see the analog voltage output on the pin.
Refer to your microcontroller datasheet for specific DAC setup details.