Professional Documents
Culture Documents
Servo Controller
Servo Controller
Servo Controller
1 period = 0.5us
*/
// 2ms = 0.5 us * 4000 (can be adapted to needs)
const unsigned int samplePeriod = 4000;
/* Pins */
// pulse 0
const byte ocr1bPin = 12;
// pulse 1
const byte ocr3bPin = 2;
// pulse 2
const byte ocr4bPin = 7;
// pulse 3
const byte ocr5bPin = 45;
// direction
const byte dir0 = 30;
const byte dir1 = 31;
const byte dir2 = 32;
const byte dir3 = 33;
void setup() {
noInterrupts();
initTimers();
interrupts();
Serial.begin(baudRate);
}
void loop() {
while (Serial.available() < 1) {
;
}
if (Serial.read() == startMark) {
while (Serial.available() < 1) {
;
}
if (Serial.read() == startMark) {
while (Serial.available() < motors * 2) {
;
}
for (int i = 0; i < motors; i++) {
targetInput[i] = mapToRange(Serial.read() << 8 | Serial.read());
}
move0(targetInput[0]);
move1(targetInput[1]);
move2(targetInput[2]);
move3(targetInput[3]);
}
}
}
void initTimers() {
// disable everything that we don't need, probably not needed
PCICR = 0;
PCMSK0 = 0;
PCMSK1 = 0;
PCMSK2 = 0;
WDTCSR = 0;
TIMSK2 = 0;
TIFR2 = 0;
TCCR2A = 0;
TCCR2B = 0;
TCNT2 = 0;
OCR2A = 0;
// The 16 bit timers that are used for generating the pulses
TCNT1 = 0;
OCR1A = 0;
OCR1B = pulseLength;
TCCR1A = 0;
TCCR1B = 0;
ICR1 = 0;
TIMSK1 = 0;
TIFR1 = 0;
TCNT3 = 0;
OCR3A = 0;
OCR3B = pulseLength;
TCCR3A = 0;
TCCR3B = 0;
ICR3 = 0;
TIMSK3 = 0;
TIFR3 = 0;
TCNT4 = 0;
OCR4A = 0;
OCR4B = pulseLength;
TCCR4A = 0;
TCCR4B = 0;
ICR4 = 0;
TIMSK4 = 0;
TIFR4 = 0;
TCNT5 = 0;
OCR5A = 0;
OCR5B = pulseLength;
TCCR5A = 0;
TCCR5B = 0;
ICR5 = 0;
TIMSK5 = 0;
TIFR5 = 0;
}
ISR(TIMER3_COMPA_vect, ISR_BLOCK) {
currentPos[1] += incPos[1];
if (stopSignal[1] || currentPos[1] == targetPos[1]) {
TCCR3B = B00011000;
TIMSK3 = 0;
isRunning[1] = false;
}
}
ISR(TIMER4_COMPA_vect, ISR_BLOCK) {
currentPos[2] += incPos[2];
if (stopSignal[2] || currentPos[2] == targetPos[2]) {
TCCR4B = B00011000;
TIMSK4 = 0;
isRunning[2] = false;
}
}
ISR(TIMER5_COMPA_vect, ISR_BLOCK) {
currentPos[3] += incPos[3];
if (stopSignal[3] || currentPos[3] == targetPos[3]) {
TCCR5B = B00011000;
TIMSK5 = 0;
isRunning[3] = false;
}
}