Created
March 27, 2018 21:07
-
-
Save bakercp/9d5d4aaf868cd2a2de6a7ea0813dc231 to your computer and use it in GitHub Desktop.
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
// Control PWM via a transistor. | |
class MotorController | |
{ | |
public: | |
MotorController(int motorPin) | |
{ | |
pin = motorPin; | |
startTime = endTime = millis(); | |
} | |
void update() | |
{ | |
unsigned long now = millis(); | |
currentValue = map(now, startTime, endTime, startValue, endValue); | |
currentValue = constrain(currentValue, min(startValue, endValue), max(startValue, endValue)); | |
analogWrite(pin, currentValue); | |
} | |
bool isAtTarget() const | |
{ | |
return endValue == currentValue; | |
} | |
void setTarget(long target, unsigned long timeMs) | |
{ | |
startValue = currentValue; | |
endValue = target; | |
startTime = millis(); | |
endTime = startTime + timeMs; | |
} | |
long value() const | |
{ | |
return currentValue; | |
} | |
private: | |
int pin = 0; | |
long startValue = 0; | |
long endValue = 0; | |
unsigned long startTime = 0; | |
unsigned long endTime = 0; | |
long currentValue = 0; | |
}; | |
MotorController motorOne(6); | |
MotorController motorTwo(5); | |
MotorController motorThree(3); | |
void setup() | |
{ | |
Serial.begin(9600); | |
randomSeed(analogRead(0)); | |
motorOne.setTarget(1, 10); | |
motorTwo.setTarget(1, 10); | |
motorThree.setTarget(1, 10); | |
} | |
void loop() | |
{ | |
motorOne.update(); | |
if (motorOne.isAtTarget()) | |
{ | |
long newTarget = random(255); | |
unsigned long duration = random(2000, 10000); | |
motorOne.setTarget(newTarget, duration); | |
} | |
motorTwo.update(); | |
if (motorTwo.isAtTarget()) | |
{ | |
motorTwo.setTarget(random(255), random(2000, 10000)); | |
} | |
motorThree.update(); | |
if (motorThree.isAtTarget()) | |
{ | |
motorThree.setTarget(random(255), random(2000, 10000)); | |
} | |
Serial.print(motorOne.value()); | |
Serial.print(","); | |
Serial.print(motorTwo.value()); | |
Serial.print(","); | |
Serial.print(motorThree.value()); | |
Serial.println(""); | |
delay(10); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment