0

I'm a beginner at Arduino.

I have a soil moisture sensor and I mapped the lowest and highest moisture value to a value in between 0 and 100.

What I was trying to do was if the value was less than 50, then the LED should turn on. But even when the value was less than 50 (e.g 25) the LED doesn't turn on.

The moisture detection or the value mapping works perfectly fine.

Does the issue lie on my code or my LED wiring? enter image description here

Code:

int mostMoist = 180;
int leastMoist = 600;
int percent;
int raw;
const int threshold = 50;

void setup() {
  Serial.begin(9600);
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  raw = analogRead(A0);
  percent = map(raw,leastMoist,mostMoist,0,100);

  if (percent < 0){
    percent = 0;
  }

  if (percent < threshold){
    digitalWrite(LED_BUILTIN,HIGH);
  } else {
    digitalWrite(LED_BUILTIN,LOW);
  }

  Serial.println(percent);
  delay(2);  
}
  • load and run LED blink code to test the LED – jsotola Jun 17 at 17:43
  • problem aside: you should only switch on power to the sensor when you're about to do a reading; a constant charge will corrode the sensor's metal very quickly. – dandavis Jun 17 at 22:32
2

A good way to start debugging this sort of problem is to print out debug statements that say what the hardware should be doing. If the debug statements print out as expected then it's probably hardware, if not, then it's probably your code, e.g.

if (percent < threshold){
  Serial.prinln("LED on.");
  digitalWrite(LED_BUILTIN,HIGH);
}
else {
  Serial.prinln("LED off.");
  digitalWrite(LED_BUILTIN,LOW);
}
  • Thanks, everything's working fine after adding the debug statement, the LED's turning on at the right time! – Jeffrey Chan Jun 18 at 9:38
  • You're welcome, glad to help. If that answers your question you may want to mark the answer as accepted: stackoverflow.com/help/someone-answers – fractious Jun 19 at 10:33

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.