In the “BlinkWithoutDelay” sketch, the following is declared in the loop:
unsigned long currentMillis = millis();
Does that have to be in loop() or can it just be placed at the top with all my other usual declarations?
The reason I ask is I am experimenting with a very very simple motor controller using two NPN transistors and two PNP transistors. Since I don’t want to chance turning the wrong ones on at the same time I just placed the on/off for the proper ones in a function.
/* Simple motor controller. Two NPN transistors and two PNP transistors connected to a small hobby motor.
VERY IMPORTANT that the proper ON/OFF sequence is observed or else there will be a direct path from VCC to GND.
VCC----------I---------------------I
I I
TranA NPN TranB NPN
I I
>--------Motor--------<
I I
TranC PNP TranD PNP
I I
GND----------I---------------------I
Thought it best to write the control as a function. */
const int TranA = 0;
const int TranB = 1;
const int TranC = 2;
const int TranD = 3;
unsigned long previousMillis = 0; // will store last time LED was updated
long TimeOn = 250; // Microseconds that motor is on
unsigned long currentMillis = millis();
void setup() {
pinMode(TranA, OUTPUT);
pinMode(TranB, OUTPUT);
pinMode(TranC, OUTPUT);
pinMode(TranD, OUTPUT);
}
void loop() {
MotorClockwise();
delay(2500);
MotorCounterClockwise();
delay(2500);
}
void MotorClockwise() {
digitalWrite(TranA, HIGH);
digitalWrite(TranD, HIGH);
if(currentMillis - previousMillis > TimeOn) {
previousMillis = currentMillis;
digitalWrite(TranA, LOW);
digitalWrite(TranD, LOW);
delay(10);
}
}
void MotorCounterClockwise() {
digitalWrite(TranB, HIGH);
digitalWrite(TranC, HIGH);
if(currentMillis - previousMillis > TimeOn) {
previousMillis = currentMillis;
digitalWrite(TranB, LOW);
digitalWrite(TranC, LOW);
delay(10);
}
}
I realize since I can’t put a blocking diode in the circuit in the usual way, couldn’t I just use a 1N4148 coming off the control pins in series to the transistor’s base?
EDIT: Maybe this would be better, but you get the idea: