adc.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. //adc.c
  2. #include "adc.h"
  3. #include <stdio.h>
  4. #include <avr/io.h>
  5. #include <avr/pgmspace.h>
  6. #include "pins.h"
  7. uint8_t adc_state;
  8. uint8_t adc_count;
  9. uint16_t adc_values[ADC_CHAN_CNT];
  10. uint16_t adc_sim_mask;
  11. #ifdef ADC_CALLBACK
  12. extern void ADC_CALLBACK(void);
  13. #endif //ADC_CALLBACK
  14. void adc_init(void)
  15. {
  16. printf_P(PSTR("adc_init\n"));
  17. adc_sim_mask = 0x00;
  18. ADCSRA |= (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);
  19. ADMUX |= (1 << REFS0);
  20. ADCSRA |= (1 << ADEN);
  21. // ADCSRA |= (1 << ADIF) | (1 << ADSC);
  22. DIDR0 = ((ADC_CHAN_MSK & ADC_DIDR_MSK) & 0xff);
  23. DIDR2 = ((ADC_CHAN_MSK & ADC_DIDR_MSK) >> 8);
  24. adc_reset();
  25. // adc_sim_mask = 0b0101;
  26. // adc_sim_mask = 0b100101;
  27. // adc_values[0] = 1023 * 16;
  28. // adc_values[2] = 1023 * 16;
  29. // adc_values[5] = 1002 * 16;
  30. }
  31. void adc_reset(void)
  32. {
  33. adc_state = 0;
  34. adc_count = 0;
  35. uint8_t i; for (i = 0; i < ADC_CHAN_CNT; i++)
  36. if ((adc_sim_mask & (1 << i)) == 0)
  37. adc_values[i] = 0;
  38. }
  39. void adc_setmux(uint8_t ch)
  40. {
  41. ch &= 0x0f;
  42. if (ch & 0x08) ADCSRB |= (1 << MUX5);
  43. else ADCSRB &= ~(1 << MUX5);
  44. ADMUX = (ADMUX & ~(0x07)) | (ch & 0x07);
  45. }
  46. uint8_t adc_chan(uint8_t index)
  47. {
  48. uint8_t chan = 0;
  49. uint16_t mask = 1;
  50. while (mask)
  51. {
  52. if ((mask & ADC_CHAN_MSK) && (index-- == 0)) break;
  53. mask <<= 1;
  54. chan++;
  55. }
  56. return chan;
  57. }
  58. void adc_cycle(void)
  59. {
  60. if (adc_state & 0x80)
  61. {
  62. uint8_t index = adc_state & 0x0f;
  63. if ((adc_sim_mask & (1 << index)) == 0)
  64. adc_values[index] += ADC;
  65. if (++index >= ADC_CHAN_CNT)
  66. {
  67. index = 0;
  68. adc_count++;
  69. if (adc_count >= ADC_OVRSAMPL)
  70. {
  71. #ifdef ADC_CALLBACK
  72. ADC_CALLBACK();
  73. #endif //ADC_CALLBACK
  74. adc_reset();
  75. }
  76. }
  77. adc_setmux(adc_chan(index));
  78. adc_state = index;
  79. }
  80. else
  81. {
  82. ADCSRA |= (1 << ADSC); //start conversion
  83. adc_state |= 0x80;
  84. }
  85. }