My Marlin configs for Fabrikator Mini and CTC i3 Pro B
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.

servo.cpp 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
  4. *
  5. * Based on Sprinter and grbl.
  6. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. /**
  23. * servo.cpp - Interrupt driven Servo library for Arduino using 16 bit timers- Version 2
  24. * Copyright (c) 2009 Michael Margolis. All right reserved.
  25. */
  26. /**
  27. * A servo is activated by creating an instance of the Servo class passing the desired pin to the attach() method.
  28. * The servos are pulsed in the background using the value most recently written using the write() method
  29. *
  30. * Note that analogWrite of PWM on pins associated with the timer are disabled when the first servo is attached.
  31. * Timers are seized as needed in groups of 12 servos - 24 servos use two timers, 48 servos will use four.
  32. *
  33. * The methods are:
  34. *
  35. * Servo - Class for manipulating servo motors connected to Arduino pins.
  36. *
  37. * attach(pin) - Attach a servo motor to an i/o pin.
  38. * attach(pin, min, max) - Attach to a pin, setting min and max values in microseconds
  39. * Default min is 544, max is 2400
  40. *
  41. * write() - Set the servo angle in degrees. (Invalid angles —over MIN_PULSE_WIDTH— are treated as µs.)
  42. * writeMicroseconds() - Set the servo pulse width in microseconds.
  43. * move(pin, angle) - Sequence of attach(pin), write(angle), delay(SERVO_DELAY).
  44. * With DEACTIVATE_SERVOS_AFTER_MOVE it detaches after SERVO_DELAY.
  45. * read() - Get the last-written servo pulse width as an angle between 0 and 180.
  46. * readMicroseconds() - Get the last-written servo pulse width in microseconds.
  47. * attached() - Return true if a servo is attached.
  48. * detach() - Stop an attached servo from pulsing its i/o pin.
  49. *
  50. */
  51. #include "MarlinConfig.h"
  52. #if HAS_SERVOS
  53. #include <avr/interrupt.h>
  54. #include <Arduino.h>
  55. #include "servo.h"
  56. #define usToTicks(_us) (( clockCyclesPerMicrosecond()* _us) / 8) // converts microseconds to tick (assumes prescale of 8) // 12 Aug 2009
  57. #define ticksToUs(_ticks) (( (unsigned)_ticks * 8)/ clockCyclesPerMicrosecond() ) // converts from ticks back to microseconds
  58. #define TRIM_DURATION 2 // compensation ticks to trim adjust for digitalWrite delays // 12 August 2009
  59. //#define NBR_TIMERS ((MAX_SERVOS) / (SERVOS_PER_TIMER))
  60. static ServoInfo_t servo_info[MAX_SERVOS]; // static array of servo info structures
  61. static volatile int8_t Channel[_Nbr_16timers ]; // counter for the servo being pulsed for each timer (or -1 if refresh interval)
  62. uint8_t ServoCount = 0; // the total number of attached servos
  63. // convenience macros
  64. #define SERVO_INDEX_TO_TIMER(_servo_nbr) ((timer16_Sequence_t)(_servo_nbr / (SERVOS_PER_TIMER))) // returns the timer controlling this servo
  65. #define SERVO_INDEX_TO_CHANNEL(_servo_nbr) (_servo_nbr % (SERVOS_PER_TIMER)) // returns the index of the servo on this timer
  66. #define SERVO_INDEX(_timer,_channel) ((_timer*(SERVOS_PER_TIMER)) + _channel) // macro to access servo index by timer and channel
  67. #define SERVO(_timer,_channel) (servo_info[SERVO_INDEX(_timer,_channel)]) // macro to access servo class by timer and channel
  68. #define SERVO_MIN() (MIN_PULSE_WIDTH - this->min * 4) // minimum value in uS for this servo
  69. #define SERVO_MAX() (MAX_PULSE_WIDTH - this->max * 4) // maximum value in uS for this servo
  70. /************ static functions common to all instances ***********************/
  71. static inline void handle_interrupts(timer16_Sequence_t timer, volatile uint16_t* TCNTn, volatile uint16_t* OCRnA) {
  72. if (Channel[timer] < 0)
  73. *TCNTn = 0; // channel set to -1 indicated that refresh interval completed so reset the timer
  74. else {
  75. if (SERVO_INDEX(timer, Channel[timer]) < ServoCount && SERVO(timer, Channel[timer]).Pin.isActive)
  76. digitalWrite(SERVO(timer, Channel[timer]).Pin.nbr, LOW); // pulse this channel low if activated
  77. }
  78. Channel[timer]++; // increment to the next channel
  79. if (SERVO_INDEX(timer, Channel[timer]) < ServoCount && Channel[timer] < SERVOS_PER_TIMER) {
  80. *OCRnA = *TCNTn + SERVO(timer, Channel[timer]).ticks;
  81. if (SERVO(timer, Channel[timer]).Pin.isActive) // check if activated
  82. digitalWrite(SERVO(timer, Channel[timer]).Pin.nbr, HIGH); // it's an active channel so pulse it high
  83. }
  84. else {
  85. // finished all channels so wait for the refresh period to expire before starting over
  86. if (((unsigned)*TCNTn) + 4 < usToTicks(REFRESH_INTERVAL)) // allow a few ticks to ensure the next OCR1A not missed
  87. *OCRnA = (unsigned int)usToTicks(REFRESH_INTERVAL);
  88. else
  89. *OCRnA = *TCNTn + 4; // at least REFRESH_INTERVAL has elapsed
  90. Channel[timer] = -1; // this will get incremented at the end of the refresh period to start again at the first channel
  91. }
  92. }
  93. #ifndef WIRING // Wiring pre-defines signal handlers so don't define any if compiling for the Wiring platform
  94. // Interrupt handlers for Arduino
  95. #if ENABLED(_useTimer1)
  96. SIGNAL (TIMER1_COMPA_vect) { handle_interrupts(_timer1, &TCNT1, &OCR1A); }
  97. #endif
  98. #if ENABLED(_useTimer3)
  99. SIGNAL (TIMER3_COMPA_vect) { handle_interrupts(_timer3, &TCNT3, &OCR3A); }
  100. #endif
  101. #if ENABLED(_useTimer4)
  102. SIGNAL (TIMER4_COMPA_vect) { handle_interrupts(_timer4, &TCNT4, &OCR4A); }
  103. #endif
  104. #if ENABLED(_useTimer5)
  105. SIGNAL (TIMER5_COMPA_vect) { handle_interrupts(_timer5, &TCNT5, &OCR5A); }
  106. #endif
  107. #else // WIRING
  108. // Interrupt handlers for Wiring
  109. #if ENABLED(_useTimer1)
  110. void Timer1Service() { handle_interrupts(_timer1, &TCNT1, &OCR1A); }
  111. #endif
  112. #if ENABLED(_useTimer3)
  113. void Timer3Service() { handle_interrupts(_timer3, &TCNT3, &OCR3A); }
  114. #endif
  115. #endif // WIRING
  116. static void initISR(timer16_Sequence_t timer) {
  117. #if ENABLED(_useTimer1)
  118. if (timer == _timer1) {
  119. TCCR1A = 0; // normal counting mode
  120. TCCR1B = _BV(CS11); // set prescaler of 8
  121. TCNT1 = 0; // clear the timer count
  122. #if defined(__AVR_ATmega8__)|| defined(__AVR_ATmega128__)
  123. SBI(TIFR, OCF1A); // clear any pending interrupts;
  124. SBI(TIMSK, OCIE1A); // enable the output compare interrupt
  125. #else
  126. // here if not ATmega8 or ATmega128
  127. SBI(TIFR1, OCF1A); // clear any pending interrupts;
  128. SBI(TIMSK1, OCIE1A); // enable the output compare interrupt
  129. #endif
  130. #ifdef WIRING
  131. timerAttach(TIMER1OUTCOMPAREA_INT, Timer1Service);
  132. #endif
  133. }
  134. #endif
  135. #if ENABLED(_useTimer3)
  136. if (timer == _timer3) {
  137. TCCR3A = 0; // normal counting mode
  138. TCCR3B = _BV(CS31); // set prescaler of 8
  139. TCNT3 = 0; // clear the timer count
  140. #ifdef __AVR_ATmega128__
  141. SBI(TIFR, OCF3A); // clear any pending interrupts;
  142. SBI(ETIMSK, OCIE3A); // enable the output compare interrupt
  143. #else
  144. SBI(TIFR3, OCF3A); // clear any pending interrupts;
  145. SBI(TIMSK3, OCIE3A); // enable the output compare interrupt
  146. #endif
  147. #ifdef WIRING
  148. timerAttach(TIMER3OUTCOMPAREA_INT, Timer3Service); // for Wiring platform only
  149. #endif
  150. }
  151. #endif
  152. #if ENABLED(_useTimer4)
  153. if (timer == _timer4) {
  154. TCCR4A = 0; // normal counting mode
  155. TCCR4B = _BV(CS41); // set prescaler of 8
  156. TCNT4 = 0; // clear the timer count
  157. TIFR4 = _BV(OCF4A); // clear any pending interrupts;
  158. TIMSK4 = _BV(OCIE4A); // enable the output compare interrupt
  159. }
  160. #endif
  161. #if ENABLED(_useTimer5)
  162. if (timer == _timer5) {
  163. TCCR5A = 0; // normal counting mode
  164. TCCR5B = _BV(CS51); // set prescaler of 8
  165. TCNT5 = 0; // clear the timer count
  166. TIFR5 = _BV(OCF5A); // clear any pending interrupts;
  167. TIMSK5 = _BV(OCIE5A); // enable the output compare interrupt
  168. }
  169. #endif
  170. }
  171. static void finISR(timer16_Sequence_t timer) {
  172. // Disable use of the given timer
  173. #ifdef WIRING
  174. if (timer == _timer1) {
  175. CBI(
  176. #if defined(__AVR_ATmega1281__) || defined(__AVR_ATmega2561__)
  177. TIMSK1
  178. #else
  179. TIMSK
  180. #endif
  181. , OCIE1A); // disable timer 1 output compare interrupt
  182. timerDetach(TIMER1OUTCOMPAREA_INT);
  183. }
  184. else if (timer == _timer3) {
  185. CBI(
  186. #if defined(__AVR_ATmega1281__) || defined(__AVR_ATmega2561__)
  187. TIMSK3
  188. #else
  189. ETIMSK
  190. #endif
  191. , OCIE3A); // disable the timer3 output compare A interrupt
  192. timerDetach(TIMER3OUTCOMPAREA_INT);
  193. }
  194. #else // !WIRING
  195. // For arduino - in future: call here to a currently undefined function to reset the timer
  196. UNUSED(timer);
  197. #endif
  198. }
  199. static bool isTimerActive(timer16_Sequence_t timer) {
  200. // returns true if any servo is active on this timer
  201. for (uint8_t channel = 0; channel < SERVOS_PER_TIMER; channel++) {
  202. if (SERVO(timer, channel).Pin.isActive)
  203. return true;
  204. }
  205. return false;
  206. }
  207. /****************** end of static functions ******************************/
  208. Servo::Servo() {
  209. if (ServoCount < MAX_SERVOS) {
  210. this->servoIndex = ServoCount++; // assign a servo index to this instance
  211. servo_info[this->servoIndex].ticks = usToTicks(DEFAULT_PULSE_WIDTH); // store default values - 12 Aug 2009
  212. }
  213. else
  214. this->servoIndex = INVALID_SERVO; // too many servos
  215. }
  216. int8_t Servo::attach(int pin) {
  217. return this->attach(pin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH);
  218. }
  219. int8_t Servo::attach(int pin, int min, int max) {
  220. if (this->servoIndex >= MAX_SERVOS) return -1;
  221. if (pin > 0) servo_info[this->servoIndex].Pin.nbr = pin;
  222. pinMode(servo_info[this->servoIndex].Pin.nbr, OUTPUT); // set servo pin to output
  223. // todo min/max check: abs(min - MIN_PULSE_WIDTH) /4 < 128
  224. this->min = (MIN_PULSE_WIDTH - min) / 4; //resolution of min/max is 4 uS
  225. this->max = (MAX_PULSE_WIDTH - max) / 4;
  226. // initialize the timer if it has not already been initialized
  227. timer16_Sequence_t timer = SERVO_INDEX_TO_TIMER(servoIndex);
  228. if (!isTimerActive(timer)) initISR(timer);
  229. servo_info[this->servoIndex].Pin.isActive = true; // this must be set after the check for isTimerActive
  230. return this->servoIndex;
  231. }
  232. void Servo::detach() {
  233. servo_info[this->servoIndex].Pin.isActive = false;
  234. timer16_Sequence_t timer = SERVO_INDEX_TO_TIMER(servoIndex);
  235. if (!isTimerActive(timer)) finISR(timer);
  236. }
  237. void Servo::write(int value) {
  238. if (value < MIN_PULSE_WIDTH) { // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds)
  239. value = map(constrain(value, 0, 180), 0, 180, SERVO_MIN(), SERVO_MAX());
  240. }
  241. this->writeMicroseconds(value);
  242. }
  243. void Servo::writeMicroseconds(int value) {
  244. // calculate and store the values for the given channel
  245. byte channel = this->servoIndex;
  246. if (channel < MAX_SERVOS) { // ensure channel is valid
  247. // ensure pulse width is valid
  248. value = constrain(value, SERVO_MIN(), SERVO_MAX()) - (TRIM_DURATION);
  249. value = usToTicks(value); // convert to ticks after compensating for interrupt overhead - 12 Aug 2009
  250. CRITICAL_SECTION_START;
  251. servo_info[channel].ticks = value;
  252. CRITICAL_SECTION_END;
  253. }
  254. }
  255. // return the value as degrees
  256. int Servo::read() { return map(this->readMicroseconds() + 1, SERVO_MIN(), SERVO_MAX(), 0, 180); }
  257. int Servo::readMicroseconds() {
  258. return (this->servoIndex == INVALID_SERVO) ? 0 : ticksToUs(servo_info[this->servoIndex].ticks) + TRIM_DURATION;
  259. }
  260. bool Servo::attached() { return servo_info[this->servoIndex].Pin.isActive; }
  261. void Servo::move(int value) {
  262. constexpr uint16_t servo_delay[] = SERVO_DELAY;
  263. static_assert(COUNT(servo_delay) == NUM_SERVOS, "SERVO_DELAY must be an array NUM_SERVOS long.");
  264. if (this->attach(0) >= 0) {
  265. this->write(value);
  266. delay(servo_delay[this->servoIndex]);
  267. #if ENABLED(DEACTIVATE_SERVOS_AFTER_MOVE)
  268. this->detach();
  269. #endif
  270. }
  271. }
  272. #endif