You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

118 lines
2.3 KiB

  1. #include "config.h"
  2. #include "adc.h"
  3. #include "adcext.h"
  4. #include "dac.h"
  5. #include "uart.h"
  6. #include "timer.h"
  7. #include <stdio.h>
  8. #include <math.h>
  9. #include "calibrate.h"
  10. #include "util.h"
  11. #include "mode.h"
  12. #include "led.h"
  13. #include "zoom.h"
  14. #include "packet.h"
  15. int send_data = 0;
  16. uint16_t send_adc;
  17. uint16_t send_dac;
  18. int possibly_clamped = 0;
  19. uint16_t dac_cmd;
  20. #define TIMER_RATE 8000 /* how often to read the ADC and update DAC */
  21. #define PC_RATE 8000 /* how often to send data to the PC */
  22. #define DEBUG_ISR_TIME
  23. #define ADC_WINDOW_MIN 512
  24. #define ADC_WINDOW_MIN_STEPTO 1280
  25. #define ADC_WINDOW_MAX 1536
  26. #define ADC_WINDOW_MAX_STEPTO 768
  27. /* Run mode */
  28. void TISR_HANDLER(5)
  29. {
  30. static int count = 0;
  31. int16_t v;
  32. #ifdef DEBUG_ISR_TIME
  33. LATAbits.LATA9 = 1;
  34. #endif
  35. timer_clear_txif(5);
  36. /* Get most recent sample from 12-bit ADC. */
  37. v = adc_get();
  38. if (v < ADC_CLAMP_MIN || v >= ADC_CLAMP_MAX)
  39. possibly_clamped = 1;
  40. /* Send data to PC */
  41. if (++count >= (TIMER_RATE / PC_RATE)) {
  42. count = 0;
  43. /* Send most recent sample and old DAC value */
  44. send_adc = v;
  45. send_dac = dac_cmd;
  46. send_data = 1;
  47. }
  48. /* If ADC value is outside the window, step DAC */
  49. if (v < ADC_WINDOW_MIN)
  50. dac_cmd = adc_to_dac(dac_cmd, v, ADC_WINDOW_MIN_STEPTO, g_scale);
  51. else if (v > ADC_WINDOW_MAX)
  52. dac_cmd = adc_to_dac(dac_cmd, v, ADC_WINDOW_MAX_STEPTO, g_scale);
  53. /* Send it out */
  54. dac_write(dac_cmd);
  55. #ifdef DEBUG_ISR_TIME
  56. LATAbits.LATA9 = 0;
  57. #endif
  58. }
  59. void run_normal(void)
  60. {
  61. uart1_init(500000);
  62. led_on();
  63. /* Assume startup current is 0 */
  64. msleep(100);
  65. dac_cmd = do_calibrate();
  66. timer_setup_16bit(5, TIMER_RATE, 1);
  67. timer_set_priority(5, 6);
  68. while(1) {
  69. if (send_data) {
  70. /* There's data to send. Disable the ISR briefly
  71. while we grab it */
  72. uint16_t a, d, o;
  73. disable_int({
  74. if (possibly_clamped) {
  75. /* Mark a possible overflow in the output */
  76. o = 1;
  77. possibly_clamped = 0;
  78. }
  79. a = send_adc;
  80. d = send_dac;
  81. send_data = 0;
  82. });
  83. packet_send_adc_dac(a, d, o);
  84. }
  85. if (uart1_can_get()) {
  86. switch (uart1_get()) {
  87. case 'c':
  88. disable_int({
  89. send_data = 0;
  90. dac_cmd = do_calibrate();
  91. });
  92. packet_send_calibration(g_scale);
  93. default:
  94. break;
  95. }
  96. }
  97. }
  98. }