Hall Effect Sensor, making part of the code loop only once.

Hi all,
Wondering if anyone can spare me a moment to point me in the right direction.
I’ve got a magnet rotating on a disk and a Hall effect sensor which is sending an output to trigger an LED. It’s not a simple blink, I want a fade on the LED so it initially lights up at 100% then fades out - the speed of which is adjustable via the fade value. This generates more of a pulse.
Everything works as I intended. If the sensor is triggered before the LED has finished fading, it ramps back up to 100%. So once the disk is spinning fast enough it appears that the LED is on continuously.
However, I want to ensure the LED always defaults to 0% so if the magnet were to stop in front of the sensor, then the LED would do it’s pulse but then stay off at 0%. At the moment it stays on until the magnet has moved far enough away to stop the Hall effect trigger…
So i’m wondering if there is a way to make the ‘if (state==LOW)’ part of the code only loop once per trigger…or if there is another potential solution?
Thanks!

int hallSensorPin = 3;     
int ledPin =  LED_BUILTIN;


void setup() {
  pinMode(LED_BUILTIN, OUTPUT);      
  pinMode(hallSensorPin, INPUT);
}

void loop()
{
  static int fadeValue = 5; //How quickly the LED Fades

  // if Hall is ON
  if (digitalRead(hallSensorPin) == HIGH)
  {
    // if not LED at maximum
    if (fadeValue < 255)
    {
      // increment intensity
      fadeValue++;
      // write LED intensity
      analogWrite(ledPin, fadeValue);
      // wait a little
      delay(1);
    }
  }
  // if switch is OFF
  else
  {
    // switch LED off
    analogWrite(ledPin, 0 );
    // reset fade value to reflect the intensity of the LED
    fadeValue = 0;
  }
}

you need to ignore "magnet requests" if the last one happened too recently.

How you define "too recently" is up to you. It will have an impact on the behavior if the disk is really spinning fast, so fast that the magnet comes back within the delay you'll have defined.

that would also deal with bouncing signals from your Hall effect sensor

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.