So essentially I'm trying to run an AC motor for 20seconds based on the activation of a phototransistor. My circuit is set up properly with a beefcake relay, the only trouble I'm having is with my if statement.. everything works fine, it will work for 2 times and the third time the motor stays on indefinitely. The problematic line is: if(currentTime + 10000 < millis()){
How can I adjust code so that the if statement will work no matter what time it is.... Or is there another way to go about this?
Here is the Code:
int sensorPin = 0; //analog pin 0
int threshold = 100;
int motorPin = 13;
int currentTime = 0;
Thank you for your quick reply PaulS.
I set up int analogValue = analogRead(sensorPin); to communicate that if the analog value is high enough it can initiate based on the threshold: if (analogValue < threshold) {
A bit of a newb when it comes to arduino, but could you expand on what you mean by "The millis() function does not return an int!" and maybe offer another solution to my code?
Thanks!
const int sensorPin = A0;
const int threshold = 100;
const unsigned long interval = 20*1000UL; // Twenty seconds
const int motorPin = 13;
unsigned long startTime = 0;
void setup(){
Serial.begin(9600);
digitalWrite(motorPin, LOW);
pinMode(13, OUTPUT);
}
void loop(){
// if the analog value is low enough, turn on the motor:
if (analogRead(sensorPin) < threshold) {
startTime = millis();
Serial.println(startTime); // Serial Print When the sensor is sensed.
Serial.println("on");
digitalWrite(motorPin, LOW);
}
// If time has expired, turn the motor off
if(millis() - startTime > interval) {
Serial.println("off");
digitalWrite(motorPin, HIGH);
}
}
johnwasser thank you so much!! your code works perfect! My friend and i have been slaving for weeks to try and get this figured out and you put the icing on the cake!!!
Much appreciated!
And for others, thank you for your advice!
I appreciate the quick responses, its nice to know these forums are very active and I will work to do my part in the arduino community