CC Lab: Homework Week Three

Monday, September 18th 2017

The Code

const int motorPin = 9; int currentSpeed = 0;

void setup() { Serial.begin(9600);

pinMode(motorPin, OUTPUT); }

void loop() { int sensorValue = analogRead(A0); int newMotorSpeed = map(sensorValue, 0, 1023, 0, 255); Serial.println(newMotorSpeed); analogWrite(motorPin, newMotorSpeed); delay(20); // this was an idea that ended up not working out // I found that a small delay was enough to send the pot value // straight to the motor // changeSpeedTo(newMotorSpeed); }

void changeSpeedTo(int speed) { Serial.println(speed); int delayTime = 20; // milliseconds between each speed step // accelerate the motor

if (speed > currentSpeed) { for(int newSpeed = speed; newSpeed > currentSpeed; speed--) { analogWrite(motorPin, newSpeed); // set the new speed delay(delayTime); // delay between speed steps } }

if (speed < currentSpeed) { for(int newSpeed = speed; speed < currentSpeed; speed++) { analogWrite(motorPin,speed); // set the new speed delay(delayTime); // delay between speed steps } } currentSpeed = speed; }