Example Code for Arduino-Read Sensor Value

Last revision 2025/12/26

This article provides step-by-step instructions on how to read sensor values using Arduino, including hardware setup, software preparation, wiring tips, and sample code for DHT11 temperature and humidity sensor along with a moisture sensor. It features a wiring diagram and offers solutions for common errors while reading sensor data.

Hardware Preparation

Name Model/SKU Quantity Purchase Link
6xAA Battery Holder with DC2.1 Power Jack (FIT0141) FIT0141 1 Link
Free Life - EcoDuino Control Board - 1 -
DHT11 Temperature and Humidity Sensor DFR0067 1 Link
Moisture Sensor SEN0114 1 Link
sensor Cable - 2 -

Software Preparation

Please install the libraries before you testing the sample codes

Wiring Diagram

Soil moisture sensor:blue wire(A2),red wire(VCC),black wire(GND)
DHT11 humidity sensor:green wire(D9),red wire(VCC),black wire(GND)
Battery holder:red wire(+),black wire(-)

Other Preparation Work

  1. Install the DHT11 library in Arduino IDE
  2. Connect hardware according to the wiring diagram

Sample Code


#include <dht11.h>
dht11 DHT;
#define MOISTURE_PIN A2  /soil Moisture sensor/
#define DHT11_PIN    9   //DHT11

int airHumidity;   //environment humidity
int airTemperature;  // environment temperature
int soilHumidity;   //soil moisture

void setup(){
  Serial.begin(9600);
}

void loop(){
  int chk;
  chk = DHT.read(DHT11_PIN);   //Read Data
  switch (chk){
    case DHTLIB_OK:
                Serial.print("OK,\t");
                break;
    case DHTLIB_ERROR_CHECKSUM:
                Serial.print("Checksum error,\t");
                break;
    case DHTLIB_ERROR_TIMEOUT:
                Serial.print("Time out error,\t");
                break;
    default:
                Serial.print("Unknown error,\t");
                break;
  }
  airHumidity=DHT.humidity;
  airTemperature=DHT.temperature;
  soilHumidity=analogRead(MOISTURE_PIN);

  Serial.print("airHumidity:");
  Serial.print(airHumidity);
  Serial.print(",\t");
  Serial.print("airTemperature:");
  Serial.print(airTemperature);
  Serial.print(",\t");
  Serial.print("soilHumidity:");
  Serial.println(soilHumidity);

  delay(1000);
}

Result

Open the Serial monitor, Baud rate: 9600.

Additional Information

The cables packaged with the sensors is not correct,we suggest you use the orange cables attached.

Was this article helpful?

TOP