ads1224.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #include "ads1224.h"
  2. #include "main.h"
  3. volatile unsigned char ads1224_read_wait = 0;
  4. volatile float adc_val;
  5. volatile unsigned char adc_data_ready;
  6. unsigned char adc_skip_result = 5;
  7. void ads1224_mux(unsigned char input){
  8. cli();
  9. if(input&1){
  10. PORTB |= ADC_MUX0;
  11. } else {
  12. PORTB &= ~ADC_MUX0;
  13. }
  14. if(input&2){
  15. PORTB |= ADC_MUX1;
  16. } else {
  17. PORTB &= ~ADC_MUX1;
  18. }
  19. adc_skip_result = 10;
  20. sei();
  21. }
  22. void ads1224_init(void){
  23. // configure pin change interrupt on PB6/PCINT14
  24. PCICR |= _BV(PCIE1);
  25. PCMSK1 |= _BV(PCINT14);
  26. // configure mux outputs
  27. DDRB |= ADC_MUX1 | ADC_MUX0; // MUX1 is SS so set it before SPI init!
  28. // configure SPI
  29. DDRB |= _BV(PB7); // SCK as output
  30. SPCR = _BV(SPE) | _BV(MSTR) | _BV(CPHA);
  31. SPSR = _BV(SPI2X); // CLK/2
  32. ads1224_read_wait = 1;
  33. }
  34. void ads1224_data_read(void){
  35. static unsigned char adc_avg_count = 0;
  36. static signed long int adc_buf = 0;
  37. unsigned char i;
  38. union {
  39. signed long int out;
  40. unsigned char d[4];
  41. } ads1224_out;
  42. for(i=3; i>0; i--){
  43. while(!(SPSR & _BV(SPIF)));
  44. if(i > 1)
  45. SPDR = 0;
  46. ads1224_out.d[i] = SPDR;
  47. }
  48. SPCR = 0; // addidtional sck pulse
  49. PORTB |= _BV(PB7);
  50. PORTB &= ~_BV(PB7);
  51. SPCR = _BV(SPE) | _BV(MSTR) | _BV(CPHA);
  52. if(adc_skip_result){
  53. adc_skip_result--;
  54. adc_buf = 0;
  55. adc_avg_count = 0;
  56. adc_data_ready = 0;
  57. } else {
  58. adc_buf += ads1224_out.out >> 8;
  59. if(++adc_avg_count == 32){
  60. adc_val = adc_buf; // interrupt context!
  61. adc_avg_count = 0;
  62. adc_buf = 0;
  63. adc_data_ready = 1;
  64. }
  65. }
  66. ads1224_read_wait = 1;
  67. }
  68. ISR(PCINT1_vect){
  69. PORTB ^= _BV(PB2);
  70. if(ads1224_read_wait && !(PINB & _BV(PB6))){
  71. ads1224_read_wait = 0;
  72. SPDR = 0; // start SPI transaction
  73. ads1224_data_read();
  74. }
  75. PORTB ^= _BV(PB2);
  76. }