03_main.ino 2.1 KB

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