This is the Arduino code corresponding to my humidity project in the general project of the agriculture robotics, in this case my objective is measure the humidity of a plant and depending on the soil moisture or humidity a red LED will be switch on (low humidity)
/*
HC-SR04 Ultrasonic Sensor Example.
Turn the LED on when an object is within 100cm range.
Copyright (C) 2021, Uri Shaked
*/
#define ECHO_PIN 2
#define TRIG_PIN 3
void setup() {
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
float readDistanceCM() { //this part is for the speed
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
int duration = pulseIn(ECHO_PIN, HIGH);
return duration * 0.034 / 2;
}
void loop() {
float distance = readDistanceCM();
Serial.println(distance);
bool isNearby = distance < 30; //this is to determinate the maximum distance the sensor reads
digitalWrite(LED_BUILTIN, isNearby);
Serial.print("Measured distance: ");
Serial.println(readDistanceCM());
delay(10); //delay is to determinate the time the light is on when it receives a sign
}