I'm coding a hydroponics project where I trigger a servo to turn on a sprayer, then a pump is turned on and off and the entire thing needs to repeat.
The whole thing works great except for the last delay cycle, which never ends and so the loop cycle never repeats, it only runs once.
Any ideas on why this is happening?
The code:
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
#define SERVOMIN 250
#define SERVOMAX 650
#define USMIN 600
#define USMAX 2400
#define SERVO_FREQ 50
uint8_t servonum = 0;
int D3 = 3;
int D4 = 4;
void setup() {
Serial.begin(9600);
Serial.println("Reboot!");
pinMode(D3, OUTPUT);
pinMode(D4, OUTPUT);
pwm.begin();
pwm.setOscillatorFrequency(27000000);
pwm.setPWMFreq(SERVO_FREQ); // Analog servos run at ~50 Hz updates
delay(10);
}
void loop() {
Serial.println('On');
digitalWrite(D3, LOW);
digitalWrite(D4, LOW);
pwm.setPWM(servonum, 0, 170);
delay(500);
pwm.setPWM(servonum, 0, 300);
//
delay(0.5*1000*60);
//delay(3000);
// Off for 10 minutes
Serial.println('Off');
pwm.setPWM(servonum, 0, 170);
delay(500);
pwm.setPWM(servonum, 0, 300);
Serial.println('Pump on');
digitalWrite(D3, HIGH);
digitalWrite(D4, HIGH);
delay(15*1000); // TURN ON PUMP FOR 15 seconds
Serial.println('Pump Off');
digitalWrite(D3, LOW);
digitalWrite(D4, LOW); // TURN OFF PUMP, TURN ON
delay(2*1000*60); // This is the delay that never ends, it's supposed to be 2 minutes long...
}
void setServoPulse(uint8_t n, double pulse) {
double pulselength;
pulselength = 1000000; // 1,000,000 us per second
pulselength /= SERVO_FREQ; // Analog servos run at ~60 Hz updates
pulselength /= 4096; // 12 bits of resolution
pulse *= 1000000; // convert input seconds to us
pulse /= pulselength;
pwm.setPWM(n, 0, pulse);
}
dont do arithmetic operation on such function, why not just write delay(120000); instead?. if you want to make arithmetic operations, is better to separe the operation, like this:
long int timeDelay1 = 60*2*1000;
delay(timeDelay1);
such long delay is not very good practice, instead used the funtion millis() to measure time, like this:
long int t0 = 0;
long int t1 = 0;
long int howManyTimeIWantToWait = 120000;
void setup() {
t0 = millis();
}
void loop() {
t1 = millis();
if(t1 >= (t0+howManyTimeIWantToWait)){
t0 = millis();
//howManyTimeIWantToWait has been passed
}
//do other stuff whithout waiting on the function delay();
}