Hall effect sensor Programming: 2 sensors to run 1 LED on and off

Hello,

I am struggling on a project based on hell effect sensor. Although my problem to write the correct codes. Please help me.

The sequence would be : (Magnetic Sensor 1 ON → Solenoid Valve ON → Magnetic Sensor 2 ON -----> Solenoid Valve OFF ) 3000 times

Last two weeks, I tired a lot to sort it out. there are 3 issues and those stuck me for ages.

Issue 1: when I brings the sensor1 closure to the Magnet, it LED turn on until I remove it but I want to remain it on until the (second sensor) sensor2 come close to the Magnet.

Issue 2: When I brought the sensor1 close to the magnet, it runs for 3000 times until i remove it. But I want the led will turn on and then sensor 2 will be closure and led will turn off. AND OVERALL, it WILL COUNT as 1 CYCLE.

Issue 3: the following code give me value like “Sensor 1 Value = 1” and “Sensor 2 value =1”… No idea why?? :frowning:

Here is my codes. Please help me to sort this problem and let me know what to do! Advanced Thanks.

/******************************

  • global variables *
    ******************************/

int sensor_1_pin = 2;
int sensor_2_pin = 3; //hall effect sensor output connected to Ard UNO

int led = 7; //Declaring Variables

int sensor_1_value = 0;
int sensor_2_value = 0;

int cycle = 3000; //Cycle to 3000 Times
int i = 0; //for if loop

/******************************

  • setup *
    ******************************/
    void setup()
    {
    Serial.begin (9600);
    //Pin declaration

pinMode(sensor_1_pin, INPUT);
pinMode(sensor_2_pin, INPUT);

pinMode(led, OUTPUT);
}

void loop()
{
//Read and store sensor state (1 or 0)
sensor_1_value = digitalRead(sensor_1_pin);
sensor_2_value = digitalRead(sensor_2_pin);

Serial.print ("Sensor 1 value = ");
Serial.println (sensor_1_value);
Serial.print ("Sensor 2 value = ");
Serial.println (sensor_2_value);

//if sensor 1 value doesn’t match sensor 2 value
if (sensor_1_value != sensor_2_value)
{
if (i<cycle)
{
//sensor 1 value is a 1, turn off led
if(sensor_1_value == HIGH)
{
digitalWrite(led, LOW);
Serial.print ("Sensor 1 value = ");
Serial.println (sensor_1_value);
}
//sensor 2 value is a 1, turn on led
else if(sensor_2_value == HIGH)
{
digitalWrite(led, HIGH);
Serial.print ("Sensor 2 value = ");
Serial.println (sensor_2_value);
}
}
i++;
}
sensor_1_value = sensor_2_value;
}//<-----end of void loop()

Have you looked at the state change detection example? You need to keep track of when the hall effect sensors change state, not when there are in some state.

When the first sensor changes state (to "magnet is present"), turn the LED on and increment the counter (i is a lousy name for the counter). When the second sensor changes state (to "magnet is present"), turn the LED off.

if possible could you please add those code in the place where i should .... It would be really helpful. Please.