adc.c 1.6 KB

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