daWandlerDirekt.c


1
/**************************************************************************
2
% Projekt 9   : Ansteuerung DA-Converter MCP4921
3
% Autor       : 
4
% Filename    : daWandler.c
5
% Startdate   : 22.02.14
6
% Enddate     : 01.03.14
7
% Version     : 1.0
8
%**************************************************************************
9
%
10
%Auf ATMEGA16 16MHZ   ext. Cristal
11
%
12
%**************************************************************************
13
%
14
%Test zum Ansteueren des DA-Converters MCP4921. 
15
%
16
%**************************************************************************/
17
18
19
#include <avr/interrupt.h>    
20
#include <avr/io.h>  
21
22
23
#define UC_CS    PB4
24
#define UC_MOSI   PB5
25
#define UC_MISO   PB6
26
#define UC_SCK    PB7
27
28
typedef union ushort {                       
29
      uint16_t Short;                          
30
      uint8_t Byte[2];
31
} ushort;
32
33
34
35
volatile uint8_t flg = 0;
36
//prototypen
37
  unsigned char spi_transfer(unsigned char);
38
  void update();
39
  void init();
40
41
int main() {
42
  init();
43
44
  while(1){
45
        
46
  if (flg == 1){    
47
      cli();
48
      update();
49
      flg = 0;
50
      sei();
51
    }
52
  }
53
  return 0;
54
}
55
56
//Updates den MCP4921 
57
void update() {
58
  ushort value;
59
60
  value.Short = 4000;
61
  //value.Short *= amplitude;
62
63
  //Definiere die Kontroll-Werte fuer den chip
64
  //  bit 15 0 = Write to DAC register
65
  //  bit 14 0 = Unbuffered
66
  //  bit 13 0 = Output gain select (X2)
67
  //  bit 12 1 = Output shutdown control (Active mode) 
68
  value.Short |= 0x1000;
69
70
  //Output the data
71
  PORTB &= ~_BV(UC_CS);
72
73
  spi_transfer(value.Byte[1]);
74
  spi_transfer(value.Byte[0]);
75
76
  PORTB |= _BV(UC_CS);
77
}
78
79
80
// Transfers 1 byte of data via SPI
81
unsigned char spi_transfer(unsigned char data)
82
{
83
  SPDR = data;
84
  while (!(SPSR & (1<<SPIF)))     // warte bis uebertragen 
85
  {
86
  };
87
  return SPDR;                    // return the received byte
88
  }
89
90
void init() 
91
{
92
  //Init Ports
93
  DDRB  |= (1<<UC_MOSI) | (1<<UC_SCK) | (1<<UC_CS);
94
  PORTB = _BV(UC_CS);
95
  
96
  //Init SPI
97
  SPCR = (1<<SPE) | (1<<MSTR);        //Enable SPI, Master, set clock rated fclk/4
98
  SPSR = (1<<SPI2X);
99
100
  //Set up Timer2
101
  TCCR2 |=  (1<<WGM21);  //>ocr2 comp.
102
  TCCR2 =   _BV(CS21);//>prescale 8
103
  OCR2 = 10;
104
  TIMSK |= (1<<OCIE2);
105
  sei();  
106
}
107
108
109
ISR(TIMER2_COMP_vect) {
110
  flg = 1;
111
}