/*
* Motor control program
* Purpose: to control an external motor using a separate power supply
* and a TIP41 transistor supplied in the Mobile Modular trainer
*
* Hookup guide:
* Digital pin 9 to a 330 ohm resistor to the TIP29 transistor's base (Term Block # 7)
* Arduino Ground to Mobile Modular ground (Term Block #13)
* Mobile modular Motor Positive wire (Term Block # 16 to TIP29 Collector (Term Block #8)
* Mobile modular Motor Negative wire (Term Block #17 to Mobile Modular 9V supply (Term block #23)
*
* Functionality:
* The PWM pin (9) when turned on supplies a current to the base of the TIP29
* The Collector of the TIP29, then allows current to flow from the 9V source through
* the motor (acting as a switch), turning the motor on.
* When the PWM pin is off, the transistor will also be off, and the motor will coast.
*
* Created by Ron Roposon
* July 7, 2020
*/
float potValue;
float potVoltage;
const byte potInput = A0;
float Motorpercent;
const int motorPin = 9; // pins 3, 5, 6, 9, 10, and 11 are PWM pins with the tilde ~ in front of the number
int motorSpeed = 0; // the PWM setting for the motor control
int onTime = 3000; // for motor control
int offTime = 1000; // for motor control
int delayTime = 30; // acceleration/deceleration step time
void setup()
{
Serial.begin(9600);
pinMode(motorPin, OUTPUT); // the PWM mode won't work unless we set the pin as an output
pinMode(potInput, INPUT);
}
void loop()
{
potValue = analogRead(potInput);
Motorpercent = float(potValue) * (100.0 / 1023.0);
//Serial.println(potVoltage);
Serial.println(Motorpercent);
motorSpeed=float(potVoltage)*(51);
//Motorpercent=float(potValue)*((5.0/1023.0)*20);
controlSpeed(motorSpeed, onTime, offTime);
spinUp(motorSpeed, delayTime);
spinDown(motorSpeed, delayTime);
delay(1000);
consoleMotorSpeed();
}
void spinUp(int speedSetting, int delaySetting)
{
for (int a = 0; a < speedSetting; a++)
{
analogWrite(motorPin, a);
delay(delaySetting);
}
}
void spinDown(int speedSetting, int delaySetting)
{
for (int a = speedSetting; a >= 0; a--)
{
analogWrite(motorPin, a);
delay(delaySetting);
}
}
void controlSpeed(int speedSetting, int timeOn, int timeOff)
{
analogWrite(motorPin, speedSetting);
delay(timeOn);
if (timeOff > 0)
{
analogWrite(motorPin, 0);
delay(timeOff);
}
}
void consoleMotorSpeed()
{
int motorSpeed = getInteger(255);
analogWrite(motorPin, motorSpeed);
delay(1000);
}
int getInteger(int maxValue)
{
int newValue = maxValue + 1;
while (Serial.available() > 0)
{
Serial.read();
delay(10);
} // clear Serial port
//Serial.print("Please enter a motor speed between 0 and ");
//Serial.println(maxValue);
while (newValue > maxValue)
{
while (Serial.available() == 0) {}
newValue = Serial.parseInt();
if (newValue > maxValue)
{
Serial.println("Out of Range");
}
}
Serial.print("New Value = ");
Serial.println(newValue);
return newValue;
}