PlatformIO package of the Teensy core framework compatible with GCC 10 & C++20
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

845 lines
24KB

  1. /*
  2. Servo.cpp - Interrupt driven Servo library for Arduino using 16 bit timers- Version 2
  3. Copyright (c) 2009 Michael Margolis. All right reserved.
  4. This library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. This library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with this library; if not, write to the Free Software
  14. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  15. */
  16. /*
  17. A servo is activated by creating an instance of the Servo class passing the desired pin to the attach() method.
  18. The servos are pulsed in the background using the value most recently written using the write() method
  19. Note that analogWrite of PWM on pins associated with the timer are disabled when the first servo is attached.
  20. Timers are seized as needed in groups of 12 servos - 24 servos use two timers, 48 servos will use four.
  21. The methods are:
  22. Servo - Class for manipulating servo motors connected to Arduino pins.
  23. attach(pin ) - Attaches a servo motor to an i/o pin.
  24. attach(pin, min, max ) - Attaches to a pin setting min and max values in microseconds
  25. default min is 544, max is 2400
  26. write() - Sets the servo angle in degrees. (invalid angle that is valid as pulse in microseconds is treated as microseconds)
  27. writeMicroseconds() - Sets the servo pulse width in microseconds
  28. read() - Gets the last written servo pulse width as an angle between 0 and 180.
  29. readMicroseconds() - Gets the last written servo pulse width in microseconds. (was read_us() in first release)
  30. attached() - Returns true if there is a servo attached.
  31. detach() - Stops an attached servos from pulsing its i/o pin.
  32. */
  33. #if defined(__AVR__)
  34. #include <avr/interrupt.h>
  35. #include <Arduino.h>
  36. #include "Servo.h"
  37. #define usToTicks(_us) (( clockCyclesPerMicrosecond()* _us) / 8) // converts microseconds to tick (assumes prescale of 8) // 12 Aug 2009
  38. #define ticksToUs(_ticks) (( (unsigned)_ticks * 8)/ clockCyclesPerMicrosecond() ) // converts from ticks back to microseconds
  39. #define TRIM_DURATION 2 // compensation ticks to trim adjust for digitalWrite delays // 12 August 2009
  40. //#define NBR_TIMERS (MAX_SERVOS / SERVOS_PER_TIMER)
  41. static servo_t servos[MAX_SERVOS]; // static array of servo structures
  42. static volatile int8_t Channel[_Nbr_16timers ]; // counter for the servo being pulsed for each timer (or -1 if refresh interval)
  43. uint8_t ServoCount = 0; // the total number of attached servos
  44. // convenience macros
  45. #define SERVO_INDEX_TO_TIMER(_servo_nbr) ((timer16_Sequence_t)(_servo_nbr / SERVOS_PER_TIMER)) // returns the timer controlling this servo
  46. #define SERVO_INDEX_TO_CHANNEL(_servo_nbr) (_servo_nbr % SERVOS_PER_TIMER) // returns the index of the servo on this timer
  47. #define SERVO_INDEX(_timer,_channel) ((_timer*SERVOS_PER_TIMER) + _channel) // macro to access servo index by timer and channel
  48. #define SERVO(_timer,_channel) (servos[SERVO_INDEX(_timer,_channel)]) // macro to access servo class by timer and channel
  49. #define SERVO_MIN() (MIN_PULSE_WIDTH - this->min * 4) // minimum value in uS for this servo
  50. #define SERVO_MAX() (MAX_PULSE_WIDTH - this->max * 4) // maximum value in uS for this servo
  51. /************ static functions common to all instances ***********************/
  52. static inline void handle_interrupts(timer16_Sequence_t timer, volatile uint16_t *TCNTn, volatile uint16_t* OCRnA)
  53. {
  54. if( Channel[timer] < 0 )
  55. *TCNTn = 0; // channel set to -1 indicated that refresh interval completed so reset the timer
  56. else{
  57. if( SERVO_INDEX(timer,Channel[timer]) < ServoCount && SERVO(timer,Channel[timer]).Pin.isActive == true )
  58. digitalWrite( SERVO(timer,Channel[timer]).Pin.nbr,LOW); // pulse this channel low if activated
  59. }
  60. Channel[timer]++; // increment to the next channel
  61. if( SERVO_INDEX(timer,Channel[timer]) < ServoCount && Channel[timer] < SERVOS_PER_TIMER) {
  62. *OCRnA = *TCNTn + SERVO(timer,Channel[timer]).ticks;
  63. if(SERVO(timer,Channel[timer]).Pin.isActive == true) // check if activated
  64. digitalWrite( SERVO(timer,Channel[timer]).Pin.nbr,HIGH); // its an active channel so pulse it high
  65. }
  66. else {
  67. // finished all channels so wait for the refresh period to expire before starting over
  68. if( ((unsigned)*TCNTn) + 4 < usToTicks(REFRESH_INTERVAL) ) // allow a few ticks to ensure the next OCR1A not missed
  69. *OCRnA = (unsigned int)usToTicks(REFRESH_INTERVAL);
  70. else
  71. *OCRnA = *TCNTn + 4; // at least REFRESH_INTERVAL has elapsed
  72. Channel[timer] = -1; // this will get incremented at the end of the refresh period to start again at the first channel
  73. }
  74. }
  75. #ifndef WIRING // Wiring pre-defines signal handlers so don't define any if compiling for the Wiring platform
  76. // Interrupt handlers for Arduino
  77. #if defined(_useTimer1)
  78. SIGNAL (TIMER1_COMPA_vect)
  79. {
  80. handle_interrupts(_timer1, &TCNT1, &OCR1A);
  81. }
  82. #endif
  83. #if defined(_useTimer3)
  84. SIGNAL (TIMER3_COMPA_vect)
  85. {
  86. handle_interrupts(_timer3, &TCNT3, &OCR3A);
  87. }
  88. #endif
  89. #if defined(_useTimer4)
  90. SIGNAL (TIMER4_COMPA_vect)
  91. {
  92. handle_interrupts(_timer4, &TCNT4, &OCR4A);
  93. }
  94. #endif
  95. #if defined(_useTimer5)
  96. SIGNAL (TIMER5_COMPA_vect)
  97. {
  98. handle_interrupts(_timer5, &TCNT5, &OCR5A);
  99. }
  100. #endif
  101. #elif defined WIRING
  102. // Interrupt handlers for Wiring
  103. #if defined(_useTimer1)
  104. void Timer1Service()
  105. {
  106. handle_interrupts(_timer1, &TCNT1, &OCR1A);
  107. }
  108. #endif
  109. #if defined(_useTimer3)
  110. void Timer3Service()
  111. {
  112. handle_interrupts(_timer3, &TCNT3, &OCR3A);
  113. }
  114. #endif
  115. #endif
  116. static void initISR(timer16_Sequence_t timer)
  117. {
  118. #if defined (_useTimer1)
  119. if(timer == _timer1) {
  120. TCCR1A = 0; // normal counting mode
  121. TCCR1B = _BV(CS11); // set prescaler of 8
  122. TCNT1 = 0; // clear the timer count
  123. #if defined(__AVR_ATmega8__)|| defined(__AVR_ATmega128__)
  124. TIFR |= _BV(OCF1A); // clear any pending interrupts;
  125. TIMSK |= _BV(OCIE1A) ; // enable the output compare interrupt
  126. #else
  127. // here if not ATmega8 or ATmega128
  128. TIFR1 |= _BV(OCF1A); // clear any pending interrupts;
  129. TIMSK1 |= _BV(OCIE1A) ; // enable the output compare interrupt
  130. #endif
  131. #if defined(WIRING)
  132. timerAttach(TIMER1OUTCOMPAREA_INT, Timer1Service);
  133. #endif
  134. }
  135. #endif
  136. #if defined (_useTimer3)
  137. if(timer == _timer3) {
  138. TCCR3A = 0; // normal counting mode
  139. TCCR3B = _BV(CS31); // set prescaler of 8
  140. TCNT3 = 0; // clear the timer count
  141. #if defined(__AVR_ATmega128__)
  142. TIFR |= _BV(OCF3A); // clear any pending interrupts;
  143. ETIMSK |= _BV(OCIE3A); // enable the output compare interrupt
  144. #else
  145. TIFR3 = _BV(OCF3A); // clear any pending interrupts;
  146. TIMSK3 = _BV(OCIE3A) ; // enable the output compare interrupt
  147. #endif
  148. #if defined(WIRING)
  149. timerAttach(TIMER3OUTCOMPAREA_INT, Timer3Service); // for Wiring platform only
  150. #endif
  151. }
  152. #endif
  153. #if defined (_useTimer4)
  154. if(timer == _timer4) {
  155. TCCR4A = 0; // normal counting mode
  156. TCCR4B = _BV(CS41); // set prescaler of 8
  157. TCNT4 = 0; // clear the timer count
  158. TIFR4 = _BV(OCF4A); // clear any pending interrupts;
  159. TIMSK4 = _BV(OCIE4A) ; // enable the output compare interrupt
  160. }
  161. #endif
  162. #if defined (_useTimer5)
  163. if(timer == _timer5) {
  164. TCCR5A = 0; // normal counting mode
  165. TCCR5B = _BV(CS51); // set prescaler of 8
  166. TCNT5 = 0; // clear the timer count
  167. TIFR5 = _BV(OCF5A); // clear any pending interrupts;
  168. TIMSK5 = _BV(OCIE5A) ; // enable the output compare interrupt
  169. }
  170. #endif
  171. }
  172. static void finISR(timer16_Sequence_t timer)
  173. {
  174. //disable use of the given timer
  175. #if defined WIRING // Wiring
  176. if(timer == _timer1) {
  177. #if defined(__AVR_ATmega1281__)||defined(__AVR_ATmega2561__)
  178. TIMSK1 &= ~_BV(OCIE1A) ; // disable timer 1 output compare interrupt
  179. #else
  180. TIMSK &= ~_BV(OCIE1A) ; // disable timer 1 output compare interrupt
  181. #endif
  182. timerDetach(TIMER1OUTCOMPAREA_INT);
  183. }
  184. else if(timer == _timer3) {
  185. #if defined(__AVR_ATmega1281__)||defined(__AVR_ATmega2561__)
  186. TIMSK3 &= ~_BV(OCIE3A); // disable the timer3 output compare A interrupt
  187. #else
  188. ETIMSK &= ~_BV(OCIE3A); // disable the timer3 output compare A interrupt
  189. #endif
  190. timerDetach(TIMER3OUTCOMPAREA_INT);
  191. }
  192. #else
  193. //For arduino - in future: call here to a currently undefined function to reset the timer
  194. #endif
  195. }
  196. static boolean isTimerActive(timer16_Sequence_t timer)
  197. {
  198. // returns true if any servo is active on this timer
  199. for(uint8_t channel=0; channel < SERVOS_PER_TIMER; channel++) {
  200. if(SERVO(timer,channel).Pin.isActive == true)
  201. return true;
  202. }
  203. return false;
  204. }
  205. /****************** end of static functions ******************************/
  206. Servo::Servo()
  207. {
  208. if( ServoCount < MAX_SERVOS) {
  209. this->servoIndex = ServoCount++; // assign a servo index to this instance
  210. servos[this->servoIndex].ticks = usToTicks(DEFAULT_PULSE_WIDTH); // store default values - 12 Aug 2009
  211. }
  212. else
  213. this->servoIndex = INVALID_SERVO ; // too many servos
  214. }
  215. uint8_t Servo::attach(int pin)
  216. {
  217. return this->attach(pin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH);
  218. }
  219. uint8_t Servo::attach(int pin, int min, int max)
  220. {
  221. if(this->servoIndex < MAX_SERVOS ) {
  222. pinMode( pin, OUTPUT) ; // set servo pin to output
  223. servos[this->servoIndex].Pin.nbr = pin;
  224. // todo min/max check: abs(min - MIN_PULSE_WIDTH) /4 < 128
  225. this->min = (MIN_PULSE_WIDTH - min)/4; //resolution of min/max is 4 uS
  226. this->max = (MAX_PULSE_WIDTH - max)/4;
  227. // initialize the timer if it has not already been initialized
  228. timer16_Sequence_t timer = SERVO_INDEX_TO_TIMER(servoIndex);
  229. if(isTimerActive(timer) == false)
  230. initISR(timer);
  231. servos[this->servoIndex].Pin.isActive = true; // this must be set after the check for isTimerActive
  232. }
  233. return this->servoIndex ;
  234. }
  235. void Servo::detach()
  236. {
  237. servos[this->servoIndex].Pin.isActive = false;
  238. timer16_Sequence_t timer = SERVO_INDEX_TO_TIMER(servoIndex);
  239. if(isTimerActive(timer) == false) {
  240. finISR(timer);
  241. }
  242. }
  243. void Servo::write(int value)
  244. {
  245. if(value < MIN_PULSE_WIDTH)
  246. { // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds)
  247. if(value < 0) value = 0;
  248. if(value > 180) value = 180;
  249. value = map(value, 0, 180, SERVO_MIN(), SERVO_MAX());
  250. }
  251. this->writeMicroseconds(value);
  252. }
  253. void Servo::writeMicroseconds(int value)
  254. {
  255. // calculate and store the values for the given channel
  256. byte channel = this->servoIndex;
  257. if( (channel < MAX_SERVOS) ) // ensure channel is valid
  258. {
  259. if( value < SERVO_MIN() ) // ensure pulse width is valid
  260. value = SERVO_MIN();
  261. else if( value > SERVO_MAX() )
  262. value = SERVO_MAX();
  263. value = value - TRIM_DURATION;
  264. value = usToTicks(value); // convert to ticks after compensating for interrupt overhead - 12 Aug 2009
  265. uint8_t oldSREG = SREG;
  266. cli();
  267. servos[channel].ticks = value;
  268. SREG = oldSREG;
  269. }
  270. }
  271. int Servo::read() // return the value as degrees
  272. {
  273. return map( this->readMicroseconds()+1, SERVO_MIN(), SERVO_MAX(), 0, 180);
  274. }
  275. int Servo::readMicroseconds()
  276. {
  277. unsigned int pulsewidth;
  278. if( this->servoIndex != INVALID_SERVO )
  279. pulsewidth = ticksToUs(servos[this->servoIndex].ticks) + TRIM_DURATION ; // 12 aug 2009
  280. else
  281. pulsewidth = 0;
  282. return pulsewidth;
  283. }
  284. bool Servo::attached()
  285. {
  286. return servos[this->servoIndex].Pin.isActive ;
  287. }
  288. #elif defined(__arm__) && (defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK64FX512__) || defined(__MK66FX1M0__))
  289. // ******************************************************************************
  290. // Teensy 3.0 implementation, using Programmable Delay Block
  291. // ******************************************************************************
  292. #include <Arduino.h>
  293. #include "Servo.h"
  294. #define PDB_CONFIG (PDB_SC_TRGSEL(15) | PDB_SC_PDBEN | PDB_SC_PDBIE \
  295. | PDB_SC_CONT | PDB_SC_PRESCALER(2) | PDB_SC_MULT(0))
  296. #define PDB_PRESCALE 4 //
  297. #define usToTicks(us) ((us) * (F_BUS / 1000) / PDB_PRESCALE / 1000)
  298. #define ticksToUs(ticks) ((ticks) * PDB_PRESCALE * 1000 / (F_BUS / 1000))
  299. #if SERVOS_PER_TIMER <= 16
  300. static uint16_t servo_active_mask = 0;
  301. static uint16_t servo_allocated_mask = 0;
  302. #else
  303. static uint32_t servo_active_mask = 0;
  304. static uint32_t servo_allocated_mask = 0;
  305. #endif
  306. static uint8_t servo_pin[MAX_SERVOS];
  307. static uint16_t servo_ticks[MAX_SERVOS];
  308. Servo::Servo()
  309. {
  310. uint16_t mask;
  311. servoIndex = 0;
  312. for (mask=1; mask < (1<<MAX_SERVOS); mask <<= 1) {
  313. if (!(servo_allocated_mask & mask)) {
  314. servo_allocated_mask |= mask;
  315. servo_active_mask &= ~mask;
  316. return;
  317. }
  318. servoIndex++;
  319. }
  320. servoIndex = INVALID_SERVO;
  321. }
  322. uint8_t Servo::attach(int pin)
  323. {
  324. return attach(pin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH);
  325. }
  326. uint8_t Servo::attach(int pin, int minimum, int maximum)
  327. {
  328. if (servoIndex < MAX_SERVOS) {
  329. pinMode(pin, OUTPUT);
  330. servo_pin[servoIndex] = pin;
  331. servo_ticks[servoIndex] = usToTicks(DEFAULT_PULSE_WIDTH);
  332. servo_active_mask |= (1<<servoIndex);
  333. min_ticks = usToTicks(minimum);
  334. max_ticks = usToTicks(maximum);
  335. if (!(SIM_SCGC6 & SIM_SCGC6_PDB)) {
  336. SIM_SCGC6 |= SIM_SCGC6_PDB; // TODO: use bitband for atomic bitset
  337. PDB0_MOD = 0xFFFF;
  338. PDB0_CNT = 0;
  339. PDB0_IDLY = 0;
  340. PDB0_SC = PDB_CONFIG;
  341. // TODO: maybe this should be a higher priority than most
  342. // other interrupts (init all to some default?)
  343. PDB0_SC = PDB_CONFIG | PDB_SC_SWTRIG;
  344. NVIC_SET_PRIORITY(IRQ_PDB, 32);
  345. }
  346. NVIC_ENABLE_IRQ(IRQ_PDB);
  347. }
  348. return servoIndex;
  349. }
  350. void Servo::detach()
  351. {
  352. if (servoIndex >= MAX_SERVOS) return;
  353. servo_active_mask &= ~(1<<servoIndex);
  354. servo_allocated_mask &= ~(1<<servoIndex);
  355. if (servo_active_mask == 0) {
  356. NVIC_DISABLE_IRQ(IRQ_PDB);
  357. }
  358. }
  359. void Servo::write(int value)
  360. {
  361. if (servoIndex >= MAX_SERVOS) return;
  362. if (value >= MIN_PULSE_WIDTH) {
  363. writeMicroseconds(value);
  364. return;
  365. } else if (value > 180) {
  366. value = 180;
  367. } else if (value < 0) {
  368. value = 0;
  369. }
  370. if (servoIndex >= MAX_SERVOS) return;
  371. servo_ticks[servoIndex] = map(value, 0, 180, min_ticks, max_ticks);
  372. }
  373. void Servo::writeMicroseconds(int value)
  374. {
  375. value = usToTicks(value);
  376. if (value < min_ticks) {
  377. value = min_ticks;
  378. } else if (value > max_ticks) {
  379. value = max_ticks;
  380. }
  381. if (servoIndex >= MAX_SERVOS) return;
  382. servo_ticks[servoIndex] = value;
  383. }
  384. int Servo::read() // return the value as degrees
  385. {
  386. if (servoIndex >= MAX_SERVOS) return 0;
  387. return map(servo_ticks[servoIndex], min_ticks, max_ticks, 0, 180);
  388. }
  389. int Servo::readMicroseconds()
  390. {
  391. if (servoIndex >= MAX_SERVOS) return 0;
  392. return ticksToUs(servo_ticks[servoIndex]);
  393. }
  394. bool Servo::attached()
  395. {
  396. if (servoIndex >= MAX_SERVOS) return 0;
  397. return servo_active_mask & (1<<servoIndex);
  398. }
  399. extern "C" void pdb_isr(void)
  400. {
  401. static int8_t channel=0, channel_high=MAX_SERVOS;
  402. static uint32_t tick_accum=0;
  403. uint32_t ticks;
  404. int32_t wait_ticks;
  405. // first, if any channel was left high from the previous
  406. // run, now is the time to shut it off
  407. if (servo_active_mask & (1<<channel_high)) {
  408. digitalWrite(servo_pin[channel_high], LOW);
  409. channel_high = MAX_SERVOS;
  410. }
  411. // search for the next channel to turn on
  412. while (channel < MAX_SERVOS) {
  413. if (servo_active_mask & (1<<channel)) {
  414. digitalWrite(servo_pin[channel], HIGH);
  415. channel_high = channel;
  416. ticks = servo_ticks[channel];
  417. tick_accum += ticks;
  418. PDB0_IDLY += ticks;
  419. PDB0_SC = PDB_CONFIG | PDB_SC_LDOK;
  420. channel++;
  421. return;
  422. }
  423. channel++;
  424. }
  425. // when all channels have output, wait for the
  426. // minimum refresh interval
  427. wait_ticks = usToTicks(REFRESH_INTERVAL) - tick_accum;
  428. if (wait_ticks < usToTicks(100)) wait_ticks = usToTicks(100);
  429. else if (wait_ticks > 60000) wait_ticks = 60000;
  430. tick_accum += wait_ticks;
  431. PDB0_IDLY += wait_ticks;
  432. PDB0_SC = PDB_CONFIG | PDB_SC_LDOK;
  433. // if this wait is enough to satisfy the refresh
  434. // interval, next time begin again at channel zero
  435. if (tick_accum >= usToTicks(REFRESH_INTERVAL)) {
  436. tick_accum = 0;
  437. channel = 0;
  438. }
  439. }
  440. #elif defined(__arm__) && defined(__MKL26Z64__)
  441. // ******************************************************************************
  442. // Teensy-LC implementation, using Low Power Timer
  443. // ******************************************************************************
  444. #include <Arduino.h>
  445. #include "Servo.h"
  446. #define LPTMR_CONFIG LPTMR_CSR_TIE | LPTMR_CSR_TFC | LPTMR_CSR_TEN
  447. #define usToTicks(us) ((us) * 8)
  448. #define ticksToUs(ticks) ((ticks) / 8)
  449. #if SERVOS_PER_TIMER <= 16
  450. static uint16_t servo_active_mask = 0;
  451. static uint16_t servo_allocated_mask = 0;
  452. #else
  453. static uint32_t servo_active_mask = 0;
  454. static uint32_t servo_allocated_mask = 0;
  455. #endif
  456. static uint8_t servo_pin[MAX_SERVOS];
  457. static uint16_t servo_ticks[MAX_SERVOS];
  458. Servo::Servo()
  459. {
  460. uint16_t mask;
  461. servoIndex = 0;
  462. for (mask=1; mask < (1<<MAX_SERVOS); mask <<= 1) {
  463. if (!(servo_allocated_mask & mask)) {
  464. servo_allocated_mask |= mask;
  465. servo_active_mask &= ~mask;
  466. return;
  467. }
  468. servoIndex++;
  469. }
  470. servoIndex = INVALID_SERVO;
  471. }
  472. uint8_t Servo::attach(int pin)
  473. {
  474. return attach(pin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH);
  475. }
  476. uint8_t Servo::attach(int pin, int minimum, int maximum)
  477. {
  478. if (servoIndex < MAX_SERVOS) {
  479. pinMode(pin, OUTPUT);
  480. servo_pin[servoIndex] = pin;
  481. servo_ticks[servoIndex] = usToTicks(DEFAULT_PULSE_WIDTH);
  482. servo_active_mask |= (1<<servoIndex);
  483. min_ticks = usToTicks(minimum);
  484. max_ticks = usToTicks(maximum);
  485. if (!(SIM_SCGC5 & SIM_SCGC5_LPTIMER)) {
  486. SIM_SCGC5 |= SIM_SCGC5_LPTIMER; // TODO: use BME
  487. OSC0_CR |= OSC_ERCLKEN;
  488. LPTMR0_CSR = 0;
  489. LPTMR0_PSR = LPTMR_PSR_PRESCALE(0) | LPTMR_PSR_PCS(3); // 8 MHz
  490. LPTMR0_CMR = 1;
  491. LPTMR0_CSR = LPTMR_CONFIG;
  492. NVIC_SET_PRIORITY(IRQ_LPTMR, 32);
  493. }
  494. NVIC_ENABLE_IRQ(IRQ_LPTMR);
  495. }
  496. return servoIndex;
  497. }
  498. void Servo::detach()
  499. {
  500. if (servoIndex >= MAX_SERVOS) return;
  501. servo_active_mask &= ~(1<<servoIndex);
  502. servo_allocated_mask &= ~(1<<servoIndex);
  503. if (servo_active_mask == 0) {
  504. NVIC_DISABLE_IRQ(IRQ_LPTMR);
  505. }
  506. }
  507. void Servo::write(int value)
  508. {
  509. if (servoIndex >= MAX_SERVOS) return;
  510. if (value >= MIN_PULSE_WIDTH) {
  511. writeMicroseconds(value);
  512. return;
  513. } else if (value > 180) {
  514. value = 180;
  515. } else if (value < 0) {
  516. value = 0;
  517. }
  518. if (servoIndex >= MAX_SERVOS) return;
  519. servo_ticks[servoIndex] = map(value, 0, 180, min_ticks, max_ticks);
  520. }
  521. void Servo::writeMicroseconds(int value)
  522. {
  523. value = usToTicks(value);
  524. if (value < min_ticks) {
  525. value = min_ticks;
  526. } else if (value > max_ticks) {
  527. value = max_ticks;
  528. }
  529. if (servoIndex >= MAX_SERVOS) return;
  530. servo_ticks[servoIndex] = value;
  531. }
  532. int Servo::read() // return the value as degrees
  533. {
  534. if (servoIndex >= MAX_SERVOS) return 0;
  535. return map(servo_ticks[servoIndex], min_ticks, max_ticks, 0, 180);
  536. }
  537. int Servo::readMicroseconds()
  538. {
  539. if (servoIndex >= MAX_SERVOS) return 0;
  540. return ticksToUs(servo_ticks[servoIndex]);
  541. }
  542. bool Servo::attached()
  543. {
  544. if (servoIndex >= MAX_SERVOS) return 0;
  545. return servo_active_mask & (1<<servoIndex);
  546. }
  547. void lptmr_isr(void)
  548. {
  549. static int8_t channel=0, channel_high=MAX_SERVOS;
  550. static uint32_t tick_accum=0;
  551. uint32_t ticks;
  552. int32_t wait_ticks;
  553. // first, if any channel was left high from the previous
  554. // run, now is the time to shut it off
  555. if (servo_active_mask & (1<<channel_high)) {
  556. digitalWrite(servo_pin[channel_high], LOW);
  557. channel_high = MAX_SERVOS;
  558. }
  559. // search for the next channel to turn on
  560. while (channel < MAX_SERVOS) {
  561. if (servo_active_mask & (1<<channel)) {
  562. digitalWrite(servo_pin[channel], HIGH);
  563. channel_high = channel;
  564. ticks = servo_ticks[channel];
  565. tick_accum += ticks;
  566. LPTMR0_CMR += ticks;
  567. LPTMR0_CSR = LPTMR_CONFIG | LPTMR_CSR_TCF;
  568. channel++;
  569. return;
  570. }
  571. channel++;
  572. }
  573. // when all channels have output, wait for the
  574. // minimum refresh interval
  575. wait_ticks = usToTicks(REFRESH_INTERVAL) - tick_accum;
  576. if (wait_ticks < usToTicks(100)) wait_ticks = usToTicks(100);
  577. else if (wait_ticks > 60000) wait_ticks = 60000;
  578. tick_accum += wait_ticks;
  579. LPTMR0_CMR += wait_ticks;
  580. LPTMR0_CSR = LPTMR_CONFIG | LPTMR_CSR_TCF;
  581. // if this wait is enough to satisfy the refresh
  582. // interval, next time begin again at channel zero
  583. if (tick_accum >= usToTicks(REFRESH_INTERVAL)) {
  584. tick_accum = 0;
  585. channel = 0;
  586. }
  587. }
  588. #elif defined(__arm__) && (defined(__IMXRT1052__) || defined(__IMXRT1062__))
  589. // ******************************************************************************
  590. // Teensy generic implementation, using IntervalTimer
  591. // ******************************************************************************
  592. #include <Arduino.h>
  593. #include <IntervalTimer.h>
  594. #include "Servo.h"
  595. #include "debug/printf.h"
  596. #define usToTicks(us) ((us) * 16)
  597. #define ticksToUs(ticks) ((ticks) / 16)
  598. #define ticksToUs_f(t) ((float)(t) * 0.0625f)
  599. static uint32_t servo_active_mask = 0;
  600. static uint32_t servo_allocated_mask = 0;
  601. static uint8_t servo_pin[MAX_SERVOS];
  602. static uint16_t servo_ticks[MAX_SERVOS];
  603. static IntervalTimer timer;
  604. static void isr(void);
  605. Servo::Servo()
  606. {
  607. uint16_t mask;
  608. servoIndex = 0;
  609. for (mask=1; mask < (1<<MAX_SERVOS); mask <<= 1) {
  610. if (!(servo_allocated_mask & mask)) {
  611. servo_allocated_mask |= mask;
  612. servo_active_mask &= ~mask;
  613. return;
  614. }
  615. servoIndex++;
  616. }
  617. servoIndex = INVALID_SERVO;
  618. }
  619. uint8_t Servo::attach(int pin)
  620. {
  621. return attach(pin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH);
  622. }
  623. uint8_t Servo::attach(int pin, int minimum, int maximum)
  624. {
  625. if (servoIndex < MAX_SERVOS) {
  626. pinMode(pin, OUTPUT);
  627. servo_pin[servoIndex] = pin;
  628. servo_ticks[servoIndex] = usToTicks(DEFAULT_PULSE_WIDTH);
  629. servo_active_mask |= (1<<servoIndex);
  630. min_ticks = usToTicks(minimum);
  631. max_ticks = usToTicks(maximum);
  632. if ((IRQ_NUMBER_t)timer >= NVIC_NUM_INTERRUPTS) {
  633. timer.begin(isr, 10);
  634. }
  635. }
  636. return servoIndex;
  637. }
  638. void Servo::detach()
  639. {
  640. if (servoIndex >= MAX_SERVOS) return;
  641. servo_active_mask &= ~(1<<servoIndex);
  642. servo_allocated_mask &= ~(1<<servoIndex);
  643. if (servo_active_mask == 0) {
  644. timer.end();
  645. }
  646. }
  647. void Servo::write(int value)
  648. {
  649. if (servoIndex >= MAX_SERVOS) return;
  650. if (value >= MIN_PULSE_WIDTH) {
  651. writeMicroseconds(value);
  652. return;
  653. } else if (value > 180) {
  654. value = 180;
  655. } else if (value < 0) {
  656. value = 0;
  657. }
  658. if (servoIndex >= MAX_SERVOS) return;
  659. servo_ticks[servoIndex] = map(value, 0, 180, min_ticks, max_ticks);
  660. }
  661. void Servo::writeMicroseconds(int value)
  662. {
  663. value = usToTicks(value);
  664. if (value < min_ticks) {
  665. value = min_ticks;
  666. } else if (value > max_ticks) {
  667. value = max_ticks;
  668. }
  669. if (servoIndex >= MAX_SERVOS) return;
  670. servo_ticks[servoIndex] = value;
  671. }
  672. int Servo::read() // return the value as degrees
  673. {
  674. if (servoIndex >= MAX_SERVOS) return 0;
  675. return map(servo_ticks[servoIndex], min_ticks, max_ticks, 0, 180);
  676. }
  677. int Servo::readMicroseconds()
  678. {
  679. if (servoIndex >= MAX_SERVOS) return 0;
  680. return ticksToUs(servo_ticks[servoIndex]);
  681. }
  682. bool Servo::attached()
  683. {
  684. if (servoIndex >= MAX_SERVOS) return 0;
  685. return servo_active_mask & (1<<servoIndex);
  686. }
  687. static void isr(void)
  688. {
  689. static uint8_t channel=MAX_SERVOS;
  690. static uint8_t next_low=255;
  691. static uint32_t tick_accum=0;
  692. // If a pin is still HIGH from a prior run, turn it off
  693. if (next_low < 255) {
  694. digitalWrite(next_low, LOW);
  695. }
  696. // If we're on an active channel, drive it HIGH
  697. if (channel < MAX_SERVOS && (servo_active_mask & (1<<channel))) {
  698. uint8_t pin = servo_pin[channel];
  699. digitalWrite(pin, HIGH);
  700. next_low = pin;
  701. } else {
  702. next_low = 255;
  703. }
  704. // Generate an oscilloscope trigger pulse at beginning
  705. //if (channel == __builtin_ctz(servo_active_mask)) {
  706. //digitalWrite(2, HIGH);
  707. //delayMicroseconds(1);
  708. //digitalWrite(2, LOW);
  709. //}
  710. // Find the next channel and set the timer up
  711. if (++channel >= MAX_SERVOS) {
  712. channel = 0;
  713. }
  714. do {
  715. if (servo_active_mask & (1<<channel)) {
  716. uint32_t ticks = servo_ticks[channel];
  717. tick_accum += ticks;
  718. timer.update(ticksToUs_f(ticks));
  719. return;
  720. }
  721. channel++;
  722. } while (channel < MAX_SERVOS);
  723. // when all channels have output, wait for the refresh interval
  724. if (tick_accum < usToTicks(REFRESH_INTERVAL)) {
  725. timer.update(ticksToUs_f(usToTicks(REFRESH_INTERVAL) - tick_accum));
  726. } else {
  727. timer.update(ticksToUs_f(100));
  728. }
  729. tick_accum = 0;
  730. }
  731. #endif