Created
January 6, 2016 10:06
-
-
Save urish/51c72460a37beb4dd337 to your computer and use it in GitHub Desktop.
motorcoil
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const int phase1pin = 2; | |
const int phase2pin = 4; | |
const int phase3pin = 3; | |
float holdTime = 50000; // microsecs | |
const unsigned long minHoldTime = 10000; | |
unsigned long p1start, | |
p1end, | |
p2start, | |
p2end, | |
p3start, | |
p3end; | |
#define outpin 11 // OC2A pin - cannot be changed | |
#define clockFrequency 16000000 | |
#define prescaleFactor 1 | |
void setup(){ | |
Serial.begin(115200); | |
pinMode(phase1pin, OUTPUT); | |
pinMode(phase2pin, OUTPUT); | |
pinMode(phase3pin, OUTPUT); | |
p1start = micros(); | |
digitalWrite(phase1pin, HIGH); | |
TCCR2B = B00000001; // set CS20, clear CS21, CS22 and WGM22 | |
TCCR2A = B01000010; // set COM2A0 and WGM21, clear COM2A1 and WGM20 | |
// calculate and load the timer data timer | |
unsigned long noteval = 4000; | |
OCR2A = ((float)clockFrequency / (noteval * 2 * prescaleFactor)) -1; | |
pinMode(outpin, OUTPUT); // turn on output pin | |
} | |
void chkP1(){ | |
unsigned long currentTime = micros(); | |
unsigned long td = currentTime - p1start; | |
unsigned long refractory = 2.25*holdTime; | |
if(digitalRead(phase1pin)){ | |
if(td > holdTime){ | |
digitalWrite(phase1pin, LOW); | |
p1end = currentTime; | |
} | |
}else if(td > refractory){ | |
digitalWrite(phase1pin, HIGH); | |
p1start = currentTime; | |
} | |
} | |
void chkP2(){ | |
unsigned long currentTime = micros(); | |
unsigned long td = currentTime - p1start; | |
if(digitalRead(phase2pin)){ | |
if(td > 1.75*holdTime || td < 0.75*holdTime){ | |
digitalWrite(phase2pin, LOW); | |
p2end = currentTime; | |
} | |
}else if(td > 0.75*holdTime && td < 1.75*holdTime){ | |
digitalWrite(phase2pin, HIGH); | |
p2start = currentTime; | |
} | |
} | |
void chkP3(){ | |
unsigned long currentTime = micros(); | |
unsigned long td = currentTime - p1start; | |
if(digitalRead(phase3pin)){ | |
if(td > 0.25*holdTime && p3start < p1start){ | |
digitalWrite(phase3pin, LOW); | |
p3end = currentTime; | |
} | |
}else if(td > 1.5*holdTime){ | |
digitalWrite(phase3pin, HIGH); | |
p3start = currentTime; | |
} | |
} | |
void loop(){ | |
chkP1(); | |
chkP2(); | |
chkP3(); | |
delayMicroseconds(100); | |
if(holdTime >= minHoldTime){ | |
holdTime -= 0.5; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment