dac.c 1.54 KB
Newer Older
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include "ch.h"
#include "hal.h"
#include "board.h"

#include "dac.h"
#include <math.h>

static const DACConfig dac1cfg1 = {
  .init         = 2047U,
  .datamode     = DAC_DHRM_12BIT_RIGHT,
};

static const DACConversionGroup dacgrpcfg1 = {
  .num_channels = 1U,
  .trigger      = DAC_TRG(0)
};

/*
 * GPT6 configuration.
 */
static const GPTConfig gpt6cfg1 = {
  .frequency    = DAC_RATE,
  .callback     = NULL,
  .cr2          = TIM_CR2_MMS_1,    /* MMS = 010 = TRGO on Update Event.    */
  .dier         = 0U
};


void generate_waveform(float amplitude, waveform_t type, dacsample_t *buf) {
    switch(type) {
        case SINE:
            for (uint32_t i = 0; i < DAC_BUFFER_SIZE; ++i) {
               buf[i] = (amplitude * 2047.0f * sinf((2.0f*PI*i)/DAC_BUFFER_SIZE)) + 2047;
            }; break;
    }
}

THD_WORKING_AREA(waDAC, 512);
THD_FUNCTION(DACt, arg) {
  (void)arg;
  chRegSetThreadName("dac");

  dacStart(&DACD1, &dac1cfg1);
  gptStart(&GPTD6, &gpt6cfg1);

  generate_waveform(0.8, SINE, dac_buffer);

  dacStartConversion(&DACD1, &dacgrpcfg1,
                (dacsample_t *)dac_buffer, DAC_BUFFER_SIZE);
  gptStartContinuous(&GPTD6, 2U);

  while (true) {
    //thread_t *tp = chMsgWait();
    gptChangeInterval(&GPTD6, 2U);
    chThdSleepMilliseconds(5000);
    gptChangeInterval(&GPTD6, 10U);
    chThdSleepMilliseconds(5000);
    gptChangeInterval(&GPTD6, 100U);
    chThdSleepMilliseconds(5000);
    gptChangeInterval(&GPTD6, 1000U);
    chThdSleepMilliseconds(5000);
    gptChangeInterval(&GPTD6, 10000U);
    chThdSleepMilliseconds(5000);
  }
}