0

basically I am trying to write an IF/ELSE statement that triggers a light when a pressure sensor is between two values.

In other words, I want the light to respond ONLY if the analog read is between 400 and 600, as opposed to, say, only being above 400.

Here is the code, any suggestions?

int sensor=0;
int threshold=200;

void setup (){
  pinMode(2, OUTPUT);  
  digitalWrite(2, LOW);
  Serial.begin(9600);
}

void loop() {
  sensor=analogRead(0);
  Serial.println(sensor);
  if (sensor > threshold) {
    digitalWrite(2, HIGH);
  }
  else {
    digitalWrite(2, LOW);
  }
}
1

To get the light to turn on only when the sensor reading is between two numbers, you should test if the reading is between the two numbers, and if it is, turn on the light.

To test if a value is between two numbers, you could use the && AND operator to see if both conditions are met. For example:

if (sensor > loLimit && sensor < hiLimit) {
    digitalWrite(2, HIGH);
} else {
    digitalWrite(2, LOW);
}

Here's a shorter way to write that:

digitalWrite(2, (sensor > loLimit && sensor < hiLimit));

In this form, the expression evaluates to 1, or HIGH, if it is true, and to 0, or LOW, if it is false.

Another approach is to test if abs(sensor-midLimit) < halfGap, where midLimit is (loLimit+hiLimit)/2 and halfGap is (hiLimit-loLimit)/2. Turn on the light if abs(sensor-midLimit) < halfGap, else turn it off.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.