trigger relay with wind speed

I have taken a sketch which measures RPM and modified it to use with an anemometer (hall-effect switch) to measure wind speed.

My goal is to trigger a 5 volt relay when the wind is >10 and <50. Otherwise the relay is off. While my sketch compiles and displays the MPH, the relay is not triggered.

Ideas…suggestions?

#include <LiquidCrystal.h>
LiquidCrystal lcd(13,12,11,10,9,8);
const int hallSensorPin = 2;                      // connect the hall effect sensor on pin 2
const int relay = 4;
const unsigned long sampleTime = 1000;
const int maxRPM = 950;                  // maximum RPM for LCD Bar
int rpmMaximum = 0;

void setup() 
{
  pinMode(hallSensorPin,INPUT);
  pinMode(relay, OUTPUT);
  Serial.begin(9600);
   lcd.begin(16, 2);
  lcd.print("Initializing");
  delay(1000);
  lcd.clear();
  lcd.print("Welcome");
  for (int positionCounter = 0; positionCounter < 21; positionCounter++) {
    lcd.scrollDisplayLeft();
    delay(350);
  }
    delay(1000);
  lcd.clear();
}

void loop() 
{
  delay(100);
  int rpm = getRPM();
  if (rpm > rpmMaximum) rpmMaximum = rpm;
    lcd.clear();
  displayRPM(rpm);
  displayBar(rpm);
  
}
int getRPM()
{
  int count = 0;
  boolean countFlag = LOW;
  unsigned long currentTime = 0;
  unsigned long startTime = millis();
  while (currentTime <= sampleTime)
  {
    if (digitalRead(hallSensorPin) == HIGH)
    {
      countFlag = HIGH;
    }
    if (digitalRead(hallSensorPin) == LOW && countFlag == HIGH)
    {
      count++;
      countFlag=LOW;
    }
    currentTime = millis() - startTime;
  }
  int countRpm = int(6000/float(sampleTime))*count;
  if ((countRpm > 10) && (countRpm < 50))
  {digitalWrite (relay, HIGH);}
  
  return countRpm;
   
}    
void displayRPM(int rpm) 
{
  lcd.clear();
  lcd.setCursor(0, 0); 
  lcd.print(rpm,DEC);
  lcd.setCursor(4,0);
  lcd.print("MPH");
  lcd.setCursor(9,0);
  lcd.print(rpmMaximum, DEC);
  lcd.setCursor(13,0);
  lcd.print("MAX");
  Serial.print("RPM = ");
  Serial.print(rpm);
  Serial.print("  MAX RPM = ");
  Serial.println(rpmMaximum);
}

void displayBar(int rpm)
{
  int numOfBars=map(rpm,0,maxRPM,0,15);
  lcd.setCursor(0,1);
  if (rpm!=0)
  {
  for (int i=0; i<=numOfBars; i++)
   {
        lcd.setCursor(i,1);
        lcd.write(1023);
      }
  }
}

How is the relay wired? Can you trigger it just with a debug program (use for example Blink)?

And not how much more readable this is compared to your code :wink:

if ((countRpm > 10) && (countRpm < 50)){
  digitalWrite (relay, HIGH);
}

No float nonsense:

  int countRpm = 6000 UL * count / sampleTime;

Thanks. I will make those changes to the code.

Yes, I wired the relay backwards. I thought making the relay pin “high” would make it 5vdc + instead of the ground completing the circuit.

That all depends on how you connect it and what you use. I start to think you don't use a relay but a relay module :wink: Devil is in the details!