Page 1 of 1

Digital to analog converter

Posted: Thu Dec 01, 2022 4:34 pm
by kimonas
Hi, I am a new arduino-designer and i have a question.I read the tamperature of a sensor and i want to convert it through the digital to analog converter of STM32f303k8tx to analog and give it as an autput.How can i do that?Which are the commands for this conversion?

Thank you

Re: Digital to analog converter

Posted: Fri Dec 02, 2022 12:26 pm
by GonzoG
To use DAC simply use analogWrite() on DAC pin (PA4-PA6).
As to conversion, it depends on what you want on output, but easiest way is to use map() function.
You set DAC resolution with analogWriteResolution().

Re: Digital to analog converter

Posted: Wed Dec 28, 2022 8:33 am
by oodhoundhay
GonzoG wrote: Fri Dec 02, 2022 12:26 pm To use DAC simply use analogWrite() on DAC pin (PA4-PA6).
As to conversion, it depends on what you want on output, but easiest way is to use map() function.
You set DAC resolution with analogWriteResolution().
After acquiring a sensor's temperature reading, I want to provide it to the outside world in the form of an analog output using the STM32f303k8tx's onboard digital-to-analog converter. What do I need to do? Can you tell me the necessary instructions to make this change?

Re: Digital to analog converter

Posted: Wed Dec 28, 2022 12:19 pm
by GonzoG
It's pretty easy.
1. You need to set a temperature range you want to have.
2. Convert/map temperature you got to output values using map() function: https://www.arduino.cc/reference/en/lan ... /math/map/
3. use analogWrite() to set output.

Example:
You have input temperature in range -20*C to 70*C and output will have same range. Analog output resolution set to 12 bits.

Code: Select all


void setup{
...
	analogWriteResolution(12);
...
}

void loop(){
uint16_t temperature;
//read temperature
// temperature = ....
uint16_t output = map(temperature, -20, 70, 0, 4095)
analogWrite(PA4, output);
delay(1000);
}
because map() function uses 32b integer values as inputs, you might want to convert decimal fractions to integers. Simplest way it to multiply number by 10, 100, etc. depending on what precision you want.
example:

Code: Select all

void loop(){
...
temperature  *= 100;
uint16_t output = map(temperature, -2000, 7000, 0, 4095)
analogWrite(PA4, output);
delay(1000);
}
But there's one issue. Your output value depends on power supply voltage as the DAC output range is 0V-Vcc. You might need to do some calibrations in your program.