-1
while(1)
{ 
    for(x=0;x<5;)   //note: x is incremented elsewhere 
    {
        DAC->DHR12R1 = (uint16_t)(x/5.0*4095*3.0/3.3);
    }
}   

what does this loop mean?I know the DHR12R1 is data hold register 12bits right

1 Answers1

0

I've converted it to a standard C program to see what values are written to the DAC register.

#include <stdio.h>
#include <stdint.h>
int x;
int main() {
  for(x=0;x<=5;x++) // Why x <= 5? See note at bottom
    printf("x=%d DAC->DHR12R1=%u\n", x, (uint16_t)(x/5.0*4095*3.0/3.3));
  return 0;
}

Output:

$ gcc -Wall -Wextra dac.c -o dac && ./dac
x=0 DAC->DHR12R1=0
x=1 DAC->DHR12R1=744
x=2 DAC->DHR12R1=1489
x=3 DAC->DHR12R1=2233
x=4 DAC->DHR12R1=2978
x=5 DAC->DHR12R1=3722

This value will eventually end up in the DAC Channel 1 Data Output Register DAC->DOR1, and gets converted to a voltage according to the formula

U=Vref*DAC->DOR1/4095

So, if your Vref is 3 Volts, then you'd get 0 Volts at x=0, 0.545 Volts at x=1 etc.

Note: I've assumed that x is incremented by 1 in some interrupt handler, then x can be briefly set to 5 before it gets reset to 0. If it can be incremented by arbitrary values, or this interrupt can occur more than once per loop iteration, then the result will wrap around at 4096. It means that the output voltage will normally fall between GND and 0.727*Vref, with occasional short spikes above that. Note also that if two increments ocuur in short succession at the wrong moment, one before x<5 is checked, and the other right after that, before x=0 is executed, then one pulse will be lost.

Therefore, you should consider moving the limit check into the interupt where the increment occurs, like

x = (x + 1) % 5;