I've racked my brain and cannot figure this out.
I'm running a DC motor for approx 5 secs every 10 seconds. My code works fine AS LONG AS I KEEP THE SERIAL MONITOR COMMANDS IN THE PROGRAM (placed there while debugging). If I remove them (either by adding "//" or simply deleting the lines), the program no longer works.
I'd appreciate learning what stupid thing I must not be seeing.
Thank you,
Michael
/*
Controls motor with transisitor: https://learn.adafruit.com/adafruit-arduino-lesson-13-dc-motor
Using a rs445pa14233r motor. Speed setting (80) is the lowest that will allow the motor to moves.
*/
int motorPin = 3;
long int CurrentMillis = 0;
void setup()
{
pinMode(motorPin, OUTPUT);
Serial.begin(9600);
}
void loop()
{
if (millis() - CurrentMillis >= 10000) {
CurrentMillis = millis();
for (int t = 0; t < 100; t++) {
Serial.println (t);
analogWrite(motorPin, 80);
}
analogWrite(motorPin, 0);
}
}
Without the Serial.println() the for loop is running very fast, the print instruction is slowing the code down because it is filling the serial buffer up and having to wait for the characters to transmit at 9600 baud before continuing to the next line of code.
What David said. That println is causing a 1 to 3ms delay.
I'm running a DC motor for approx 500ms every 10 seconds
To execute a periodic action, you can use millis() for timing.
You may wish to review
Using millis() for timing. A beginners guide.
https://forum.arduino.cc/index.php?topic=503368.0
Here's some example code for your motor cycle which uses millis() for the timing. This example uses a boolean control variable which enables the timed motor cycle at the periodic interval.
int motorPin = 3;
unsigned long lastMotorStart = 0;
unsigned long runTime = 500;
boolean runMotor = false;
void setup()
{
pinMode(motorPin, OUTPUT);
Serial.begin(9600);
}
void loop()
{
if (millis() - lastMotorStart >= 10000)
{
lastMotorStart = millis();
runMotor = true;
analogWrite(motorPin, 80);
}
if (runMotor == true && millis() - lastMotorStart >= runTime)
{
analogWrite(motorPin, 0);
runMotor = false;
}
}
Thank you guys VERY much! It makes perfect sense to me. I especially appreciate the code you shared with me, cattledog!