-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathdac.c
69 lines (59 loc) · 1.96 KB
/
dac.c
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
66
67
68
69
// Driver for MCP4922 DAC on USARTC1
// (C) 2012 Nonolith Labs
// Authors:
// Kevin Mehall
// Ian Daniher
// Licensed under the terms of the GNU GPLv3+
/// Configures the XMEGA's USARTC1 to talk to the digital-analog converter.
void DAC_init(void){
PORTD.DIRSET = DAC_SHDN;
PORTD.OUTSET = DAC_SHDN;
PORTC.DIRSET = LDAC | CS | SCK | TXD1;
USARTC1.CTRLC = USART_CMODE_MSPI_gc; // SPI master, MSB first, sample on rising clock (UCPHA=0)
USARTC1.BAUDCTRLA = 0; // 16MHz SPI clock. XMEGA AU manual 23.15.6 & 23.3.1
USARTC1.BAUDCTRLB = 0;
USARTC1.CTRLB = USART_TXEN_bm; // enable TX
PORTC.OUTSET = CS;
PORTC.OUTCLR = LDAC | CS; // LDAC, SCK low
}
// Configuration nibbles for the DAC
uint8_t DAC_data_config[2];
/// Buffer for the pending data to be written to the DAC
uint8_t DAC_data[2];
/// Generate the DAC flags nibble based on the mode
#define MODE_TO_DACFLAGS(m) ((((m)!=DISABLED)?DACFLAG_ENABLE:0) \
|(((m)==SIMV)?DACFLAG_NO_MULT_REF:0))
/// Update the config nibbles to DAC_data based on the new flags
inline void DAC_config(uint8_t mode_a, uint8_t mode_b){
DAC_data_config[0] = MODE_TO_DACFLAGS(mode_a) << 4;
DAC_data_config[1] = (DACFLAG_CHANNEL | MODE_TO_DACFLAGS(mode_b)) << 4;
}
/// Begin a non-blocking DAC write of the data from an OUT_Sample
inline void DAC_startWrite(OUT_sample* s){
// Put out_sample into DAC_data
uint8_t data0 = DAC_data_config[0] | (s->bh_ah & 0x0F);
uint8_t data1 = s->al;
DAC_data[0] = DAC_data_config[1] | (s->bh_ah >> 4);
DAC_data[1] = s->bl;
dac_write_state = 0;
dac_done = 0;
CS_LO();
USARTC1.DATA = data0;
USARTC1.DATA = data1;
USARTC1.STATUS = USART_TXCIF_bm; // clear TXC
USARTC1.CTRLA = USART_TXCINTLVL_HI_gc; // enable TXC
}
ISR(USARTC1_TXC_vect){
CS_HI();
if (!dac_write_state){
CS_LO();
USARTC1.DATA = DAC_data[0]; // write byte 2
USARTC1.DATA = DAC_data[1]; // write byte 3
dac_write_state = 1;
}else{
dac_done = 1;
}
}
inline void DAC_wait(void){
while(!dac_done);
}