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);
 }
}
Nick Gammon
38.9k13 gold badges69 silver badges125 bronze badges
asked May 19, 2016 at 20:25

1 Answer 1

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.

answered May 19, 2016 at 20:52

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.