0

I am trying to set my servo at f.e. 90 degrees when the friendlyValue of the soil sensor is < 50%. The servo isn't moving at all, is it because the code is running too fast and the servo doesn't have time to reposition in between? I tried putting in delays but that didn't work, how do I fix this? I am new to Arduino and would appreciate any help.

#include <Servo.h>
Servo myservo;


int dryValue = 1024; // max
int wetValue = 0; // min

int friendlyDryValue = 0; // %
int friendlyWetValue = 100;

int sensor = A0;
int sensorValue;

void setup() {

  Serial.begin(115200);

  pinMode(A0, INPUT);
  pinMode(D6, OUTPUT);
}

void loop() {

  int rawValue = analogRead(A0); // soil sensor

 Serial.print("Raw: ");
  Serial.print(rawValue);
  Serial.print (" | ");

   int friendlyValue = map(rawValue, dryValue, wetValue,     friendlyDryValue, friendlyWetValue);


  Serial.print("Friendly: ");
  Serial.print(friendlyValue);
  Serial.println("%");


if (friendlyValue <50)
{
  myservo.write(9);
  }
  else
  {
    myservo.write(90);
    }
  }
1

From your statement pinMode(D6, OUTPUT);, It looks you're using pin6 for the servo - ? If so, you need instead: myservo.attach(6); to prepare a servo object to use that pin to drive a servo. Not having done this is the reason why your servo wasn't moving. There is an example program to drive a servo using the servo library on the Arduino site.

Your code will run very fast, but since soil moisture can't change rapidly, the value being read from the soil sensor shouldn't either - unless there is electrical noise (and there will always be some; it's a question of how much). Your print statements should show you how consistent the readings are.

There are a couple of things you can do about it:

  1. Delay for a second or so at the bottom of the loop() function so the servo updates will come less frequently and the servo will have time to track them. This really doesn't help with a noisy signal though, and you probably don't want it to track noise. Also, I don't usually suggest using delays but in so uncomplicated a program as this one, it is really the most straightforward approach.

  2. Calculate the servo position from an average of a few sensor readings rather than using just one. This will help with noise so the servo should only have to track real data rather than data+noise.

  3. Do both. Update less frequently and average a few readings taken a few 10s of milliseconds apart. This will both reduce noise and keep the servo updates to within its tracking ability.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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