Hello, I'm pretty new in the Arduino world, so i need help with some programming. The Arduino controls 3 things: a servo with a potentiometer; a relay that controls a 220v water heater with a temperature sensor; and another relay that controls a water pump activated with an infrared proximity sensor. The code works, the problem it's with the delays used in the pump cycle, that interferes with the servo operation creating a ton of lag. I've tried using millis() instead, but my knowledge is very limited and I couldn't manage to make it work. It would be very useful some guidance.
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Servo.h>
#define Pin 3 // pin sensor
OneWire ourWire(Pin);
DallasTemperature sensors(&ourWire);
float celsius()
{
int dato;
float c;
dato=sensors.getTempCByIndex(0);
c=(dato);
return(c);
}
Servo yerba; //servo
int potenciometro = 0;
int valor_potenciometro;
const int ProxSensor=6; //pin infrared sensor
void setup()
{
sensors.begin();
pinMode (8,OUTPUT); // pin water heater relay
yerba.attach(2); // pin servo
pinMode(7, OUTPUT); // pin pump relay
pinMode(ProxSensor,INPUT);
}
void loop(){
valor_potenciometro = analogRead(potenciometro);
valor_potenciometro = map(valor_potenciometro, 0, 1023, 0, 120);
yerba.write(valor_potenciometro);
sensors.requestTemperatures();
if (celsius() > 35.00)
{
digitalWrite(8,HIGH); // relay on, water heater off (water heater in NC)
}
else
digitalWrite(8,LOW); // relay off, water heater on
float Celsius = celsius();
if(digitalRead(ProxSensor)==LOW) //if sensor LOW (obstacle)
{
delay(2000); // wait time for pump on
digitalWrite(7, HIGH);
delay(3000); // pump working time
digitalWrite(7, LOW);
delay(10000); // wait time after pump operation
}
else
{
digitalWrite(7, LOW);
}
}
Starting point, work out all the possible states the device can be in…
e.g. idle, opening, pumping, blinking etc.
Make sure you figure out ALL the possibilities.
With that, you now have ‘states’ for a state machine.
Even if they overlap, or change order, you can use millis() and switch()-case statements to navigate through the various states - based on switch inputs, or intervals.
Sometimes you might need multiple millis() timers to keep one event running, while you go to do something else.