03_main.ino 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. char outputStr[100];
  2. int16_t averages[AVG_PERIODS];
  3. const int throtDeadHigh = THROT_NONE + THROT_DEAD_ZONE,
  4. throtDeadLow = THROT_NONE - THROT_DEAD_ZONE;
  5. void loop() {
  6. const long startTime = millis();
  7. #ifdef SCAN_MODE
  8. for(byte ch = LOW_CHANNEL; ch <= NUM_CHANNELS; ch++) {
  9. int val = channelVals[ch];
  10. sprintf(outputStr, "Channel-%d:%d\t", ch, val);
  11. Serial.print(outputStr);
  12. }
  13. Serial.println();
  14. #else
  15. debugln();
  16. debugln("===================");
  17. int throttle = getThrottle();
  18. throttle = restrictThrottlePower(throttle);
  19. throttle = getAverage(throttle);
  20. sprintf(outputStr, "Throttle:%d", throttle);
  21. Serial.println(outputStr);
  22. digitalWrite(LEFT_MOTOR_DIRECT_PIN, throttle > 0 ? HIGH : LOW);
  23. analogWrite(LEFT_MOTOR_PIN, throttle > 0 ? throttle : -throttle);
  24. #endif
  25. const long now = millis();
  26. delay(SCAN_DELAY + (startTime - now));
  27. }
  28. int getThrottle() {
  29. int val = channelVals[THROT_CHANNEL];
  30. debug("Channel value: ");
  31. debug(val);
  32. debug("\t");
  33. if(val <= THROT_OFF) {
  34. debugln("Throttle is off");
  35. return 0;
  36. } else if(val < throtDeadHigh && val > throtDeadLow) {
  37. debugln("Throttle in dead zone");
  38. return 0;
  39. }
  40. int throttle = val < THROT_NONE
  41. ? map(val, THROT_MIN, THROT_NONE, -OUTPUT_RANGE, 0)
  42. : map(val, THROT_NONE, THROT_MAX, 0, OUTPUT_RANGE);
  43. throttle = constrain(throttle, -OUTPUT_RANGE, OUTPUT_RANGE);
  44. debugln("Throttle: ", throttle);
  45. return throttle;
  46. }
  47. int restrictThrottlePower(int throttle) {
  48. // Reduce the average voltage to something safe for the motor to consume.
  49. throttle = (throttle * MAX_POWER_PERCENT) / 100;
  50. debugln("Restricted throttle:\t", throttle);
  51. // Use the current value of the knob to reduce the speed.
  52. int speedKnob = channelVals[SPEED_CHANNEL];
  53. speedKnob = map(speedKnob, SPEED_MIN, SPEED_MAX, 0, 100);
  54. speedKnob = constrain(speedKnob, 0, 100);
  55. throttle = (throttle * speedKnob) / 100;
  56. debugln("Speed knob:\t", speedKnob);
  57. debugln("Speed adjusted throttle:\t", throttle);
  58. return throttle;
  59. }
  60. int getAverage(const int throttle) {
  61. long long total = throttle;
  62. for(byte i = 0; i < AVG_PERIODS-1; i++) {
  63. total += averages[i];
  64. averages[i] = averages[i+1];
  65. }
  66. averages[AVG_PERIODS-1] = throttle;
  67. total /= AVG_PERIODS;
  68. debugln("Average adjusted throttle:\t", total);
  69. return total;
  70. }