Activating relay by analog sensor

Hi all, I'm wondering how I would go about getting a relay to activate when an analog sensor goes below a certain value.
I have been using this code as an example, but now I need it to be activated by the analog sensor. How would I go about modifying the code?

int in1 = 8;
void setup() {
  pinMode(in1, OUTPUT);
  digitalWrite(in1, HIGH);
}
void loop() {
  digitalWrite(in1, LOW);
  delay(500);
  digitalWrite(in1, HIGH);
  delay(1000);
}

Thanks in advance for any help

you need to read the analog value and test it; if it is above (or below) the threshold, then you do things

void loop()
{
   int value = analogRead(SENSOR_PIN);
   if (value > THRESHOLD) {
      ...
   }
   ...
}

I suggest that you examine the button example that comes with the IDE. It uses a button (obviously) but you need to understand the principle how to control something (led / relay) based on an input. Next you can adjust the code to use an analogRead instead of a digitalRead.

You might also want to add a bit of hysteresis (to the example given by arduino_new); if the analog value is at the edge of the threshold, your relay will be switching on and off like crazy. E.g. if the threshold is 500 and one moment the analog value is 500 and the next moment 499.

So e.g.

void loop()
{
  int value = analogRead(SENSOR_PIN);
  if (value > THRESHOLD) {
    // relay on (or off)
    ...
  }
  else if ( value < THRESHOLD - 50)
  {
    // relay off (or on)
    ...
  }
  else
  {
    // do nothing
  }
}

Hi,
You need to use an if statement, this will help;

https://www.arduino.cc/reference/en/language/structure/control-structure/if/

Tom.. :slight_smile: