DHT11 Humidity and Temperature Sensor

In this tutorial you will learn how to use a DHT11 Temperature and Humidity Sensor with the Arduino, what is DHT11, difference between DHT11 and DHT22, DHT11 circuit diagram with the Arduino, and how to write Arduino code to read DHT11 Temperature and Humidity. Finally, we will introduce the Elegoo DHT11 module.

What is DHT11 ?

The DHT11 sensor is low-cost Temperature and Humidity sensor that is ideal for hobbyists and prototyping applications. The DHT11 temperature sensor range: 0 – 50°C (±2°C) and DHT11 humidity sensor range: 20-80% (±5%). Its Supply voltage: 3 to 5.5V. DHT11 sensor uses a OneWire protocol.  It integrates a thermistor and a capacitive humidity sensor. An integrated ADC converter converts the measured values into a digital signal, which is then output via the OneWire interface.

Range0°C to 50°C (Temperature) 20% to 80% (Humidity)
Accuracy±2°C (Temperature) ±5% (Humidity)
Supply voltage3 to 5.5V
Current consumptionMax. 2.5 mA
Sampling time1 measurement per second
DHT11 Specifications

DHT11 vs DHT22 Specifications

Both DHT11 and DHT22 have the same pin configuration but have different characteristics. The comparison is shown below. In summary, the DHT22 a little more accurate have a slightly larger temperature and humidity range.

 DHT11DHT22 (AM2302)
Costlowerlow
Voltage (supply and I/O)3 to 5.5V3 to 5.5V
Max current2.5mA2.5mA
Temperature range0-50°C-40 to 80°C
Temperature accuracy±2°C±0.5°C
Humidity range20-80%0-100%
Humidity accuracy5%2-5%
Sampling rate1 Hz0.5 Hz
Physical dimensions15.5mm x 12mm x 5.5mm15.1mm x 25mm x 7.7mm
Pins4 pins with 0.1 inch spacing4 pins with 0.1 inch spacing
DHT11 and DHT22 Specifications

DHT11 Sensor Application

DHT11 is usually used in Weather Stations, HVAC, Dehumidifier, data loggers, humidity regulators, Home Appliances, and Consumer Electronics.

DHT11 sensor circuit diagram

The circuit diagram below shows DHT sensor Arduino circuit. Connect Pin 1 directly to Supply (3.3V or 5V), pin 4 to GND, and Pin 2 to the microcontroller pin with pull-up resistor to the supply voltage.

DHT11 sensor Arduino circuit. Source: Elegoo Inc.

DHT11 and DHT22 Pin Configuration

DHT11 and DHT22 have only three connections: Vcc, GND, and Data. Pin 3 is not connected.

DHT11 Pin configuration
  • Pin 1: Vcc
  • Pin 2: Data
  • Pin 3: NC
  • Pin 4: GND

Parts list (DHT11 Arduino)

The parts required for this tutorial are:

  • 1 Arduino board
  • 1 Breadboard
  • 1 Sensor DHT11 or DHT22
  • 1 Resistor 10k ohm
  • Connecting wires

DHT11 Fritzing Circuit

The figure below shows the DHT11 sensor interfacing with arduino. The DHT11 data pin is connected to the arduino digital pin 2.

DHT11 fritzing circuit

DHT11 Arduino Code

First install DHT sensor library:

In the Arduino IDE, go to Sketch->Include Library->Manage Libraries…

Type DHT11 in the search tab then go to DHT sensor library and click Install

DHT sensor library

After installing DHT sensor library, you should include the header file DHT.h in your program. Then define the Arduino pin for DHT sensor (here it’s pin 2), then select the DHT type (here DHT11) and define dht object. See the DHT11 temperature and humidity sensor Arduino code below.

#include "DHT.h"

// Define DHT pin
#define DHTPIN 2
// DHT11 selected
#define DHTTYPE DHT11 // Other possibilities DHT21, DHT22 

// Define DHT object
DHT dht(DHTPIN, DHTTYPE);

void setup()
{
  // Start Serial at baudrate 9600
  Serial.begin(9600);
  // Start DHT sensor
  dht.begin();
}

void loop()
{
  // Read temperature sensor
  float temp = dht.readTemperature();
  // Read humidity sensor
  float humidity = dht.readHumidity();
  
  /* Are temp and humidity values valid numbers? */
  if (isnan(temp) || isnan(humidity))
  {
    Serial.println("Failed to read from DHT11");
  }
  else
  {
    // Print out  temp and humidity values
    Serial.print("Temperature: ");
    Serial.print(temp);
    Serial.print(" °C, ");
    Serial.print("Humidity: ");
    Serial.print(humidity);
    Serial.println(" %");
  }
  delay(5000);
}

In the setup routine, the serial interface is configured to print out the measurement on the serial monitor and the DHT sensor is started.

In the main program, the measured values for humidity and temperature are now read in and assigned to the variables humidity and temp. The program then checks whether a valid numerical value has been measured for humidity and temperature. If both measured values are valid, they are printed out on the serial monitor, otherwise an error message is printed out.

DHT11 Serial Monitor

The code shown above remains the same. After wiring the Elegoo DHT11 Sensor with the Arduino. Click UPLOAD to upload the program shown above then open the serial monitor, you can see the data as below: (The temperature is around 23°C the humidity is 59.00 %)

DHT11 serial monitor

Elegoo DHT11 Sensor Module

The Elegoo DHT11 Module integrates the built-in 10 Kohm pull-up resistor. See figure below.

Elegoo DHT11 sensor module

Elegoo DHT11 Pin configuration

The mark S denotes the signal (pin 3).

  • Pin 1: GND
  • Pin 2: Vcc (3.3V or 5V)
  • Pin 3: Output

Elegoo DHT11 Arduino Circuit Diagram

The circuit diagram below shows the DHT sensor Arduino circuit. Since the pull-up resistor is already integrated into the module, connct the data pin directly to the arduino pin 2.

DHT sensor Arduino circuit. Source: Elegoo Inc.
Read More

Arduino Photoresistor

Photoresistor or Light Dependent Resistor (LDR) is used wherever there is a need to sense the absence or presence of light. In this tutorial, you will learn what is photoresistor or Light Dependent Resistor (LDR), LDR interfacing with Arduino, and how to write Arduino code for LDR sensor and LED. We will also introduce the Elegoo 37 sensor kit and its photoresistor module. Finally, intensity control of an LED using LDR and Arduino board code is presented.

What is photoresistor ?

The photoresistor or LDR (Light Dependent Resistor) is a light-sensitive semiconductor element that changes its resistance value according to the intensity of the light: the higher the light intensity on the sensitive surface of the LDR, the smaller its resistance value becomes.

A photoresistor has two connecting wires and can be treated like a variable resistor. The resistance value can be measured with an ohmmeter. The resistor has a very high resistance value in darkness and a very low resistance value in brightness.

LDR circuit

As we already mentioned, the resistance value indicates how much light falls on the photocell. However, the microcontroller cannot measure resistance directly, but it can measure the voltage applied to a resistor. Since the voltage is proportional to the resistor value according to ohm’s law, the easiest photoresistor circuit is to build a voltage divider between a fixed resistor and the LDR. The result is a voltage that changes according to the light intensity. The voltage drop across the resistor is connected to the analog input of the Arduino as shown below.

If the photoresistor is subjected to high light intensity, its resistance becomes small in relation to the fixed resistor. There is less voltage at the smaller resistor than at the larger one. In the following circuit, this means that we will measure a voltage value close to 5V at Arduino pin A0 at sun light for instance. In complete darkness, almost the entire voltage is applied to the photoresistor, and we measure voltage close to 0V.

LDR connection with Arduino

Photoresistor Arduino code

Below is an LDR Arduino code that measures the analog value of the LDR and prints it on the serial monitor. The purpose is to determine the analog value on which the room is dark or bright. Simply cover and uncover the LDR with your finger and monitor the value on the serial monitor.

Try to find out at which value the room is considered dark! The reason to do it this way because you might not be able to find the datasheet of your specific LDR. And to choose an appropriate value for your application without having to determine the illumination in lux.

#define LDR_PIN  A0 // LDR pin
unsigned int photoresistor = 0; // LDR_PIN value

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

void loop() {
  // Read analog value of the LDR
  photoresistor = analogRead(LDR_PIN);
  Serial.println(photoresistor); // Print on serial monitor 
  delay(1000); //Delay 1 second
}

Arduino LDR LED code

The Figure below shows the LDR connection with Arduino. The LDR circuit is connected to the Arduino analog pin A0. And an LED is connected to digital pin 13. The LED here is a representation of a lamp. You can replace the LED with a relay with transistor circuit, and the code remains the same.

Photoresistor circuit Arduino

Below is an Arduino code for LDR sensor and LED. This Arduino LDR LED code measures the analog value of the LDR and compares it with a threshold value (that you have already determined). If the LDR value is below the threshold, the LED turns on.

#define LED_PWM_PIN  13 // LED pin
#define LDR_PIN  A0 // LDR pin
unsigned int photoresistor = 0; // LDR_PIN value
const unsigned int thrLDR = 300; // Threshold for LDR

void setup() { 
  pinMode(LED_PWM_PIN, OUTPUT);
}

void loop() {
  // Read analog value of the LDR_PIN 
  photoresistor = analogRead(LDR_PIN);
  // is LDR analog value greater than Threshold ?
  if (photoresistor < thrLDR) {
    digitalWrite(LED_PWM_PIN, HIGH); //Turn LED on
  }
  else
  {
    digitalWrite(LED_PWM_PIN, LOW); //Turn LED off
  }

  delay(1000); //Delay 1 second
}

Elegoo 37 sensor kit

The Elegoo 37 sensor kit contains 37 sensors and other electronic components that are combined together in a high-quality and nice plastic box. The benefit of buying such a kit is that the sensor circuits are already built for you so that you can concentrate on the code and your application.

Elegoo photoresistor

The Elegoo photoresistor module is a breakout board for the LDR circuit as shown below. Its LDR Resistance in darkness can go higher than 20 Megohms and as low as 80 Ohms in sunlight. The fixed resistor is 10 kOhm.

Elegoo photoresistor

The pin marked with – should be connected to GND, the middle pin should be connected to VCC, and the pin marked with S should be connected to Arduino analog pin.

Intensity control of LED using LDR and Arduino

Arduino LDR LED

In the previous code, the Arduino make a digital decision to turn the LED on or off if the room is dark or not. In this Arduino LDR example, we will use Arduino analog read and PWM output to change the intensity of the LED with respect to changes of the LDR brightness using Arduino map. Finally, it print out the LDR and LED PWM values. If the result is not satisfying, tune the values: 1023 and 255 for your application.

#define LED_PWM_PIN  9 // LED PWM pin
#define LDR_PIN  A0    // LDR analog pin
unsigned int ValLDR = 0, ledPWM = 0; // LDR and LED values

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

void loop() {
  // Read analog value of the LDR_PIN 
  ValLDR = analogRead(LDR_PIN);

  // Map LDR to PWM range
  ledPWM = map(ValLDR, 0, 1023, 0, 255);
  // Set PWM to the LED pin
  analogWrite(LED_PWM_PIN, ledPWM);
  
  Serial.print("LDR value: ");
  Serial.print(ValLDR);
  Serial.print("       "); 
  Serial.print("LED PWM vlaue: ");
  Serial.println(ledPWM);

  delay(1000); //Delay 1 second
}
Read More

Arduino Analog

After reading this tutorial, you will understand the basic of Arduino analog pins: What they are, how to use them as input or output, how to analogRead, and how to analogWrite. Also, we present the concept of Pulse-width modulation (PWM).

What is Analog ?

Analog signals are the signals in our “analog” world. The temperature, for instance, can be expressed in
an infinite set of values: e.g. 25°C, 25.1°C, 25.12°C, 25.123°C, 0°C, -4°C, -4.7°C, etc.

Analog temperature sensors provide analog voltage as an output signal, which corresponds to the measured temperature. Let’s consider the temperature sensor LM35. It measures the surrounding temperature with a linear scale of 10 mV/°C.

The 5V Arduino Boards reads and processes analog signals in a voltage range from 0 to 5 volts. The microcontroller of the Arduino board has an internal Analog-to-digital converter (ADC) for processing the analog input signals. The Arduino Uno, for instance, has six analog channels, in which six analog voltages (i.e. sensors) can be processed in parallel. The ports available for this purpose are labeled A0 to A5 on the Arduino Uno.

The resolution of its ADC is 10 bits. The 10-bit resolution corresponds to 210 = 1024 values. With a reference voltage of 5 volts, input signals from 0 to 5 volts can be read in, which are digitized by the ADC into values from 0 to 1023. This results in an accuracy of 5 V / 1024 = 4.9 mV

This 5V reference voltage is generated from the supply voltage and can be changed with the analogReference command. However, this command is not covered in this article.

Arduino analogRead

The Arduino analog read is done using analogRead() function by passing the analog pin as the function parameter. In the following instructions, the analog port A0 is read in and the resulting raw ADC value is then stored in the variable rawADC.

unsigned int rawADC = 0;
rawADC = analogRead(A0);

Now, let’s write the first analog sketch. The following circuit diagram depicts a potentiometer (variable resistor) connected to the Arduino analog pin A0.

Potentiometer circuit diagram

In the following sketch, the analog port A0 is read in and the resulting raw ADC value is then stored in the variable rawADC. Consequently, the program prints out the rawADC value on the serial monitor. Now, by rotating the potentiometer from fully clockwise to fully counter-clockwise, you will see that the ADC value alters between 0 and 1023, which corresponds to 0 V to 5V, respectively.

unsigned int rawADC = 0;    // variable for analog value

void setup() {
    Serial.begin(9600); //Init serial @ 9600 baudrate
}

void loop() {
  // read the analog raw value:
  rawADC = analogRead(A0);

  // print to the Serial Monitor
  Serial.print("Potentiometer value = ");
  Serial.println(rawADC);

  delay(1000);        // Wait 1000 ms
}

LM35 Arduino

The LM35 temperature sensor measures the temperature with a linear scale of 10 mV/°C. This means that each one degree Celsius is 10 mV. Thus, the equation to convert between raw ADC to degree Celsius is

Temperature [°C] = (rawADC/1024) * 5 * 100

The figure below shows the LM35 pinout for the TO-92 package from the LM35 datasheet. Simply connect pin 1 to 5V, pin 3 to GND, and pin 2 to an analog port.

LM35 pin diagram. Source: Texas Instruments

The following circuit diagram depicts an LM35 sensor connected to the Arduino analog pin A0.

LM35 interfacing with Arduino

In the following sketch, the temperature sensor LM35 is connected to the Arduino analog pin A0. The resulting raw ADC value is then stored in the variable rawADC. The temperature is then calculated according to the equation mentioned above and finally printed on the serial monitor.

// Define senor pin and variable for temperature
#define TEMP_SENSR_PIN  A0
double temp, rawADC;

void setup()
{
    Serial.begin(9600); //Init serial @ 9600 baudrate
}

void loop()
{
    // Read analog raw value
    rawADC = analogRead(TEMP_SENSR_PIN);
    // convert to degree celsius
    temp = (rawADC/1024.0) * 5.0 * 100.0;
    // Print temperature in °C
    Serial.print(temp);
    Serial.println("°C ");

    delay(1000);        // Wait 1000 ms
}

Arduino analogWrite

The Arduino outputs analog signals by means of pulse width modulation (PWM). With this technique, an analog signal can be generated by generating a digital signal, alternating between HIGH and LOW, with variable pulse time.

Due to the variable times of the HIGH phase (pulse time), an analog voltage between 0 to 100% (0V to 5V) can be generated. Think of it as the resulting average voltage. The PWM register is 8 bits, i.e. values from 0 to 255 (28 -1), which corresponds to an analog voltage between 0 to 5V.  The Arduino Uno default PWM frequency is 490 Hz, which corresponds to a period T = 1/frequency, which equals around 2 ms. So within this period, we control the percentage of output high to the complete period. This percentage is called the duty cycle.

PWM signal. Source: wikipedia.org

The PWM is usually used to control motors, servos, or the brightness of an LED, etc. The Arduino Uno PWM pins are 3, 5, 6, 9, 10, and 11. They are the same for Arduino Nano and Mini.

The output of an analog voltage by means of PWM is done with the function:

 analogWrite(Pin, Value)

The parameter Pin defines the PWM pin and Value defines duty cycle in an integer value between 0 and 255 (corresponds to 0% to 100%) as function parameters. For instance, Value = 128 represents a 50% duty cycle and 2.5 V.

Arduino map

Consider the following circuit diagram, a potentiometer (poti) is connected to the Arduino analog pin A0 and an LED connected to port 9.

Arduino LED and Poti circuit diagram

The sketch below is written to read the analog voltage from the poti, map the analog range (0 to 1023) to the PWM range (0 to 255) using the Arduino map() function and finally output PWM to dim the LED. As a result, the LED changes its brightness as you rotate the poti.

// Port for PWM and variable for the PWM value
#define PWM_PIN 9
#define TEMP_SENSR_PIN  A0

unsigned int valuePWM, rawADC = 0;

void setup()
{
    // Set port 9 as PWM output
    pinMode(PWM_PIN, OUTPUT);
}

void loop()
{
    // Read analog raw value
    rawADC = analogRead(TEMP_SENSR_PIN);
    // Map analog raw range to PWM range
    valuePWM = map(rawADC, 0, 1023, 0, 255);
    // Set PWM to the pin
    analogWrite(PWM_PIN, valuePWM);
}

Arduino PWM to analog

As mentioned already, the PWM is not an actual analog signal. Rather, the resulting average voltage seems to be analog. Fortunately, combining the output PWM signal with a low-pass filter creates an analog signal as shown in the following circuit diagram. This circuit consists of an RC circuit and a buffer.

PWM to analog converter
Read More

Arduino Digital

After reading this tutorial, you will understand the basic of Arduino digital pins: What they are, how to configure them as input or output, how to digitalRead, and how to digitalWrite. Also we present, briefly, the concepts of debouncing, and pull-up & pull-down resistors.

Digital Inputs

Arduino digital pins know only two states: HIGH voltage (1’s) and LOW voltage (0’s), where 1 corresponds to a voltage of 5 volts and 0 to a voltage of 0 volts. The signals to be read in at the digital inputs come from other digital circuits such as push-button or limit switch, or sensors with digital outputs.

pinMode input

The digital pins of the Arduino microcontroller are programmed as inputs by default and have a high input impedance. No configuration needs to be done for an input. In most programs, however, inputs are defined with the pinMode().

As already explained in Arduino Sketch, the configuration is done in the setup() function.

void setup()
{
  pinMode(12, INPUT); // Set pin 12 as input
}

Pull-up and Pull-down Resistors

A pullup or pulldown resistor is used to provide a clearly defined signal (LOW or HIGH) at the input pin. Without a pullup or pulldown resistor, noise on an open input pin can cause Distortion so that false signals are detected by the microcontroller.

If you want to read the status of a switch, for example, a limit switch from a robot, the pullup or pulldown resistor should be connected. This is necessary so that the input has a fixed potential if the switch is not activated, to avoid the so-called floating state, where the actual voltage is not recognized as high nor low.

Pull-up Resistor

The figure below shows the connection of an Arduino input pullup resistor. If the 10kΩ resistor were replaced with wire, there would be a short circuit between 5V and GND pins when pressing the switch. In addition, the signal could no longer be determined correctly due to interference. The pullup resistor ensures that the signal is “pulled up” to VCC.

Pull-up Resistor

Internal Pull-up Resistor

Instead of connecting a pullup resistor, an internal pull-up can be enabled. This configuration is then done in the setup() using the pinMode function by passing the parameter INPUT_PULLUP. The next figure represents the Arduino internal pullup resistor.

void setup()
{
  // Set Port 2 as input and enable pullup resistor 
  pinMode(2, INPUT_PULLUP); 
}
Internal Pull-up Resistor

Pull-down Resistor

The figure below shows the connection of the Arduino input pulldown. It has the same concept as the pull up resistor, except that the read value is 0 V when the switch is not pressed. The pulldown resistor ensures that the signal is “pulled down” to GND.

Pull-down Resistor

digitalRead

Reading the value for a digital input is done using digitalRead(PinNumber). The read result is always a value HIGH or LOW. The Arduino Uno digital pins are in the range from 0 to 13.

int switchVal;           // variable for switch

void setup()
{
  pinMode(12, INPUT); // Set pin 12 as input
}

void loop()
{
  switchVal = digitalRead(12);     // Read pin 12
}

The PinNumber can be passed directly as a number in the pinMode function or passed as a Define or variable initialized at the beginning of the Arduino Sketch.

#define SWITCH_PIN   2   // Define input pin
int switchVal;           // variable for switch

void setup()
{
  pinMode(SWITCH_PIN, INPUT); // Set SWITCH_PIN as input
}

void loop()
{
  switchVal = digitalRead(SWITCH_PIN); // Read switch state
}

Debouncing

When reading digital signals from switches or push-buttons, it often happens that several signals with HIGH and LOW are read when the button is pressed. This behavior is called “bouncing”. As a result, the Arduino thinks that the switch is pressed several times.

The bouncing behavior can be suppressed by means of debouncing. The debouncing can be done on

  • hardware level (debouncing circuit)
  • software level (debouncing code)
Debouncing circuit

One of the debouncing circuits is the RC circuit, which consists of resistor (R) and capacitor (C). Here R2 and C1 act as a so-called low pass filter. The resistor R1 is the pull-up resistor.

RC Circuit
Debouncing code

Instead of using extra components for the debouncing circuit, the bouncing issue can be solved using the software. The simplest way is to use a small delay after the digitalRead as below. Choose a value between 10 and 50 ms.

  // read button state
  buttonSt = digitalRead(BUTTON_PIN);
  // Delay 50 ms for debouncing
  delay(50);

A more robust way is to use Arduino debounce code, available in the Arduino IDE under File/Examples/02.Digital/Debounce.

This example implements the hysteresis by using the millis() function to update the button state after milliseconds since the last time the push-button pressed. It reverts the LED state each time the button is pressed.

Digital Outputs

The digital outputs of the Arduino are the signal transmitters to the outside world, which control LEDs, relays, etc. The outputs provide digital signals, i.e. 1 and 0 or HIGH and LOW. The voltage levels are 5 volts for HIGH and 0 volts for LOW. Of course, for 3.3 V Arduino, the output signals at signal HIGH are 3.3 volts.

The Arduino Uno maximum current for digital I/O is 40 mA. This current allows the direct control of an LED with a series resistor. The control of components such as relays, lamps, or motors requires an additional driver circuit that uses transistors or driver IC.

Arduino digitalWrite

Any of the Arduino Uno digital pins (0 to 13) can be initialized as output or input. An output pin must be initialized as output in the setup(). The output voltage is set to HIGH or LOW in the loop() for the application use, as shown in the blinking LED sketch.

Arduino read digital output

In some applications, we would like to read the current state of a specific digital output pin. One solution is to connect another input port to the output port we want to check. However, this solution requires reserving additional digital ports for this simple check!

A better solution to read the output pin with digitalRead(), although it is defined as an output. We wrote the sketch below to present this concept. The LED 1 follows the state of the push button. Next, the program waits 1 second. Subsequently, we read the actual state of LED 1 using ledSt = digitalRead(LED_PIN1) and pass it to LED 2 using digitalWrite(LED_PIN2, ledSt).

#define BUTTON_PIN  2    // Push-button pin
#define LED_PIN1   12    // LED 1 pin
#define LED_PIN2   13    // LED 2 pin

int ledSt = LOW;          // Current LED state
int buttonSt;             // Current button state

void setup()
{
  // Set LED 1 and 2 as outputs
  pinMode(LED_PIN1, OUTPUT);
  pinMode(LED_PIN2, OUTPUT);
  // Initialize pin 12 and 13 as low
  digitalWrite(LED_PIN1, LOW);
  digitalWrite(LED_PIN2, LOW);
}

void loop()
{
  // read button state
  buttonSt = digitalRead(BUTTON_PIN);
  // Delay 10 ms for debouncing
  delay(10);

  // Set LED 1 as button state
  digitalWrite(LED_PIN1, buttonSt);
  
  // Dealy 1000 ms
  delay(1000);
  // Read LED 1 state
  ledSt = digitalRead(LED_PIN1); 
  // Set LED 2 as LED 1
  digitalWrite(LED_PIN2, ledSt); 
}

Read More

Arduino Testing

Test Arduino code

The testing of the software and hardware is carried out in several steps. During code programming, the programmer can check the syntax errors using the compiler directly in the Arduino IDE (using Verify button). However, this syntax error check does not give any indication of incorrect structuring or sequence of the program.

Testing the correct sequence of the code should be done directly on the board with external components connected. However, it’s a good idea to perform a hardware test for each component by writing small test programs for each external component individually.

By connecting all hardware parts and running the whole program for the first time, the first important test is done. Often the built solution does not run or runs partially faulty during the first tests. Now the debugging of the individual actions and functions of the program begins.

The display of individual variable values or signal states within the program sequence can be realized using the serial monitor by outputting the desired values to the serial interface. In the console the data are displayed during the program run and support the programmer in troubleshooting.

Arduino serial monitor

The serial monitor is a useful tool within the Arduino IDE and allows the display of the transmitted data via the serial port. When you open the Serial monitor, via the toolbar or Tools->Serial Monitor, a new window opens a new window without any content.

Serial Monitor

The serial monitor can now be used to receive data from the Arduino or to send data. To show data from the Arduino on the serial monitor, the Arduino Board must execute serial print instruction as shown in the example below.

void setup()
{
  // Initialize serial at baudrate of 9600
  Serial.begin(9600);  
}

void loop()
{
  Serial.println("Hallo world");
}

Serial.begin(9600); instruction initialize the serial transmission with a transmission rate (called baud rate) of 9600 bits per second. This should match the baud rate on the serial monitor window in order to see sent data.

char letter = '0';

void setup()
{
  // Initialize serial at baudrate of 9600
  Serial.begin(9600);
}
void loop() {
  if (Serial.available() > 0){
    letter = Serial.read();
    if(letter == 'A'){
      Serial.println("Letter is A");
    }
    else if(letter == 'B'){
      Serial.println("Letter is B");
    }
  }
  delay(500);
}

Serial.begin(9600); instruction initialize the serial transmission with a transmission rate (called baud rate) of 9600 bits per second. This should match the baud rate on the serial monitor window in order to see sent data.

To receive the data from the Arduino board, the instruction Serial.println( ); is used to print out what’s inside the brackets on the serial monitor. For sending data from the serial monitor, write a text in the input field and press the button Send or press Enter.

Debug Arduino code

Where programming is done, errors occur. You will notice this quickly when you first lines of code for your Arduino board. A missing semicolon or a forgotten declaration and the IDE complains when compiling the program code. With smaller projects, you usually found the error quickly and fixed it then recompile again. Such errors are called compile errors.

But an error does not necessarily mean a missing semicolon or a typo in the code. Another type of error is called runtime error, where your program compiled successfully but your project does not work as expected.

Possible causes can vary: In the program structure a function is not called, a wrong formula used in the calculations, or even a variable declared with a wrong data type.

The approach to look deeper into the code to find the error is called debugging. The first important step is to make sure that the external components like a sensor or limit switch are wired properly. Second, check that they deliver correct values or signals. This can be tested using small sketches to check that they are functioning correctly.

Another way is to inject debugging instruction inside the code. One example is to use Serial print to print out sensor values or Computation output on the serial monitor. This way you can see what and where is things going wrong.

#define DEBUG

#define SENSOR_PIN  A0  // Sensor analog input pin 
#define PWM_PIN       9      // PWM output pin

int valSensor= 0;        // variable for sensor value
int valPwm= 0;        // variable for PWM output value

void setup()
{
  // Initialize serial at baudrate of 9600
  Serial.begin(9600); 
  
  #ifdef DEBUG
    Serial.println("Debugging aktiviert");
  #endif

}

void loop()
{

   // read the sensor value
  valSensor= analogRead(SENSOR_PIN);
  // map to PWM range
  valPwm= map(valSensor, 0, 1023, 0, 255);
  // Update the PWM value:
  analogWrite(PWM_PIN, valPwm);

  #ifdef DEBUG
    // Print on the Serial Monitor:
    Serial.print("sensor value = ");
    Serial.print(valSensor);
    Serial.print("t PWM output value = ");
    Serial.println(valPwm);
  #endif


  // wait 500 milliseconds
  delay(500);
  
}

By defining DEBUG, the values can be checked on the serial monitor. Once done with debugging, undefine DEBGU (replace #define with #undef) and no output is sent to the serial port.

Digital states can be visualized not only by the output on the serial monitor but also using LEDs. For this purpose, connect an LED and series resistors on the required port of the Arduino board. Then the LED will turn-on or off according to the actual voltage on the ouput pin.

Read More

Arduino Functions

Functions in Arduino

A function is a closed unit within a program and is called by its name. Usually with the function call still values are passed, which are processed then within the function. These values are called “parameters”. After execution of the function, which can be a calculation, a conversion or a signal output to an output port, this “small program” is executed and the main program, which called the function, is continued.

Often, however, the called function returns a response (called function return). This can be the result of a calculation or a status of a state.

Function Structure

The structure of the function is as follows:

Type FunctionName (type parameter){
//Function body
rerun val;
}

An example looks like this:

Function Structure

The type of a function indicates what kind of value is returned from the function. This can be int, char, etc. Accordingly, the data type of this return value is specified in the call of the function before the function name. The call of a function is usually made from the main program.

Arduino Function Example

Program 1

Program 1 shows the call of the function sensorRead from the main program (loop). The return value is the analog value with the int data type. For a function that does not have a return value, the keyword void is used for the type designation.

Program 2

In Program 2, the loop calls the function sensorReadPrintSerial which has no return value and no input parameter. Consequently, this it calls another function printVal, which has an input parameter an no return.  

Read More

Arduino – Variables and Datatypes

Arduino Variables

In programming, values that are stored for further processing are named with a single word called a variable. The value of a variable can change continuously or be changed by the program. The variable name should be chosen in such a way that it is easily readable and understandable within the program. In addition, a variable also has a data type that defines the value range.

The Variable must be declared before being used. So the data type, the variable name and the value of the variable are set. If no value is specified, the variable value is set to 0.

datatype Variable_Name = Value;

Example:

int motorSpeed = 255;

Comprehensible variable names such as motorSpeed or temperatureSensor improve the readability of the program

Arduino Datatypes

A data type describes the value range and the possible operations of a variable. Since the data types of the variables require different amounts of memory, you must be aware of exactly which possible values a variable defined can have when creating the program: Is it only a digital state with the values yes and no or can the variable hold an entire text? The data type must be selected accordingly. The most important data types and their value ranges for creating Arduino programs are listed below:

Data typeValue range    Memory requirement  Explanations/Notes    Examples
booleantrue/false1 byteValue for Yes/No or On/Off,  boolean machineStatus = true;  
int-32,768 to 32,7672 bytes  Integer values for values without decimal places  int potiValue = 1023;  
unsigned int  0 to 4,294,967,295    2 bytesInteger for positive values without decimal places  int tempValue = -5;  
byte0 to 2551 byteLow values (and correspondingly small memory requirements)    byte brightnessLED = 126;  
wordUnsigned 16-bit or 32-bit16-bit on Atmega boards.
32-bit on Due and Zero
Be aware of processor usedword value = 1500;
long-2,147,483,648 to 2,147,483,6474 bytesInteger numbers with big values        long offset = -15362;  
unsigned long0 to 4,294,967,2954 bytesUnsigned Integer numbers with big values  unsigned long secondsPassed = 45379;
float-3.4028235E+38 to 3.4028235E+384 bytesValues with decimal places  float voltageValue = 3.3;  
double-3.4028235E+38 to 3.4028235E+384 bytes-3.4028235E+38 to 3.4028235E+38double distanceGPS= 722.54;  
char  -128 to 127  1 byteValue for storing one character  char charR = ‘R’;  
unsigned char  0 to 2551 byteUsually used with numbers having range 0 to 255unsigned char charNumber = 255;
stringlength depends on definitiondepends on needStrings like texts or several charactersstring brand[ ] = “ROBOSANS”;
arraysize depends to definitionDepends on array sizestore values in variables with table form like e.g. lists of ports or configuration valuesint portsPWM[ ] = {3,5,6,9,10,11};
Arduino Datatypes

Read More

Arduino Sketch

What is Arduino Sketch ?

The code that runs on Arduino is usually called “Sketch”. Getting started with Arduino programming is quite easy because the structure of the Sketches is clear. The Arduino programming language is derived from C++ programming. You only need a few lines of code for your first simple projects.

Arduino Sketch Structure

The structure of an Arduino program is divided into two parts: setup() and loop().

Arduino Sketch Structure

The setup function is executed only once when the Arduino board is started or after a reset. In this function basic settings like variable declarations, the configuration of ports, or initialization routines. Additionally, the inputs and outputs are set, as shown in the Blink example below, the led pin 13 is set as output.

Arduino blinking LED Sketch

The setup function is mandatory and must always be present, even if no declarations have to be made. In this case, the function remains empty.

The loop function is the second area of the basic structure of an Arduino program and has the task of the main program. After the setup function has been executed once, the loop function is run through – as its name implies, as an endless loop. In the loop, all further instructions and function calls are accommodated, which are needed in the normal operation for the desired application. As in the blinking example, it turns on the LED, waits one second, turns it off, waits one second, and repeats forever.

Arduino Examples

The easiest way to get started is to work through example programs and then modify and extend them for your own applications. Also, you can find a lot of Arduino sketches and even complete projects for your application on the internet. One Arduino code example is called AnalogInOutSerial shown above.

AnalogInOutSerial Arduino example

It sets the pulse width modulation (PWM) of an output pin (9) based on the analog input readings on pin (A0), after mapping from the ADC scale (0 to 1023) to the output PWM scale (0 to 255). It also prints out the results on the Serial Monitor. The circuit diagram for this code is shown below

Read More

Arduino IDE

The Arduino IDE is a complete development environment containing code editor, documentation and a number of examples as well as standard libraries.

Arduino Software Setup

For the development of the Arduino programs, the Arduino integrated development environment (IDE) should be installed on the local computer. It can be downloaded free of charge from the Arduino website.

In addition, a USB driver must be installed and configured. This driver enables the USB port to communicate as a serial port with the FTDI chip on the Arduino board. The software is available in the archive file of the development environment and must be installed after the installation of the development environment.

Arduino Serial Port

Communication between the IDE takes place via the virtual COM port that has been set up, using the USB interface as the physical transmission medium.

  1. Connect the Arduino to the computer via a standard USB. After connection, power supply is applied to the board from the USB interface.
  1. Open the Arduino IDE. Select the Arduino board via the menu item Tools->Board.
Selecting the Arduino Board on the IDE
  1. Select the serial port (COM port) via the menu item Tools->Port. Note that the serial port to be used only appears in the listing if the Arduino board is connected to the computer via USB cable.
Selecting the com port on the IDE

Arduino blinking LED

For the first function test and the first executable Arduino program, various example programs are already stored in the IDE.

  1. Open the Blink program via Files->Examples->Basics. This test program controls the digital output port 13 of the Arduino (an LED is already connected on the board), blinks every second.
  2. Compile the program via the menu item Sketch->Verify/Compile.
  3. Upload the code to the Arduino’s microcontroller via Sketch->Upload into the microcontroller on the Arduino board.

Another way to compile (Verify) and upload the code is to use the symbols: to verify and to upload.

Read More

What is Arduino Uno ?

The Arduino Uno is the standard board of the Arduino which was introduced at the New York Maker Faire in September 2010.

Arduino Uno. Source: arduino.cc

Arduino Uno Specifications

DescriptionDetailed data
MicrocontrollerATmega328
Power supply7-12 VDC
Operating voltage5 VDC and 3.3 VDC (internally generated by voltage regulator)
Digital inputs/outputs14 (6 of them as PWM outputs)
Analog inputs6
Current per digital pin40 mA DC
Flash memory32 KB (ATmega328), where 0,5 KB are occupied by the bootloader
SRAM2 KB (ATmega328)  
EEPROM1 KB (ATmega328)
Clock frequency16 MHz
USB interfaceyes
Reset switchyes

Arduino Uno Pinout

Arduino Uno Pinout. Source: pighixxx

What type of connector does an Arduino Uno contains ?

On the Arduino Uno the following connectors are standard:

  • USB socket: The USB port (type B) is used for programming via the development environment and for communication with the connected computer. At the same time the board can be powered via the USB port.
  • Socket for external power supply: The Arduino board can be supplied with an external power supply or battery via a 2.1 mm socket. The power supply via the USB port is automatically deactivated. A particular advantage is the higher power that can be drawn from the external supply voltage, for example to supply actuators and sensors. In case of a short-circuit, it is not the USB port of the connected computer that is loaded, but the overload protection of the external power supply.
  • Connector strips for digital inputs and outputs: Single-row connector sockets that can be plugged into the extension boards (shields) or connector strips. All existing ports and interfaces are available via these connector strips.
  • ICSP: The pin row for the ICSP (In-Circuit Serial Programming) allows programming of sketches (programs) without bootloader by means of an external programming device.

Arduino Ports

A “port” is a connector pin of the microcontroller that can be programmed as input or output.
The Arduino inputs and outputs are the interfaces to the physical world to read environmental data. Input ports read e.g. temperatures, humidity, distance from an infrared sensor, or signals from a limit switch, etc. Output ports are used to control e.g. lamps, relays, or motors, etc.

This article describes the Arduino digital port and this article describes the capabilities of the Arduino analog pins. The Arduino Uno has 14 digital ports and 6 analog ports.

Individual ports have additional special tasks like the transmitter signal (port D1) or receiver signal (port D0) of the serial interface or the pulse width modulation (PWM).

Using Arduino expansion board (Arduino shields) the number of ports or their functionality can be extended. You should note that that the shields occupy ports that can no longer be used by the applications on the extensions. For example, the Ethernet Shield reserves port 10 to 13 for SPI communication.

Read More
error: Content is protected !!