adc.c


1
#include <avr/io.h>
2
3
// Mega16 Pinout
4
#define MOSI  4
5
#define MISO  6
6
#define SCLK  7
7
#define SS    4
8
9
10
11
unsigned int get_adc(unsigned char adata)
12
{
13
  static unsigned int temp=0;
14
  
15
  PORTB &= ~(1<<SS);                  // set cs on low to activied the adc
16
                                      // maybe here a little delay
17
  SPDR = adata;                        // put the data into send register
18
  while(!(SPSR & (1<<SPIF)));          // send 1 Byte over HW SPI and wait for tx complete int  
19
  temp = SPDR;                        // put the received data to a static temp variable
20
  temp = temp << 8;                    // shift the temp variable 8 steps left
21
  SPDR = adata;                        // put the data into send register
22
  while(!(SPSR & (1<<SPIF)));          // send 1 Byte over HW SPI and wait for tx complete int    
23
  temp |= SPDR;                        // put the received data to a static temp variable
24
  PORTB |= (1<<SS);                    // set cs on high to disable the adc
25
  return temp;                        // return the adc value
26
}
27
28
29
30
void spim_init(void)
31
{
32
  // SET the Ports to output 
33
  DDRB |= (1<<MOSI) | (1<<SCLK) | (1<<SS);
34
  // SET MISO to input
35
  DDRB &= ~(1<<MISO); 
36
  // SPI Enable, SPI Master, SPI CLK XTAL/16, LSB First
37
  SPCR |= (1<<SPE)|(1<<MSTR)|(1<<SPR0);    
38
  PORTB |= (1<<SS);    // CS High because the SPI ADC is low active
39
}
40
41
int main (void)
42
{
43
  static unsigned int adc_value=0;  // uint variable
44
  
45
  spim_init();                       // Init HW SPI Master
46
  adc_value = get_adc(0xFF);        // Get data from SPI ADC send anything to generate the clock
47
48
  for(;;){}
49
}