Go Down

Topic: How to use sensor to change LED (Read 149 times) previous topic - next topic

ajj-671

Since I'm new to arduino last night I learned how LEDs work and finally got my weight sensor to get measurements (even though they are negative for some reason)

How do I get the LED to turn on above a certain weight and off when below that weight?

All help is appreciated.

Thank you

UKHeliBob

Do you know how the if statement works ?
Please do not send me PMs asking for help.  Post in the forum then everyone will benefit from seeing the questions and answers.

johnwasser

There are conditional operators for comparing values (variables or constants).  For example:
Code: [Select]
weight > TriggerWeight
This expression will be true/1/HIGH if the value in the weight variable is greater than the value in the TriggerWeight variable.  If not, the result is false/0/LOW

When you are writing to digital output pins, the values you generally use are HIGH or LOW but true and false or 1 and 0 will work just as well.

Knowing all of that you can see that one way to turn on a pin connected to an LED when a weight is above a trigger weight (and off otherwise) is:

Code: [Select]
  digitalWrite(LEDPin, weight > TriggerWeight);

Of course the names you make up have to be declared somewhere.  Constants like the pin number and the trigger weight value can be put at the top of your sketch:

Code: [Select]
const byte LEDPin = 13;
const int TriggerWeight = 137;  //  Pounds?  Kilograms?  Tons?


The variables you work with also have to be declared somewhere.  If the value is only needed in one function (like setup(), loop(), or some function you design) then it is good to put the declaration there so no other function can mess with the value.  Variables declared outside any function are called 'globals' and every function can use them.  You have to make sure that functions that share a global variable are working together.

Code: [Select]
const byte LEDPin = 13;
const int TriggerWeight = 137;  //  Pounds?  Kilograms?  Tons?

void setup()
{
  // Mandatory function
  pinMode(LEDPin, OUTPUT);  // This turns on the output driver so you can set the output HIGH (5V) or LOW (0V).
}

void loop()
{
  //Mandatory function.  Called repeatedly forever when setup() is finished.
  int weight;  // Local variable

  weight = GetWeight();  // Whatever way you get a weight value from your scale

  digitalWrite(LEDPin, weight > TriggerWeight);
}


That's pretty much it.  you just have to put in the code to get the weight value.
Send Bitcoin tips to: 1G2qoGwMRXx8az71DVP1E81jShxtbSh5Hp

Go Up