1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- #include "ads1224.h"
- #include "main.h"
- volatile unsigned char ads1224_read_wait = 0;
- volatile float adc_val;
- volatile unsigned char adc_data_ready;
- unsigned char adc_skip_result = 5;
- void ads1224_mux(unsigned char input){
- cli();
- if(input&1){
- PORTB |= ADC_MUX0;
- } else {
- PORTB &= ~ADC_MUX0;
- }
- if(input&2){
- PORTB |= ADC_MUX1;
- } else {
- PORTB &= ~ADC_MUX1;
- }
- adc_skip_result = 10;
- sei();
- }
- void ads1224_init(void){
- // configure pin change interrupt on PB6/PCINT14
- PCICR |= _BV(PCIE1);
- PCMSK1 |= _BV(PCINT14);
-
- // configure mux outputs
- DDRB |= ADC_MUX1 | ADC_MUX0; // MUX1 is SS so set it before SPI init!
-
- // configure SPI
- DDRB |= _BV(PB7); // SCK as output
- SPCR = _BV(SPE) | _BV(MSTR) | _BV(CPHA);
- SPSR = _BV(SPI2X); // CLK/2
-
- ads1224_read_wait = 1;
- }
- void ads1224_data_read(void){
- static unsigned char adc_avg_count = 0;
- static signed long int adc_buf = 0;
- unsigned char i;
- union {
- signed long int out;
- unsigned char d[4];
- } ads1224_out;
-
- for(i=3; i>0; i--){
- while(!(SPSR & _BV(SPIF)));
- if(i > 1)
- SPDR = 0;
- ads1224_out.d[i] = SPDR;
- }
-
- SPCR = 0; // addidtional sck pulse
- PORTB |= _BV(PB7);
- PORTB &= ~_BV(PB7);
- SPCR = _BV(SPE) | _BV(MSTR) | _BV(CPHA);
-
- if(adc_skip_result){
- adc_skip_result--;
- adc_buf = 0;
- adc_avg_count = 0;
- adc_data_ready = 0;
- } else {
- adc_buf += ads1224_out.out >> 8;
- if(++adc_avg_count == 32){
- adc_val = adc_buf; // interrupt context!
- adc_avg_count = 0;
- adc_buf = 0;
- adc_data_ready = 1;
- }
- }
-
- ads1224_read_wait = 1;
- }
- ISR(PCINT1_vect){
- PORTB ^= _BV(PB2);
- if(ads1224_read_wait && !(PINB & _BV(PB6))){
- ads1224_read_wait = 0;
- SPDR = 0; // start SPI transaction
- ads1224_data_read();
- }
- PORTB ^= _BV(PB2);
- }
|