0.6.0 this is the first version for the new hardware
[digitaldcpower] / dac.c
1 /* vim: set sw=8 ts=8 si : */
2 /*********************************************
3 * Author: Guido Socher, Copyright: GPL 
4
5 * Digital to analog converter using a R-2R leadder (7bit)
6 * and PWM (5bit)
7 **********************************************/
8 #include <avr/io.h>
9
10 // this dac can do 12 bit resolution: bit 0-4=pwm, bit 5-11=R-2R leadder
11 void dac(uint16_t value){
12         //OCR1AH=0;
13         OCR1AL=value&0x1F; // lower 5 bits
14         value=value>>(5-2);
15         // r2r ladder is pd2 to pd7 and pb0
16         PORTD=(PORTD&0x3)|(value&0xfc);
17         value=value>>8;
18         if (value){ // the MSB in the dac
19                 PORTB|= (1<<PINB0);
20         }else{
21                 PORTB &= ~(1<<PINB0);
22         }
23 }
24
25 void init_dac(void) 
26 {
27         // enable PD2 PD3 PD4 PD5 PD6 PD7 PB0 as output (PD2=LSB of R2R-leadder)
28         DDRD|= 0xfc; // output
29         PORTD &= PORTD&0x3; //  zero volt on PD2..PD7
30         DDRB|= (1<<DDB0);
31         PORTB &= ~(1<<PINB0);
32         //
33         DDRB|= (1<<DDB1); // PB1 output
34         // set up of Pulse Width Modulation (PWM)
35         TCNT1H=0; // counter to zero, high byte first
36         TCNT1L=0;
37         // COM1A1  COM1A0
38         //  1       0     Clear OC1A/OC1B on Compare Match (Set output to low level)
39         //  1       1     Set OC1A/OC1B on Compare Match (Set output to high level)
40         //
41         // Fast PWM, ICR1 is top
42         // See datasheet page 99 (settings) and 88 (description).
43         TCCR1A=(0<<COM1A0)|(1<<COM1A1)|(0<<WGM10)|(1<<WGM11);
44         TCCR1B=(1<<CS10)|(1<<WGM12)|(1<<WGM13); // full clock speed
45         // 6 bit resolution:
46         ICR1H=0;
47         ICR1L=0x3F;
48         // At what value to switch on the port (port OC1A=0 -> 0 Volt output)
49         OCR1AH=0;
50         OCR1AL=0;
51 }
52
53