I am making a project of a smart bridge in which the hight of the bridge will increase with the help of servo moters when the sensor detects moisture more than a limit.But my servo motors are not working.i think something is wrong with the code.can please help me correct it?or send me the correct code.
#include <Servo.h>
#include <Servo.h>
Servo tap_servo;
int sensor_pin = 4;
int tap_servo_pin =5;
int val;
void setup(){
pinMode(sensor_pin,INPUT);
tap_servo.attach(tap_servo_pin);
}
void loop(){
val = digitalRead(sensor_pin);
if (val==0)
{tap_servo.write(0);
}
if (val==1)
{tap_servo.write(90);
}
}
If you call servo.write() at a very high speed, then the servo motor might not work (depending on the used Servo library). Adding a delay() at the end of the loop() should make it work.
The soil sensor of Tinkercad has only a analog output, so I would use a analog input to measure it.
This is what I made of it:
// Forum: https://forum.arduino.cc/t/problem-while-controlling-soil-moisture-sensor-servo-motors/1156635
// This Wokwi project: https://wokwi.com/projects/372589470373021697
// Wokwi custom soil_sensor code by Maverick ?
#include <Servo.h>
Servo tap_servo;
const int sensor_pin = A0;
const int tap_servo_pin = 5;
void setup()
{
tap_servo.attach(tap_servo_pin);
}
void loop()
{
int val = analogRead(sensor_pin);
if (val < 600)
{
tap_servo.write(0);
}
else
{
tap_servo.write(90);
}
delay(100); // slow down the sketch
}
Try it in Wokwi simulation (Wokwi is more fun than Tinkercad, but Wokwi does not simulate an analog circuit):
Click on the green soil sensor (when the simulation is running) to change the soil humidity.