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/input
|
33 | DDRB |= (1<<MOSI) | (1<<MISO) | (1<<SCLK) | (1<<SS);
|
34 | // SPI Enable, SPI Master, SPI CLK XTAL/16, LSB First
|
35 | SPCR |= (1<<SPE)|(1<<MSTR)|(1<<SPR0);
|
36 | PORTB |= (1<<SS); // CS High because the SPI ADC is low active
|
37 | }
|
38 |
|
39 | int main (void)
|
40 | {
|
41 | static unsigned int adc_value=0; // uint variable
|
42 |
|
43 | spim_init(); // Init HW SPI Master
|
44 | adc_value = get_adc(0xFF); // Get data from SPI ADC send anything to generate the clock
|
45 |
|
46 | for(;;){}
|
47 | }
|