Potentiometer

Resistors Tutorial for Arduino, ESP8266 and ESP32

Resistor Tutorial for Arduino, ESP8266 and ESP32

In this article we cover different kinds of resistors like:

  • Photoresistors
  • Potentiometer
  • Thermistors

Also we will look deeper in the functionality of the voltage divider which gives us a basic understanding how these different kinds of resistors work. 

Potentiometer

Table of Contents

Voltage Divider

The objective of a voltage divider is to change the output voltage with the combination of 2 resistors.

One example of the use of a voltage divider is the light dependent resistor, see the second chapter in this article. Another example is a potentiometer to control the speed of a motor for example. The following example reduces the input voltage of 5V to an output voltage of 3.3V and uses a voltage divider for this task.

Voltage Divider
Voltage Divider explaination

The equation to calculate the output voltage from a voltage divider is given by: U2 = U* (R2/(R1+R2)). If the objective is to reduce the voltage from U=5V to U2=3.3V than multiple solutions are possible:

  • R1=1kΩ and R2=2kΩ
  • R1=5kΩ and R2=10kΩ.

So how do we choose the right combination? The solution is that the power to reduce the voltage and therefore the corresponding heat is not the same. The power is defined as P = U^2/(R1+R2). That’s why the combination of 5kΩ and 10kΩ resistors are producing less heat and are the preferable choice.

Keep in mind not to use a voltage divider to reduce the voltage to supply a device or load because you have to remember that an external device will result in a parallel circuit with R2. The following example show the differences in the decision to choose the resistors for the voltage divider.

WordPress Tables Plugin

In the example you could reduce the voltage from 5V to 2.22V with the combination of R1=50Ω and R2=100Ω but your output power with 278.52 mW will likely burn the resistors.

The following table gives you an overview of all components and parts that I used for this tutorial. I get commissions for purchases made through links in this table.

Photoresistor

The photoresistor, often called light dependent resistor (LDR) or light sensor, is a resistor which
changes his resistance based on the incident light.

Photoresistor explanation
Photoresistor explanation

The photoresistor contains electrons which are bonded to atoms in the valence band. If light falls on the photoresistor the electrons in the valence band, called valence electrons, absorb energy from the light and break the bond with the electrons. The electrons which break the bond are called free electrons and will jump into the conduction band. In the conduction band the electrons, not bonded to any atom are able to freely move from one place to another.
On the other side the atoms which previously had more electrons are now called holes. Therefore free electrons and holes are created as pairs and are carry electric current. These electric current decreases the resistance from the photoresistor.
When the energy from the light increases, more free electrons and holes are created and therefore the resistance decreases further. In summary: The resistance of the LDR decreases with increasing incident light.

To measure the incident light a voltage divider with a 4.7kΩ resistor is used.
With the analog to digital converter (ADC) the Arduino converts the reference voltage of the voltage divider to a digital value. In the following example we want to read the incident light from a light sensor and print the analog and digital values.

Photoresistor Steckplatine

You see that the light sensor is nothing else than a resistor. Therefore you don’t have to worry about the connection sites. There is no false way to connect the light sensor.

#define Photoresistor A0
int reading;
int bright;

void setup() {
  Serial.begin(9600);  // set baud rate to 9600
}

void loop() {
  reading = analogRead(Photoresistor);
  bright = map(reading, 0, 1000, 0, 100);
  Serial.println(bright);
  delay(10);
}

Potentiometer

A potentiometer is an adjustable voltage divider and has therefore 3 connection pins. A potentiometer consists of an electrically non-conductive support on which a resistance material is applied, two terminals at the two ends of the resistive element and a movable sliding contact (also referred to as a grinder), which can divide the electrically fixed total resistance mechanically into two partial resistances corresponding to this total resistance.

Potentiometer

The picture below shows how the output voltage of the voltage divider is calculated. Depending on the position of the sliding contact, the output voltage U2 is changing. I measured the output voltage in an example with my oscilloscope using R1=5kΩ and R2=10kΩ. The picture of the oscilloscope shows clearly how I changed the position of the grinder.

Potentiometer Steckplatine
Potentiometer Oscilloscope

If instead of three pins only two pins are used the potentiometer acts as a variable resistor. In the following picture you see the connection between the potentiomenter and the multimeter. The following video shows the resistances measured by the multimeter in different positions of the sliding contact.

Potentiometer Steckplatine

Thermistor

A thermistor is a resistor which changes the resistance based on the temperature. Thermistors are classified in two groups based on the behavior due to temperature changes:

  • Negative Temperature Coefficient (NTC) thermistors: The resistance decreases with an increase in temperature.
  • Positive Temperature Coefficient (PTC) thermistors: The resistance increases with an increase in temperature.

NTC thermistors are the most common and used in this article.

On the picture you see I use a thernistor module, which has the resistor in series already included. In my case the resistor is 10kΩ, which I measured with my multimeter. Therefore the separate resistor is missing in the picture. The circuit is already again a voltage divider which allows us to measure the voltage drop on the thermistor. Because the resistor is directly connected to ground we have a pull-up resistor. This is important for the calculation of the resistance of the thermistor. If you do not know the difference between a pull-down and pull-up resistor, you find here an article explaining the differences in detail.

Also It is possible to calculate the temperature based on the measurements of the thermistor voltage divider. Therefor we use the Steinhart equation. The following sketch shows you how to measure the voltage and the temperature with a thermistor.

int ThermistorPin = A0;
int Vo;
float R1 = 10000; // value of R1 on board
float logR2, R2, T;

//steinhart-hart coeficients for thermistor
float c1 = 0.001129148, c2 = 0.000234125, c3 = 0.0000000876741; 

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

void loop() {
  Vo = analogRead(ThermistorPin);
  R2 = R1 * (1023.0 / (float)Vo - 1.0); //calculate resistance on thermistor
  logR2 = log(R2);
  T = (1.0 / (c1 + c2*logR2 + c3*logR2*logR2*logR2)); // temperature in Kelvin
  T = T - 273.15; //convert Kelvin to Celcius
 // T = (T * 9.0)/ 5.0 + 32.0; //convert Celcius to Farenheit

  Serial.print("Temperature: "); 
  Serial.print(T);
  Serial.println(" C"); 

  delay(500);
}

Conclusion

Do you have any further questions about resistors, the voltage divider, photoresistors, rotary encoder or thermistors? Use the comment section below to ask your questions.

Ultrasonic Distance Sensor

Ultrasonic Sensor Tutorial for Arduino, ESP8266 and ESP32

Ultrasonic Sensor Tutorial for Arduino, ESP8266 and ESP32

In this tutorial you learn how to use the ultrasonic distance sensor HC-SR04.

In the first part we see how ultrasonic works.

The second part extends the theoretical part with two practical examples how to use the ultrasonic sensor.

Ultrasonic Sensor tutorial for Arduino and ESP8266

Table of Contents

Functionality of an Ultrasonic Distance Sensor

The ultrasonic distance sensor is used to measure the distance between the sensor and an object. There are a lot of robotic projects which use the sensor to identify a wall in a labyrinth and rotate the robot with the objective to find a way out of the labyrinth.

The most used sensor is the HC-SR04 ultrasonic distance sensor. This sensor can measure distances between 2cm and 4m. The measuring is done by the time taken to receive the echo of a 40 kHz ultrasonic sound wave emitted by the sensor.

For reliable measurements ultrasonic distance sensor should be perpendicular to the scanned surface horizontally and vertically. Also the scanned surface should be flat.

The following table gives you an overview of all components and parts that I used for this tutorial. I get commissions for purchases made through links in this table.

 Arduino UnoAmazonBanggoodAliExpress
ORESP8266 NodeMCUAmazonBanggoodAliExpress
ORESP32 NodeMCUAmazonBanggoodAliExpress
ANDHC-SR04 Ultrasonic Distance SensorAmazonBanggoodAliExpress
ANDDHT11 Module (blue)AmazonBanggoodAliExpress
ORDHT22 Module (white)AmazonBanggoodAliExpress
HC-SR04 ultrasonic distance sensor

The HC-SR04 ultrasonic distance sensor has the following specifications:

  • Power Supply :+5V DC
  • Quiescent Current : <2mA
  • Working Currnt: 15mA
  • Effectual Angle: <15°
  • Ranging Distance : 2cm – 400 cm/1″ – 13ft
  • Resolution : 0.3 cm
  • Measuring Angle: 30 degree
  • Trigger Input Pulse width: 10uS
  • Dimension: 45mm x 20mm x 15mm

Example of Ultrasonic Distance Sensor without Temperature and Humidity

The following example will give you a quick overview of the equations how to measure the distance with an ultrasonic distance sensor. The sensor send an eight-cycle signal at 40 kHz. After time_1 the signal will be reflected by the object and after time_2 the signal return back to the sensor and is measured. Therefore the distance between the sensor and the object is the speed of the sound multiplied by half of the time the signal was send, reflected and received. In the equation the speed of sound is 343 m/s or 0.0343 cm/μs converted to cm and the echo time measured in μs.

The following picture shows the connections between the sensors and the Arduino Nano.

Ultrasonic Distance Sensor Steckplatine
WordPress Tables Plugin

After we connect our devices we will go into the code. Our objective is to measure the distance between the sensor and our hand and print the distance to the serial monitor output. If the distance is out of range (< 2cm or > 4m) we will print an error.

int trigPin = 6;            // HC-SR04 trigger pin
int echoPin = 7;            // HC-SR04 echo pin
float duration, distance;
void setup()
{
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT); // define trigger pin as output
}
void loop()
{
  digitalWrite(echoPin, LOW);   // set the echo pin LOW
  digitalWrite(trigPin, LOW);   // set the trigger pin LOW
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);  // set the trigger pin HIGH for 10μs
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);  // measure the echo time (μs)
  distance = (duration/2.0)*0.0343;   // convert echo time to distance (cm)
  if(distance>400 || distance<2) Serial.println("Out of range");
  else
  {
    Serial.print("Distance: ");
    Serial.print(distance, 1); Serial.println(" cm");
  }
}
Ultrasonic Distance Output 1

Example of Ultrasonic Distance Sensor with Temperature and Humidity

If you want to measure the distance more exact you can calculate the speed of sound in dependence of the temperature and the humidity: v_sound = 331.3 + (0.606 * temp°C) + (0.0124 * humidity) m/s.

The following example we will use an Arduino Nano and also we use a temperature sensor to optimize the distance measurement. Moreover we will use a library for the HC-SR04 ultrasonic distance sensor called NewPing by Tim Eckel.
If you do not know how to install a new library in your Arduino IDE, I wrote a step by step article. You find the article with this link.

The NewPing library has some very nice function. Here are the top 3 of them:

  • sonar.ping_cm(): Returns the distance between the sensor and the target, but there are no digits after
    the decimal point.
  • sonar.convert_cm(echotime): Returns the distance given the echo time, but outlier values can be observed.
    It is more robust to calculate the distance between the sensor and point directly from the echo time.
  • sonar.ping_median(number of observations): Returns median echo time for the number of observations, with a minimum of five observations, after excluding out-of-range values.

The next picture shows the connections between the sensors and the Arduino nano as well as the temperature sensor, the DHT22. If you want to know more about temperature sensors, there is a whole article about multiple sensors. The wiring between the Arduino and the HC-SR04 is the same as the first example.

Ultrasonic Distance Sensor Temperature Steckplatine

In the sketch we added the reading of the temperature sensor and we calculated the speed of sound like the equation. Also we added some variables in the serial output:

  • echoTime: Raw value from the HC-SR04 ultrasonic distance sensor to calculate the distance between the sensor and the object.
  • distance: The distance between the sensor and the object.
  • temperature and humidity: The temperature and humidity from the DHT22 to calculate the speed of sound.
#include       // include NewPing library
#include "DHT.h"
#define DHT22PIN 5        // DHT22 pin
#define DHT22TYPE DHT22   // DHT22 type
int trigPin = 6;          // trigger pin
int echoPin = 7;          // echo pin
int maxdist = 100;        // set maximum scan distance (cm)
int echoTime;             // echo time
float distance;           // distance (cm)

NewPing sonar(trigPin, echoPin, maxdist);
DHT dht22(DHT22PIN, DHT22TYPE);

void setup()
{
  Serial.begin(9600);
  dht22.begin();
}
void loop()
{
  echoTime = sonar.ping();          // echo time (μs)
  float temperature = dht22.readTemperature();
  float humidity = dht22.readHumidity();
  float vsound = 331.3+(0.606*temperature)+(0.0124*humidity);
  distance = (echoTime/2.0)*vsound/10000; // distance between sensor and target
  Serial.print("echo time: ");    
  Serial.print(echoTime);         
  Serial.print(" microsecs\t"); 
  Serial.print("distance: ");    
  Serial.print(distance,2);      
  Serial.print(" cm");            
  Serial.print("\t Temperature: ");
  Serial.print(temperature);
  Serial.print("\t Humidity: ");
  Serial.println(humidity);
  delay(500);
}
Ultrasonic Distance Output 2

Conclusion

Do you have any further questions about the ultrasonic distance sensor? Use the comment section below to ask your questions. And what are projects you would like to use the distance sensor? There is also a second sensor to detect objects in a predefined range, the infrared distance module.

Arduino Mega Thumbnail

Arduino Mega Tutorial [Pinout]

Arduino Mega Tutorial [Pinout]

In this tutorial you learn everything you have to know about the Arduino Mega:

  • Technical datasheet
  • What is the pinout of the Mega?
  • What is the best power supply for this microcontroller?
  • Advantages and Disadvantages of the Arduino Mega.
  • Compare the Mega to other Arduino and ESP8266 based microcontroller.
Microcontroller Comparison

Table of Contents

The Arduino Mega is a microcontroller board, based on the ATmega2560P microcontroller by Atmel. The ATmega2560P comes with builtin bootloader which makes it very easy to flash the board with your code. Like all Arduino boards, you can program the software running on the board using a language derived from C and C++. The easiest development environment is the Arduino IDE.

The following table contains the datasheet of the microcontroller board:

WordPress Tables Plugin

Do you want to compare the datasheet of different microcontroller boards like Arduino Uno, Arduino Nano, ESP8266 Node MCU and WeMos D1 Mini? Follow this Link for the comparison.

If you do not already have an Arduino Mega, you can buy one from the following links. I get commissions for purchases made through links in this table.

Arduino Mega R3 Amazon Banggood AliExpress

Arduino Mega Pinout

Arduino Mega Pinout

Because the Mega is the biggest Arduino microcontroller, this beast has the highest number of pins and is therefore suitable for large projects where a lot of devices have to be connected to the microcontroller.

The Arduino Mega has in total one 3.3V pin and four 5V pins, which are able to provide a current up to 50 mA. The VIN power pin can also serve as power supply for the microcontroller with a voltage range between 7V-12V.

If you want to close the circuit, there are in total five ground pins available, which are all connected.

The Mega has 16 analog pins connected internally with a 10-bit analog-to-digital converter (ADC). Therefore the analog voltage is represented by 1024 digital levels. It is also possible to use the analog pins to write a digital signal with the function digitalWrite(Ax).

Also there are a bunch of digital pins available. In total the microcontroller has 54 digital I/O pins and 15 are able to produce a PWM signal. The maximum DC current per digital pin is 40 mA.

The Arduino Mega has all communication standards on board:

Arduino Mega Power Supply

The Arduino Mega power supply depends on the different voltage levels of the microcontroller. Therefore we have to know which electronic components are relevant for the voltage levels. The following picture provides an overview of the voltage levels and the maximum currents of the Arduino Mega.

Arduino Mega voltage current overview

The main component of the Arduino Mega is the microprocessor ATmega2560. The following table shows the minimum, operation and maximum voltage.

Microcontroller

Minimum Voltage

Typical Voltage

Maximum Voltage

ATmega2560

2.7V

5V

5.5V

Because the operation voltages is 5V, there this one build in voltage regulator that provide a stable 5V and also an additional voltage regulator for the 3.3V output voltage of the corresponding pin.

Arduino Mega Voltage Regulators

The following table shows the most important technical details of the two voltage regulators regarding the power supply.

Voltage Regulator

Output Voltage

Maximum Input Voltage

Maximum Output Current

LD1117S50CTR

5V

15V

800mA

LP2985-33DBVR

3.3V

16V

150mA

The LD1117S50CTR provides a stable 5V output for the ATmega2560 and has a maximum input voltage of 15V. But an input voltage between 7V and 12V is recommended to use the Arduino Mega over an extended period of time because otherwise the voltage regulator produces a lot of heat that can damage the microcontroller. Besides a higher input voltage than 12V has no advantage. The maximum output current of the LD1117S50CTR is 800mA.

The Arduino Mega can also be powered via the USB port. There is no need for a voltage regulator because the USB connection is already regulated by the USB output from your PC or laptop. The maximum current draw from the USB connection is therefore reduced to 500mA.

Because the Arduino Mega has 3.3V pins to supply external electrical devices, there is a second voltage regulator build in, that reduces the voltage from 5V to 3.3V. The LP2985-33DBVR has a maximum output current of 150mA but on the official Arduino website, the maximum current is limited to 50mA. In my opinion you should be save to draw a current up to 100mA.

The 5V pin of the Arduino Mega is directly connected to the 5V voltage regulator and supports a maximum current that is defined by the difference of the current provided by the voltage regulator and the current from the ATmega2560.

Maximum Current for I/O Pins

Regarding the data-sheet of the ATmega2560, each I/O port is tested with 20mA. But this does not mean that you can draw 20mA from each pin because the I/O pins are connected to a port register in groups of 7 pins. These port registers have in different combinations also a maximum allowed current.

There are in total 11 port registers with internal pull-up registers and some of them have an analog to digital converter if analog pins are connected to this register. The following picture shows which pin is assigned to which port register.

Arduino Mega Ports

Now we want to know which port register combination has to be considered when there is a maximum allowed current.

The maximum current for the combination of port registers is the following:

  • J0-J7 + A0-A7 + G2 < 200mA
  • C0-C7 + G0-G1 + D0-D7 + L0-L7 < 200mA
  • G3-G4 + B0-B7 + H0-B7 < 200mA
  • E0-E7 + G5 < 100mA
  • F0-F7 + K0-K7 < 100mA

Three possibilities for the Power Supply

Like the Arduino Uno, you can power your Arduino Mega in three save ways because a voltage regulator provides a regulated and stable voltage for the ATmega2560 microprocessor:

  1. USB cable: The most popular and also the easiest way to power the microcontroller is via USB cable. The standard USB connection delivers 5V and allows you to draw 500mA in total.
  2. DC Power Jack: It is possible to use the DC power Jack as power supply. If you buy a DC power jack, make sure the power adapter of the plug supplies a voltage between 7V and 12V.
  3. VIN Pin: If you use an external power supply like a battery, you can use the VIN pin. The voltage has to be between 7V and 12V. Therefore you are able to power the Uno with an external 9 Volt battery.

You cannot power the board with the barrel jack and VIN GPIO at the same time, because there is a polarity protection diode, connecting between the positive of the barrel jack to the VIN pin, rated at 1A.

You can also power power the Arduino microcontroller from the 5V pin. This is not recommended because you bypass the LD1117S50CTR 5V voltage regulator and have to make sure that the voltage level is stable.

It is not possible to power the Arduino Mega via the 3.3V pin because the voltage regulator prevent a current flow in the opposite direction.

Arduino Mega Power Consumption

The power consumption of the Arduino Mega is of course dependent on the connected electrical devices and the task that is performed. But we can get a good basic estimation of the current consumption when we sum up the individual current consumption of the main electronic parts of the microcontroller.

The main electronic part is the ATmega2560 that has a current consumption dependent on the clock cycle, the supply voltage and the power mode. The following table shows the typical and maximum current consumption of the different dependencies.

Mode

Clock Frequency

Supply voltage

Typical current consumption

Maximum current consumption

Active

1MHz

2V

0.5 mA

0.8 mA

Active

4MHz

3V

3.2 mA

5 mA

Active

8MHz

5V

10 mA

14 mA

Idle

1MHz

2V

0.14 mA

0.22 mA

Idle

4MHz

3V

0.7 mA

1.1 mA

Idle

8MHz

5V

2.7 mA

4 mA

The ATmega2560 has also a power-down mode that reduces the current consumption to a minimum.

Mode

WDT

Supply voltage

Typical current consumption

Maximum current consumption

Power-down

enabled

3V

< 0.005 mA

0.015 mA

Power-down

disabled

3V

< 0.001 mA

0.0075 mA

The activation of the power-down mode is easy if you use the Low-Power library from rocketscream. The following example scripts sets Arduino Mega in the deep-sleep mode for 8 seconds.

#include "LowPower.h"

void setup()
{
    // No setup is required for this library
}

void loop() 
{
    // Enter power down state for 8 s with ADC and BOD module disabled
    LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);  
    
    // Do something here
    // Example: Read sensor, data logging, data transmission.
}

From my experience I would power the Arduino Mega with a supply voltage of around 3V, when I try to minimize the power consumption and use a battery as power source. Therefore I assume a current consumption of 3.2mA.

Now I add the current consumption of the three voltage regulators to the consumption of the Arduino Mega. The LP2985 has a current consumption of 0.85mA at 150mA full load and the LD1117S50CTR draws maximal 10mA. Because we do not calculate with the limits of the voltage divider, I would guess a total current consumption of 3.2mA + 0.85mA / 2 + 10mA / 2 = 8.625mA.

Arduino Mega Advantages and Disadvantages

Advantages

  • The ability to use a Power Jack as a power supply.
  • The pure amount of 54 digital input pins are for the most projects far more than enough. In comparison the ESP8266 has only 1 analog input pin.

Disadvantages

  • For the Mega there is no build in WiFi. Because most of my projects are related to the IoT sector I use WiFi in almost all my projects.
  • The Mega has only 256 kB of flash memory for the many digital input pins.

Conclusion

The Mega is the biggest Arduino board on the market. If you need a lot of input pins the Arduino Mega has no competitors. Do you have any questions about the Arduino Mega or other boards on the market? Do you use the Mega in a project? If yes than let us know for what project do you use the Mega. Lave a comment below.

Arduino Nano Thumbnail

Arduino Nano Tutorial [Pinout]

Arduino Nano Tutorial [Pinout]

In this tutorial you learn everything you have to know about the Arduino Nano:

  • Technical datasheet
  • What is the pinout of the Nano?
  • What is the best power supply for this microcontroller?
  • Advantages and Disadvantages of the Arduino Nano.
  • Compare the Nano to other Arduino and ESP8266 based microcontroller.
Microcontroller Comparison

Table of Contents

The Arduino Nano is a microcontroller board, based on the ATmega328P microcontroller by Atmel. The Atmega328 comes with built-in bootloader, which makes it very easy to flash the board with your code. Like all Arduino boards, you can program the software running on the board using a language derived from C and C++. The easiest development environment is the Arduino IDE. The Nano is the smallest board of the Arduino boards but has nearly the same datasheet like the Arduino Uno. Only the power jack is missing and instead of a standard USB port the Nano has a Mini-B USB plug.

The following table contains the datasheet of the Arduino Nano R3 microcontroller board:

WordPress Tables Plugin

Do you want to compare the datasheet of different microcontroller boards like Arduino Uno, Arduino Mega, ESP8266 Node MCU and WeMos D1 Mini? Follow this Link for the comparison.

If you do not already have an Arduino Nano, you can buy one from the following links. I get commissions for purchases made through links in this table.

Arduino Nano R3 Pinout

Arduino Nano Pinout

The Arduino Nano is the smallest microcontroller in the Arduino family and has therefore the lowest number of pins and connections. But in my opinion the Nano is very suitable for projects where you do not need a wireless connection.

The Nano has one 3.3V and two 5V power pins of which one is the VIN pin. With the VIN pin you can supply the Arduino Nano with a voltage between 7V-12V to run the microcontroller on battery for example. All three power pins provide a maximum currency of 50 mA. You can close the circuit with two ground pins.

The microcontroller has 8 analog pins with a 10-bit analog-to-digital converter (ADC). The ADC converts the input voltage to a signal between 0 and 1023. There is also the possibility to use the analog pins as output with the function digitalWrite(Ax).

There are in total 14 digital I/O pins which can be used with a maximum currency of 40 mA if you are not using the serial ports RX0 (UART -> In) and RX1 (UART -> Out) and do not use the Serial.begin() function in your Arduino script. If you use the serial ports, then you have in total 12 digital pins (D2…D13) that can be used like you see in the pinout picture. If you want to create a PWM signal for example to control the speed of a motor, there are 6 of the 13 digital pins, which are PWM ready.

You can use pin 2 and 3 as interrupts if you want to monitor an input during the runtime of the whole Arduino script.

The typical communication standards (SPI, I2C and UART) are also available on the Arduino Nano.

Arduino Nano R3 Power Supply

The Arduino Nano board has different voltage levels, that we have to know before we can dive into the possibilities to supply power to the microcontroller. The following picture shows a schematic of the voltage levels on the Arduino Nano as well as the voltage levels and the maximum currents defined by the components.

Arduino Nano voltage current overview

The main microprocessor for the Arduino Nano 3 is the ATmega328p.

Microcontroller

Minimum Voltage

Typical Voltage

Maximum Voltage

ATmega328p

2.7V

5V

6V

The ATmega328p has an operation voltage of 5V, a minimum voltage of 2.7V and a maximum voltage of 6V. Therefore the two voltage regulators have an output voltage of 5V equal to the operation voltage of the microprocessor.

Arduino Nano Voltage Regulators

The following table shows the voltage specifications of the two onboard voltage regulators.

Voltage Regulator

Output Voltage

Maximum Input Voltage

Maximum Output Current

LM1117IMPX-5.0

5V

20V

800mA

FT232R USB UART

3.3V

5.25V

100mA

The FT232R USB UART is connected to the USB port of the Arduino Nano that supports the board with 5V and a maximum current of 500mA but it is recommended to only draw a current of 100mA if the microcontroller is powered via USB. The 3.3V pin is also powered from the FT232R voltage regulator that supports up to 50mA.

The second voltage regulator, the LM1117 supports input voltages between 7V and 12V with a maximum current of 900mA. In the data sheet you find a maximum voltage of 20V but this voltage is not recommended for a longer duration because the voltage regulator has no head sink.

The 5V pin of the Arduino Nano is directly connected to the 5V voltage regulator and supports a maximum current that is defined by the difference of the current provided by the voltage regulator and the current from the ATmega328p.

Maximum Current for I/O Pins

Each I/O pin supports a maximum current of 40mA but it is not possible to draw 40mA current over each pin because the maximum allowed current load of the port registers must be considered.

The digital and analog pins of the ATmega328p are connected to different port registers and each port register supports a maximum allowed current that depends on if the register is used as source or as sink. The following table shows which pin is assigned to which port register and also the maximum current.

Pins

D0…D4

D5…D7

D8…D13

A

Port Register

D0…D4

D5…D7

B0…B5

C0…C5

     

Max Current Source 150mA

    
     

Max Current Sink 100mA

    

There are in total 3 port registers: D, B, C. All digital pins D0…D13 are assigned to register D and B. For the maximum current, port register D is separated. All analog pins belong to the port register C.

The maximum current, if the pins are a current source, is 150mA. The sum of all pins in the colored port register should not exceed 150mA:

  • Current source of port register D0…D4 + C0…C5 < 150mA
  • Current source of port register D5…D7 + B0…B5 < 150mA

If the I/O pin is a current sink, the maximum current is 100mA and divided into three groups:

  • Current sink of port register D0…D4 < 100mA
  • Current sink of port register D5…D7 + B0…B5 < 100mA
  • Current sink of port register C0…C4 < 100mA

Two possibilities for the Power Supply

You can power your Nano in two save options because a voltage regulator provides a regulated and stable voltage for the microprocessor:

  1. Mini USB cable: The most popular and also the easiest way to power the Arduino Nano is via USB cable. The standard USB connection delivers 5V and allows you to draw 100mA in total.
  2. VIN Pin: If the current consumption exceeds 100mA you should power the Arduino Nano via the VIN pin. The voltage has to be between 5V and 12V. Therefore you are able to power the Nano with an external 9 Volt battery.

You can also power power the Arduino microcontroller from the 3.3V pin or the 5V pin. This is not recommended because you bypass the voltage regulators and have to make sure that the voltage level is stable.

Arduino Nano Power Consumption

The ATmega328p microprocessor draws about 5.2mA depending on the clock frequency and the supply voltage. The following table shows the typical and maximum voltage for different clock frequencies and supply voltages.

Mode

Clock Frequency

Supply voltage

Typical current consumption

Maximum current consumption

Active

4MHz

3V

1.5 mA

2.4 mA

Active

8MHz

5V

5.2 mA

10 mA

Active

16MHz

5V

9.2 mA

14 mA

Idle

4MHz

3V

0.25 mA

0.6 mA

Idle

8MHz

5V

1 mA

1.6 mA

Idle

16MHz

5V

1.9 mA

2.8 mA

The current consumption can be reduced, using the power-down mode.

Mode

WDT

Supply voltage

Maximum current consumption

Power-down

enabled

3V

0.044 mA

Power-down

enabled

5V

0.066 mA

Power-down

disabled

3V

0.004 mA

Power-down

disabled

5V

0.006 mA

The activation of the power-down mode is easy if you use the Low-Power library from rocketscream. The following example scripts sets Arduino Mega in the deep-sleep mode for 8 seconds.

#include "LowPower.h"

void setup()
{
    // No setup is required for this library
}

void loop() 
{
    // Enter power down state for 8 s with ADC and BOD module disabled
    LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);  
    
    // Do something here
    // Example: Read sensor, data logging, data transmission.
}

If we want to know the power consumption of the Arduino Nano we have to add the current consumption of all electric parts on the PCB.
After the ATmega328p we have to add the current consumption of the FT232R USB UART IC Regarding to the data sheet the average current consumption is 15mA. Therefor the average current consumption of the Arduino Nano, connected to USB, is 5.2mA + 15mA = 20.2mA. Additionally you have to consider the build in LEDs and other connected electrical parts like sensors or actors.

Arduino Nano R3 Advantages and Disadvantages

Advantages

  • The Nano has an advantage in size compared to the Uno. Because the Nano is shorter it fits better in small cases for your projects.
  • 8 analog input pins are for the most projects more than enough. The 1 analog input from the EPS8266 are for some projects too few and 8 analog inputs are better than the 6 of the Uno.

Disadvantages

  • For the Nano R3 there is no build in WiFi. Because most of my projects are related to the IoT sector I use WiFi in almost all my projects.
  • Also the Nano has a relative high price for his datasheet. If you are looking for a small but cheaper microcontroller, have a look at the WeMos D1 Mini.

Conclusion

The Nano is the smallest Arduino board on the market. If you do not need a WiFi connection the Arduino Nano is a good choice. If you want a small board in combination with a mini USB cable power supply and you do not need multiple analog pins than the WeMos D1 Mini with the ESP8266 chip will be a good alternative because this board has WiFi included.

Arduino Uno Thumbnail

Arduino Uno Tutorial [Pinout]

Arduino Uno Tutorial [Pinout]

In this tutorial you learn everything you have to know about the Arduino Uno:

  • Technical datasheet
  • What is the pinout of the Uno?
  • What is the best power supply for this microcontroller?
  • Advantages and Disadvantages of the Arduino Uno.
  • Compare the Uno to other Arduino and ESP8266 based microcontroller.
Microcontroller Comparison

Table of Contents

The Arduino Uno is a microcontroller board, based on the ATmega328P (for Arduino UNO R3) or ATmega4809 (for Arduino UNO WIFI R2) microcontroller by Atmel and was the first USB powered board of Arduino. The Atmega328 and ATmega4809 comes with built-in bootloader, which makes it very easy to flash the board with your code. Like all Arduino boards, you can program the software running on the board using a language derived from C and C++. The easiest development environment is the Arduino IDE.

The following table contains the datasheet of the microcontroller board:

WordPress Tables Plugin

Do you want to compare the datasheet of different microcontroller boards like Arduino Mega, Arduino Nano, ESP8266 Node MCU and WeMos D1 Mini? Follow this Link for the comparison.

If you do not already have an Arduino Uno, you can buy one from the following links. I get commissions for purchases made through links in this table.

Arduino Uno Pinout

Arduino Uno Pinout

The Arduino Uno has a lot of different pins and therefore we want to go over the different kinds of pins.

The Uno has in total three power pins of which one has a supply voltage of 3.3V and two pins provide 5V. All power pins have a maximum current of 50 mA. You can use the VIN pin to power the whole microcontroller with a voltage between 7V-12V, also perfect for a battery. Of cause if you have power pins you also need some ground pins to close the electric circuit. The Arduino Uno has in total three ground pins which are all connected internally.

To connect analog sensors like a temperature sensor, the Arduino has six analog pins. Internally the analog signal is converted into an digital signal with a 10-bit analog-to-digital converter (ADC). Therefore analog voltages are represented by 1024 digital levels (0-1023). You can also use an analog pin to write analog signals with the function digitalWrite(Ax) where Ax is the analog pin, for example A3.

The Arduino Uno has in total 14 digital pins which provide a maximum current of 20 mA. Six of the 14 digital I/O pins are able to produce a PWM signal.

If you want to communicate between multiple devices you need communication pins which are also provided by the Arduino. The microcontroller has for each communication protocol (I2C, SPI, UART) one group of pins.

Arduino Uno Power Supply

The Arduino Uno Power Supply depends on the electrical components that are on the PCB. The following picture gives an overview about all relevant components to get an overview of the different voltage levels on the Arduino and also the maximum currents.

Arduino Uno voltage current overview

The main component of the Arduino Uno is the microprocessor ATmega328p. The following table shows the minimum, operation and maximum voltage.

Microcontroller

Minimum Voltage

Typical Voltage

Maximum Voltage

ATmega328p

2.7V

5V

6V

Because the operation voltages is 5V, there are two build in voltage regulators that provide a stable 5V and 3.3V output voltage.

Arduino Uno Voltage Regulators

The following table shows the important technical details of the voltage regulators regarding the power supply.

Voltage Regulator

Output Voltage

Maximum Input Voltage

Maximum Output Current

NCP1117ST50T3G

5V

20V

800mA

LP2985-33DBVR

3.3V

16V

150mA

The NCP1117ST50T3G is connected to the VIN pin and the DC power jack. Technically the maximum input voltage is 20V but because at 20V the voltage regulator is producing a lot of heat and would break after a short time period, it is recommended to supply an input voltage between 7V and 12V. The NCP1117 provides a stable output voltage of 5V and a maximum current of 800mA for the ATmega328p.

The ATmega328p can also be powered via the USB connection, that I use a lot in my projects. There is no need for a voltage regulator because the USB connection is already regulated by the USB output from your PC or laptop. The maximum current draw from the USB connection is 500mA.

The second voltage regulator, 3.3V LP2985, has an input voltage of 5V and reduces the voltage to 3.3V for the 3.3V pin of the Uno. Regarding the data sheet of the LP2985, the maximum current is 150mA but on the official Arduino website, the maximum current should be 50mA. I never needed more than 50mA on the 3.3V pin, but in my opinion, a current draw of around 100mA should be possible.

The 5V pin of the Arduino Uno is directly connected to the 5V voltage regulator and supports a maximum current that is defined by the difference of the current provided by the voltage regulator and the current from the ATmega328p.

Maximum Current for I/O Pins

Each I/O pin supports a maximum current of 40mA but it is not possible to draw 40mA current over each pin because the maximum allowed current load of the port registers must be considered.

The digital and analog pins of the ATmega328p are connected to different port registers and each port register supports a maximum allowed current that depends on if the register is used as source or as sink. The following table shows which pin is assigned to which port register and also the maximum current.

Pins

D0…D4

D5…D7

D8…D13

A

Port Register

D0…D4

D5…D7

B0…B5

C0…C5

     

Max Current Source 150mA

    
     

Max Current Sink 100mA

    

There are in total 3 port registers: D, B, C. All digital pins D0…D13 are assigned to register D and B. For the maximum current, port register D is separated. All analog pins belong to the port register C.

The maximum current, if the pins are a current source, is 150mA. The sum of all pins in the colored port register should not exceed 150mA:

  • Current source of port register D0…D4 + C0…C5 < 150mA
  • Current source of port register D5…D7 + B0…B5 < 150mA

If the I/O pin is a current sink, the maximum current is 100mA and divided into three groups:

  • Current sink of port register D0…D4 < 100mA
  • Current sink of port register D5…D7 + B0…B5 < 100mA
  • Current sink of port register C0…C4 < 100mA

Three possibilities for the Power Supply

You can power your Arduino Uno in 3 save ways because a voltage regulator provides a regulated and stable voltage for the microprocessor:

  1. USB cable: The most popular and also the easiest way to power the microcontroller is via USB cable. The standard USB connection delivers 5V and allows you to draw 500mA in total.
  2. DC Power Jack: It is possible to use the DC power Jack as power supply. If you buy a DC power jack, make sure the power adapter of the plug supplies a voltage between 7V and 12V.
  3. VIN Pin: If you use an external power supply like a battery, you can use the VIN pin. The voltage has to be between 7V and 12V. Therefore you are able to power the Uno with an external 9 Volt battery.

You cannot power the board with the barrel jack and VIN GPIO at the same time, because there is a polarity protection diode, connecting between the positive of the barrel jack to the VIN pin, rated at 1A.

You can also power power the Arduino microcontroller from the 5V pin. This is not recommended because you bypass the NCP1117 voltage regulator and have to make sure that the voltage level is stable.

It is not possible to power the Arduino Uno via the 3.3V pin because the voltage regulator prevent a current flow in the opposite direction.

Arduino Uno Power Consumption

The ATmega328p microprocessor draws about 5.2mA depending on the clock frequency and the supply voltage. The following table shows the typical and maximum voltage for different clock frequencies and supply voltages.

Mode

Clock Frequency

Supply voltage

Typical current consumption

Maximum current consumption

Active

4MHz

3V

1.5 mA

2.4 mA

Active

8MHz

5V

5.2 mA

10 mA

Active

16MHz

5V

9.2 mA

14 mA

Idle

4MHz

3V

0.25 mA

0.6 mA

Idle

8MHz

5V

1 mA

1.6 mA

Idle

16MHz

5V

1.9 mA

2.8 mA

The current consumption can be reduced, using the power-down mode. (WDT = Watchdog Timer)

Mode

WDT

Supply voltage

Maximum current consumption

Power-down

enabled

3V

0.044 mA

Power-down

enabled

5V

0.066 mA

Power-down

disabled

3V

0.004 mA

Power-down

disabled

5V

0.006 mA

The activation of the power-down mode is easy if you use the Low-Power library from rocketscream. The following example scripts sets Arduino Mega in the deep-sleep mode for 8 seconds.

#include "LowPower.h"

void setup()
{
    // No setup is required for this library
}

void loop() 
{
    // Enter power down state for 8 s with ADC and BOD module disabled
    LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);  
    
    // Do something here
    // Example: Read sensor, data logging, data transmission.
}

If we want to know the power consumption of the Arduino Uno we have to add the current consumption of all electric parts on the PCB. Because the voltage regulators, LEDs and other parts needs also current for their functionality, the average current consumption of the Arduino Uno is around 45 mA.

Arduino Uno Advantages and Disadvantages

Advantages

  • The ability to use a Power Jack as a power supply
  • 6 analog input pins are for the most projects more than enough. The 1 analog input from the EPS8266 are for some projects too few.

Disadvantages

  • For the Uno R3 there is no build in WiFi. Because most of my projects are related to the IoT sector I use WiFi in almost all my projects.
  • The Uno does not have a deep sleep mode in comparison to the ESP8266.

Conclusion

The Arduino Uno is the standard Arduino board which is a good board for starters. The only real drawback is the missing WiFi. So make sure if your project already uses a WiFi connection or you would like to have this feature to upgrade your project in the future that you buy the Uno version with WiFi included. What are your thoughts on the Uno? Do you use this board and what were the reasons why you bought it? Use the comment section below for your answers.

Oscilloscope Thumbnail

Oscilloscope voltage, current, power measurements

Oscilloscope voltage, current, power measurements

In this tutorial you learn how to measure different electrical metrics:

  • Voltage across a resistor
  • Current through with Ohms Law
  • Power consumption of a capacitor

Before we dive deeper into the measurements let’s start with basic information about oscilloscopes to get a better foundation.

Oscilloscope Thumbnail

Table of Contents

General Information about Oscilloscopes

An oscilloscope is a typical laboratory instrument. The purpose of this instrument is to display and analyze waveform of electronic signals with frequencies from 1 hertz (Hz) up to several megahertz (MHz). Typically you use the oscilloscope to measure the voltage as a function of time. The oscilloscope display the voltage not as a plain number like a multimeter, but rather over time from the left to the right side. Like a multimeter also an oscilloscope is able to process and display alternating current (AC) or pulsating direct current (DC). The horizontal sweep is measured in time per seconds and the vertical deflection is measured in volts per division.

I personally use an USB oscilloscope from Pico Technology the Picoscope 2204 A. Because it is an USB oscilloscope it does not have any display. I can directly connect the oscilloscope with my computer and there is a software that gives me the interface of a standard oscilloscope. The main advantage of an USB oscilloscope is that there are cheap devices on the market because there is no need for a display or buttons. That is saving a lot of costs in comparison to non USB oscilloscopes.

The following table give you an overview about my Picoscope 2204 A.

Bandwidth10 MHz
Number of channels2
Input ranges+- 50 mV to +- 20 V
Input sensitivity10 mV/div to 4V/div
Minimum detectable pulse width5 ns
Maximum sampling rate100 MS/s
Shortest timebase10 ns/div
Maximum waveforms per second2000
Advanced triggersEdge, window, pulse width, window pulse width, dropout, window dropout, interval, logic
Trigger typesRising or falling edge
Standard output signals of function generatorSine, square, triangle, DC voltage, ramp, sinc, Gaussian, half-sine
Math channels and Software filters−x, x+y, x−y, x*y, x/y, x^y, sqrt, exp, ln, log, abs, norm, sign, sin, cos, tan, arcsin, arccos, arctan, sinh, cosh, tanh, freq, derivative, integral, min, max, average, peak, delay, duty Highpass, lowpass, bandpass, bandstop

The following table gives you an overview of all components and parts that I used for this tutorial. I get commissions for purchases made through links in this table.

Voltage Measurement with an Oscilloscope

To measure a voltage with an oscilloscope is the easiest part in working with this device. You only have to connect one probe with both ends before and after the electrical component you want to measure the voltage. The picture on the right shows you that the oscilloscope is therefore in parallel to the electrical component.

In my example I want to measure the voltage across a 10kΩ resistor. As a power source I use the NodeMCU V2 because I want to power on and power off the circuit for a given time. The following sketch shows the circuit and the sketch I used.

void setup() {
  pinMode(D3, OUTPUT);  // LED pin as output
}

void loop() {
  digitalWrite(D3, HIGH);
  delay(5000);
  digitalWrite(D3, LOW);
  delay(5000);
}
Measure Voltage Steckplatine

Then next pictures shows the output of the oscilloscope. On the x-aches you see that the circuit is powered on for 5 seconds and than powered off of another 5 seconds and so on. What is really interesting this, that even if I set the output pin to low, there is still a little voltage of around 0.2V on the resistance which has a lot of ripple. If the output is set to HIGH the output voltage of the GPIO is 3.3V which is shown in the picture.

Oscilloscope Voltage Measurement

Current Measurement with an Oscilloscope

It is possible to measure the current in a circuit directly with a current probe. But these are very expensive and I do not have one. An other possibility to measure the current is to use a known resistor and Ohms law: U=R*I

Therefore if we can measure the voltage over a known resistor, we also know the current in the circuit. We use the same setup and the same sketch of the voltage measurement with an oscilloscope. The only thing we add is a math channel in the oscilloscope. With a math channel I can add virtual channels based on mathematical operations of the real input channels. The following picture shows that I added the mathematical channel: U/10000 because I used a 10 kΩ resistor.

Oscilloscope Current Measurement

The time on the x-axis is not the same for the mathematical channel, because the values for the mathematical channel are calculated with the real values one period before.

Within the software of the oscilloscope I can measure the min and max current. The minimal current is 22 μA and the maximal current is 323 μA. Also I proved the min and max value from the oscilloscope against a measurement done with a standard multimeter.

Multimeter Min Current Validation
Multimeter Max Current Validation

Power Measurement with an Oscilloscope

Now we want to measure the power consumption of a capacitor. How can we do this? No problem, because we will combine what we learned so fare. The power is calculated by: P=U*I

  1. We measure the voltage over the capacitor directly with the first channel of the oscilloscope.
  2. We can measure the current by connecting a resistor in series with the capacitor, measuring the voltage over the resistor and calculating the current in the circuit.

The following picture shows how the electrical parts are connected.

Measure Power Steckplatine

Now we want to measure the power. The power is calculated by P_C=U_C*I = U_C*U_R/R where

  • U_C is the voltage over the capacitor
  • U_R is the voltage over the resistor
  • R is the resistor and 10 kΩ

You see the power consumption in the following picture as black line.

Oscilloscope Power Measurement

The minimal power consumption of the capacitor is 58.69 μW and the maximal power consumption is 10.62 mW. Also here the note that the time on the x-axis is not the same for the mathematical channel.

Power Consumption Min
Power Consumption Max

Conclusion

Now you know how to measure the voltage, current and power with an oscilloscope. Do you have any questions about the measurements? Do you use an oscilloscope or are you planning to buy one? I am happy when you leave a comment below.

Switches Thumbnail

Switches Tutorial for Arduino, ESP8266 and ESP32

Switches Tutorial for Arduino, ESP8266 and ESP32

In this tutorial you learn everything you need to know for your next project about the two different types of switches:

  • Buttons which are losing connection when released. Buttons power a device as long as the button is pressed.
  • Switches which maintain the state when the switch is pressed to hold the connection as long as the switch is pressed again.

Moreover you learn about the debouncing problem and how to fix it with a software and a hardware solution.

Switches Thumbnail

Table of Contents

You might wonder why the four-pin switch has 4 legs. How do we have to connect the switch to other components?

If the four-pin switch is not pressed, the pins A and C are connected as well as the pins B and D. If the switch is pressed, the connection of the pins changes and all pins are wired together. Therefore there is no difference if you connect your component you want to switch on pin B or pin D of the other side of the button.

Switch

The following table gives you an overview of all components and parts that I used for this tutorial. I get commissions for purchases made through links in this table.

Arduino Uno Amazon Banggood AliExpress
OR ESP8266 NodeMCU Amazon Banggood AliExpress
OR ESP32 NodeMCU Amazon Banggood AliExpress
AND Resistor and LED in Package Amazon Banggood AliExpress
AND Capacitors Amazon Banggood AliExpress
OPTIONAL Oscilloscope Amazon Banggood AliExpress

Connect Switches and Arduino

If you want to connect one or multiple switches to your Arduino it is useful to add a pull-down resistor when the signal should be LOW if the switch is open and to add a pull-up resistor if the signal should be HIGH if the switch is open. If you do not use a pull-down or pull-up resistor than, when the switch is open the digital pin is not connected to GND or to 5V. Therefore the pin state would be undefined.
The following section describes the difference between the pull-down resistor and the pull-up resistor.

Pull-Down Resistor

In the case of a pull-down resistor circuit, the pull down-resistor permits a small current to flow between the digital pin and GND. Therefore the digital input is pulled down to low. The following examples shows a LED which is connected with a button and a pull-down resistor. The objective of the sketch is that the LED is off, when the button is not pressed and the LED is on as long as the button is pressed.
Pull Down Resistor Schaltplan
Pull Down Resistor LED
int switchPIN = 7;  // pin switch
int switchStatus;   // status switch
int LEDpin = 4;     // pin LED

void setup() {
Serial.begin(9600);
pinMode(LEDpin, OUTPUT);  // LED pin as output
}

void loop() {
switchStatus = digitalRead(switchPIN);   // read status of switch

// turn LED on if switch is HIGH, turn LED off if switch is LOW
digitalWrite(LEDpin, switchStatus); 
}

It is possible to change the sketch that the used button has the functionality of a switch. The LED is turned on and off only if the button is pressed. Therefore the states of the LED and switch have to be stored in variables to compare the last state with the current inputs. If the button in continuously pressed the states should not be changed.

int switchPIN = 7;           // pin switch
int switchStatus;            // status switch
int switchStatusLast = LOW;  // last status switch
int LEDpin = 4;              // pin LED
int LEDStatus = LOW;         // current status LED

void setup() {
Serial.begin(9600);
pinMode(LEDpin, OUTPUT);  // LED pin as output
}

void loop() {
switchStatus = digitalRead(switchPIN);   // read status of switch
if (switchStatus != switchStatusLast)  // if status of button has changed
    {
      // if switch is pressed than change the LED status
      if (switchStatus == HIGH && switchStatusLast == LOW) LEDStatus = ! LEDStatus;
      digitalWrite(LEDpin, LEDStatus);  // turn the LED on or off
      switchStatus = switchStatusLast;
    }
}

Pull-Up Resistor

In the case of a pull-up resistor circuit, the pull down-resistor connect the digital pin and 5V. Therefore the digital input is pulled up to 5V. Only if the switch is closed, the digital pin is connected to GND.

Regarding the sketch for the pull-up resistor, we can copy the sketch of the pull-down resistor.

The switch example would be the same for the pull-up as for the pull-down. Only the initial state of the LED would be high. Therefore we do not consider the switch example for the pull-up resistor in this article.

Pull Up Resistor Schaltplan
Pull Up Resistor LED
int switchPIN = 7;  // pin switch
int switchStatus;   // status switch
int LEDpin = 4;     // pin LED

void setup() {
Serial.begin(9600);
pinMode(LEDpin, OUTPUT);  // LED pin as output
}

void loop() {
switchStatus = digitalRead(switchPIN);   // read status of switch

// turn LED on if switch is HIGH, turn LED off if switch is LOW
digitalWrite(LEDpin, switchStatus); 
}

Debouncing Problem with Buttons

When a switch or button is pressed, the metal contacts in the contact points can cause the contact points to touch several times. Therefore the contact is bouncing before making a permanent contact. You might ask yourself what problem could occur due the bouncing contacts. The problem is that the Arduino clock speed is 16 MHz which results in 16 million operations per second. So the Arduino will recognize the bouncing contacts as having closed and opened the contacts several times in a row. The following picture shows this behavior on the oscilloscope when pressing a button.

Button Debounce Problem
Button Debounce Problem

In the first picture you see clear, that when the button is pressed, the voltage only reach the around 1.8V instead of 5V. This behavior results in an LED that is not reacting when the switch or button is pressed. Only when the button is pressed a second time the internal contacts are connected and the operating voltage of 5V is reached and the LED stays on.

The same behavior can be shown when I try to switch the LED off in the second picture. The operating voltage is 5V and I push the button. Two times the voltage drops to around 4V and jumps back to 5V. The third time the voltage drops to around 1V but also jumpy back to 5V. Only when I push the button a forth time the switch is released and the LED goes off.

This behavior is a big problem in real live because to you want to push a button multiple times to switch on or off a light in your kitchen? I do not think so.

Good to know that there are two software and one hardware solution to fix this behavior called the debouncing problem.

Software solutions against debouncing

The first software solution is quite simple and initiates a delay and then rereads the state. The time between the two input reads is defined by a delay. If the delay is too short, the switch may be still bounding.

int switchPIN = 7;           // pin switch
int switchStatus;            // status switch
int switchStatusLast = LOW;  // last status switch
int LEDpin = 4;              // pin LED
int LEDStatus = LOW;         // current status LED

void setup() {
Serial.begin(9600);
pinMode(LEDpin, OUTPUT);  // LED pin as output
}

void loop() {
switchStatus = digitalRead(switchPIN);   // read status of switch
if (switchStatus != switchStatusLast)  // if status of button has changed
    {
      delay(50);     // debounce time of 50 ms
      switchStatus = digitalRead(switchPIN);   // read the status of the switchPIN again
      if (switchStatus != switchStatusLast) // if the status of the button has changed again
      {
        // if switch is pressed than change the LED status
        if (switchStatus == HIGH && switchStatusLast == LOW) LEDStatus = ! LEDStatus;
        digitalWrite(LEDpin, LEDStatus);  // turn the LED on or off
        switchStatus = switchStatusLast;
      }
    }
}

You see in the following pictures of the oscilloscope that the press and release voltage is more smoothly than without a software solution. This results in the behavior that when the button is pressed once, the LED turns on or off. The following video also shows the result of the software solution against debouncing.

Press

Debounce Problem Software Solution

Release

Debounce Problem Software Solution

A second possible software solution against debouncing is to continue delaying until there is no longer change in the switch state at the end of the debounce time. Therefore the state of the switch has to be stored at three different times:

  • State before the switch was pressed (switchStatusLast)
  • State during the debounce time (switchStatusDebounce)
  • State when the switch was last pressed (switchStatus)

If the state has changed and is present longer than a predefined debounce time, the state of the LED can be changed. To compare the debounce time with the time, the switch was last pressed we have to define the time the switch was last pressed as unsigned long variable because the integer number has an upper limit of (2^15-1) ms or 33 seconds. The unsigned long maximum value is (2^32-1) ms or 50 days.

But there is also a much better solution than saving the state of the switch 3 times because it is also possible to solve the problem with the debouncing switch with a capacitor hardware solution.

Hardware solutions against debouncing

The possible hardware solution to fix the debounce problem is to use a capacitor across the switch. While the switch is not pressed, the capacitor charges. When the switch is pressed, the capacitor discharges while the switch signal to the Arduino is HIGH. During the bouncing the energy of the capacitor maintains the switch signal at HIGH. A recommended resistor-capacitor combination is 10 kΩ pull-down resistor and 10µF capacitor.
The rate which the capacitor charges and discharges depends on the resistance R and the capacitance C. The equation for the voltage of the capacitor after t seconds

  • of charging is V(1-^e(-t/RC)) and
  • discharging is V(e(-t/RC))

Therefore the higher the RC value, the longer is the debounce delay. The debounce delay can be expressed as 0.693 * RC seconds. With a combination of a 10 kΩ pull-down resistor and 10µF capacitor the debounce delay is 69 ms. Although the combination of resistor and capacitor is free of choice, a large resistor should be used to minimize the current through the resistor.

Pull Down Resistor Capacitor
int switchPIN = 7;           // pin switch
int switchStatus;            // status switch
int switchStatusLast = LOW;  // last status switch
int LEDpin = 4;              // pin LED
int LEDStatus = LOW;         // current status LED

void setup() {
Serial.begin(9600);
pinMode(LEDpin, OUTPUT);  // LED pin as output
}

void loop() {
switchStatus = digitalRead(switchPIN);   // read status of switch
if (switchStatus != switchStatusLast)  // if status of button has changed
    {
      // if switch is pressed than change the LED status
      if (switchStatus == HIGH && switchStatusLast == LOW) LEDStatus = ! LEDStatus;
      digitalWrite(LEDpin, LEDStatus);  // turn the LED on or off
      switchStatus = switchStatusLast;
    }
}

Capacitor = 10µF

Capacitor = 100µF

In the following picture you see the voltage rise during the button press. It is very similar to the software solution.

Debounce Problem Hardware Solution

The following picture shows the voltage during the press and release phases. You see very good the impact of the capacitor reducing the voltage over time. The picture shows 4 cycles.

Debounce Problem Hardware Solution

Conclusion

In this article you learn about different kinds of switches and the pull-up and pull down resistors, how to use them and the differences. Also you learned what the debouncing problem is. Moreover we discussed hardware and software solutions against the debouncing problem.
I hope you enjoined this article. Do you have any further questions about switches? Use the comment section below to ask your questions.

Arduino IDE library 3

How to install a library in the Arduino IDE?

Arduino IDE: Installation of a Library

You want to install a new library on your Arduino desktop IDE? Here is a guide for you how to install a library and also I show you the most used libraries to will need for a lot of projects.

Let’s start by open the Arduino desktop IDE.

Arduino Logo

Table of Contents

On the navigation bar at the top of the IDE you see at the third position “Sketch”. When you mouse-over the Sketch button you find in the drop down menu “Include Library”. On the right side a new window expands with the current libraries and the first entry is “Manage Libraries…”. Click on it.

Arduino IDE library 1
Now the Library Manger opens in a new window which is the main part of the Arduino desktop IDE to install, update and uninstall libraries. Also the Library Manager has a hand search field from which you can search the library you want to install.
Arduino IDE library 2

Install a Library

If you want to install a library just type the name of the library in the search field and select the newest version. After you selected the version just click on the “Install” button.

After the successful installation you see after the name of the library that the installation was successful.

Arduino IDE library 3
Arduino IDE library 4

Update a Library

If you want to update a library you may become a popup at the main Arduino IDE. I would recommend to update a library when a newer version is available to ensure stability, security and access new functions. To update a library you can filter by libraries which are updatable. Filter after that type in the Library Manager and update the library with a click on the button “Update”.

Arduino IDE library update

Most used Libraries

WordPress Tables Plugin
Infrared Sensor Thumbnail

Infrared Sensor Tutorial for Arduino, ESP8266 and ESP32

Infrared Sensor Tutorial for Arduino, ESP8266 and ESP32

In this tutorial we will see how to use an infrared sensor. We take a look at three different types of infrared modules.

  • Infrared sensor for object detection.
  • Passive infrared sensor to detect a person in front of a device like a monitor.
  • Infrared distance module which can be used in robotic use cases where a car follows a line.

Table of Contents

Infrared radiation (IR) or infrared light is an electromagnetic radiation (EMR) and carries radiant energy like all EMR. Although IR behaves both like a wave and like its quantum particle, the photon.
Infrared light is not visible for humans because of longer wavelength as the human eye is capable to see:

  • Wavelength infrared: 700nm to 1000nm
  • Human visible wavelength: 400nm to 700nm

The following pictures gives you an overview about the electromagnetic spectrum.

electromagnetic spectrum

But there is a possibility to see the infrared light. You can see the light via your mobile phone, because the camera of you mobile phone see the light emitted by the infrared diode. You will see that the light is flickering because the infrared diode will turn on an off very fast. There is a rhythm behind this behavior which is necessary to encode the information sent from the diode.

Therefore we can use the IR by sending information as analog signals and encode these signals with a sensor. The following chapters describe normal infrared sensors and passive infrared sensors. Moreover we will discuss the use of infrared distance modules.

NEC Infrared Transmission Protocol

The NEC IR transmission protocol uses pulse distance encoding of the message bits. Each pulse burst (mark – RC transmitter ON) is 562.5µs in length, at a carrier frequency of 38kHz (26.3µs). Logical bits are transmitted as follows:

  • Logical ‘0’ – a 562.5µs pulse burst followed by a 562.5µs space, with a total transmit time of 1.125ms
  • Logical ‘1’ – a 562.5µs pulse burst followed by a 1.6875ms space, with a total transmit time of 2.25ms

When a key is pressed on the remote controller, the message transmitted consists of the following, in order:

NEC Message Frame
  1. a 9ms leading pulse burst (16 times the pulse burst length used for a logical data bit)
  2. a 4.5ms space
  3. the 8-bit address for the receiving device
  4. the 8-bit logical inverse of the address
  5. the 8-bit command
  6. the 8-bit logical inverse of the command
  7. a final 562.5µs pulse burst to signify the end of message transmission

The following table gives you an overview of all components and parts that I used for this tutorial. I get commissions for purchases made through links in this table.

 Arduino UnoAmazonBanggoodAliExpress
ORESP8266 NodeMCUAmazonBanggoodAliExpress
ORESP32 NodeMCUAmazonBanggoodAliExpress
ANDVS1838B Infrared SensorAmazonBanggoodAliExpress
ANDHC-SR501 passive Infrared SensorAmazonBanggoodAliExpress
ANDTCRT5000 Infrared Distance ModuleAmazonBanggoodAliExpress

Infrared Sensor

With the help of an infrared sensor the Arduino board is able to receive information from an infrared remote and take action based on the button you pushed on the infrared remote. Therefore the sensor scans specific frequency ranges, defined by standards, and convert these signals to the output pins of the sensor. The most basic infrared sensor is the VS1838B.

For operation the sensor receives and IR signal which have to be encoded.
There is the library “IRremote” from Ken Shirriff which encode the light pulse and will output a HEX code depending on the information sent by the infrared diode. I suggest to use the library because the decoding of the different manufacturer is quite difficult. You find here the article how to install a library in your Arduino IDE. You find the regarding library in the search field with the keyword “irremote”.
Sadly the library “IRremote” does not support boars based on the ESP8266 like the NodeMCU. But there is another library called “IRremoteESP8266” you have to use.

The following picture shows the connections between the infrared sensors and the Arduino Uno and the NodeMCU.

After we connect our devices we will go into the code. Our objective is to print out the code in HEX and Decimal (DEZ) when we push different buttons on the infrared remote control. In this example I use my TV remote control.

#include "IRremote.h"

const int RECV_PIN = 7;
IRrecv irrecv(RECV_PIN);
decode_results results;

void setup(){
  Serial.begin(9600);
  irrecv.enableIRIn();
  irrecv.blink13(true);
}

void loop(){
  if (irrecv.decode(&results)){
        Serial.println(results.value, HEX);
        Serial.println(results.value, DEC);
        irrecv.resume();
        Serial.println();
  }
}

Infrared Sensor Serial Monitor

With the help of this example you can identify all key codes of the remote control. After the identification you are able to react to different buttons on the remote control. On example could be that you want to turn on a red LED when you press volume up and you turn on a green LED when you press volume down on you remote control. Feel free to think about different use cases and try to program the corresponding sketch.

What if I do not know which protocol to use?

If you do not know which protocol to use, you can use the following sketch to find out what protocol to use.
#include "IRremote.h"

const int RECV_PIN = 7;
IRrecv irrecv(RECV_PIN);
decode_results results;

void setup(){
  Serial.begin(9600);
  irrecv.enableIRIn();
  irrecv.blink13(true);
}

void loop(){
  if (irrecv.decode(&results)){
        switch (results.decode_type){
            case NEC: Serial.println("NEC"); break ;
            case SONY: Serial.println("SONY"); break ;
            case RC5: Serial.println("RC5"); break ;
            case RC6: Serial.println("RC6"); break ;
            case DISH: Serial.println("DISH"); break ;
            case SHARP: Serial.println("SHARP"); break ;
            case JVC: Serial.println("JVC"); break ;
            case SANYO: Serial.println("SANYO"); break ;
            case MITSUBISHI: Serial.println("MITSUBISHI"); break ;
            case SAMSUNG: Serial.println("SAMSUNG"); break ;
            case LG: Serial.println("LG"); break ;
            case WHYNTER: Serial.println("WHYNTER"); break ;
            case AIWA_RC_T501: Serial.println("AIWA_RC_T501"); break ;
            case PANASONIC: Serial.println("PANASONIC"); break ;
            case DENON: Serial.println("DENON"); break ;
          default:
            case UNKNOWN: Serial.println("UNKNOWN"); break ;
          }
        irrecv.resume();
 }
}
Infrared Sensor Protocol Serial Monitor

Because I used for my example the TV remote control, you see that I have a Samsung TV.

Passive Infrared Sensor

The HC-SR501 has a build in voltage regulator on the PCB. Because the HC-SR501 is designed for Arduino boards, the sensor requires an operation voltage of 5V. However there is a possibility to get the HC-SR501 running for NodeMCU. You have to connect the Power Pin with the middle pin of the voltage regulator.

Passive infrared sensors are often used in systems when a device like a monitor should come back from energy save mode. Also these kind of sensors are used in motion alarm detectors.

All objects above a temperature of absolute zero emit heat energy in form of infrared radiation. Passive infrared (PIR) sensors like the HC-SR501 convert these infrared radiation into output voltage. Therefore the movement of an object results in a change in the infrared radiation level is detected by the PIR sensor.

After switching the sensor on, the PIR sensor requires 60 seconds to stabilize the current level of radiation. The HC-SR501 sensor has a 110 degree field of view and an operating range of 6 meters because of the Fresnel lenses. After a movement is detected the output is HIGH for 2.5 seconds after the movement is detected and switches back to LOW after the time.

With the use of the build in potentiometer you can adjust the time delay and the sensitivity of the sensor. The following table shows both maximum position of the potentiometer and the resulting settings.

WordPress Tables Plugin
After we connect our devices we will go into the code. Our objective is to detect if someone stays in front of the sensor. Therefore the sensitivity has to be high and the position of the potentiometer most counterclockwise.
Passive Infrared Sensor
int inputPin = 7;               // input pin (for PIR sensor)
int pirState = LOW;             // we start, assuming no motion detected
int val = 0;                    // variable for reading the pin status
 
void setup() {
  pinMode(inputPin, INPUT);     // declare sensor as input
  Serial.begin(9600);
}
 
void loop(){
  val = digitalRead(inputPin);  // read input value
  if (val == HIGH) {            // check if the input is HIGH
    if (pirState == LOW) {
      // we have just turned on
      Serial.println("Motion detected!");
      // We only want to print on the output change, not state
      pirState = HIGH;
    }
  } else {
    if (pirState == HIGH){
      // we have just turned of
      Serial.println("Motion ended!");
      // We only want to print on the output change, not state
      pirState = LOW;
    }
  }
}

Infrared Distance Module

The ultrasonic distance sensor is not the only sensor to detect if an object is in a predefined range in front of a sensor. There is also the infrared distance module. As sensor the TCRT5000 infrared distance module includes an infrared emitter and receiver and a potentiometer and is most often used. The module has also a potentiometer to define the threshold when an object is detected.

If the sensor is connected to the power source, the infrared diode is emitting the infrared light continuously. The distance measured by the sensor depends on the color of the surface. Different colors are measured by the reflecting factor because a black surfaces reflects less light than a white surface. Therefor the sensor is often used in follow the line robot projects. In our example we will investigate the impact of different colors on the sensors measurement.

If the received signal is greater than the threshold then the TRCT500 D0 pin state changes from LOW to HIGH and the onboard LED shows that an object is located.

Infrared Distance Module without analog output

Infrared Distance Module with analog output

WordPress Tables Plugin

After we connect our devices we will go into the code. Our objective is to measure different distances the sensor is able to receive and we will test the influence of different colors.

Infrared Distance Module without analog output

The distance module without analog output can not measure the distance because therefore the sensor needs the analog values. But the sensor has the digital output to detect an object. 

const int trackingPin = 7;
const int ledPin = 13; //pin13 built-in led
void setup()
{
  pinMode(trackingPin, INPUT); // set trackingPin as INPUT
  pinMode(ledPin, OUTPUT); //set ledPin as OUTPUT
}
void loop()
{
  boolean val = digitalRead(trackingPin); // read the value of tracking module
  if(val == HIGH) //if it is HiGH
  { 
    digitalWrite(ledPin, LOW); //turn off the led
  }
  else
  {
    digitalWrite(ledPin, HIGH); //turn on the led
  }
}

Infrared Distance Module with analog output

The infrared sensor with analog output can measure the distance to the target object and also the color of the target object.

const int pinIRd = 7;
const int pinIRa = A0;
int IRvalueA = 0;
int IRvalueD = 0;

void setup()
{
  Serial.begin(9600);
  pinMode(pinIRd,INPUT);
  pinMode(pinIRa,INPUT);

}

void loop()
{
  IRvalueA = analogRead(pinIRa);
  IRvalueD = digitalRead(pinIRd);
  
  Serial.print("Analog Reading=");
  Serial.print(IRvalueA);
  Serial.print("\t Digital Reading=");
  Serial.println(IRvalueD);
  delay(1000);

}
Infrared Distance Sensor Serial Monitor

Conclusion

In this article we took a look at three different types of infrared modules. First we saw how we can detect an object with an infrared sensor. With the help of a passive infrared sensor we build a sketch how we can detect a person in front of a device like a monitor. The last sensor was the infrared distance module which can be used in robotic use cases where a car follows a line.

Do you have any further questions about the different infrared modules? Use the comment section below to ask your questions. And what are projects you would like to use the sensors in this article? If you plan to use a distance sensor for a DIY project, check out the article about the ultrasonic distance sensor.

Temperature Humidity Sensor Thumbnail

Temperature and Humidity Sensor Tutorial for Arduino, ESP8266 and ESP32

Temperature and Humidity Sensor Tutorial for Arduino, ESP8266 and ESP32

In this tutorial your will learn everything you need to know about the temperature and humidity sensors:

  • One Wire Temperature Sensor
  • DHT11 Temperature and Humidity Sensor
  • DHT22 Temperature and Humidity Sensor

After this tutorial you know the differences between sensor and module.

Moreover you can copy all sketches for your own projects.

Temperature and Humidity Sensors

Table of Contents

There a two categories of temperature and / or humidity sensors. The first category are the one wire temperature sensors which provide an analog input as temperature. The second category are the DHT sensors which provide the temperature and humidity via digital input for Arduino, ESP8266 and ESP32 microcontrollers.

The following table gives you an overview of all components and parts that I used for this tutorial. I get commissions for purchases made through links in this table.

Arduino Uno Amazon Banggood AliExpress
OR ESP8266 NodeMCU Amazon Banggood AliExpress
OR ESP32 NodeMCU Amazon Banggood AliExpress
AND One Wire Temperature Amazon Banggood AliExpress
AND DHT11 Sensor (blue) Amazon Banggood AliExpress
AND DHT11 Module (blue) Amazon Banggood AliExpress
AND DHT22 Sensor (white) Amazon Banggood AliExpress
AND DHT22 Module (white) Amazon Banggood AliExpress

One wire temperature sensor

The one wire temperature sensor changes the resistance based on the current temperature. One often used one wire temperature sensor is the LM35 with an operating temperature range of -55°C…150°C. For every degree of temperature change the sensor changes his resistance that the output voltage changes by 10 mV. Therefore the maximum output voltage is (150°C-(-55°C)) * 10 mV/°C = 2.05V.

If you connect the LM35 with an Arduino digital input pin, the internal Arduino analog-to-digital conversation (ADC) converts the analog voltage to a digital value between 0 and 1023.

The default maximum ADC voltage of the Arduino board is 5V and equated to the value of 1023. Based on the maximum ADC voltage the digital input of the LM35 temperature sensor is between 0 and 1023*2.05/5 = 420. This solution will work but you will only use 2.05V/5V = 41% of the digital value range.
That’s why you can set the maximum ADC voltage to other values than 5V. The following table will give you an overview about the possible maximum ADC voltages, how to change the setting in the script and how much of the value range is used.

Maximum ADC voltageFunctionPercentage of used value range
5VanalogReference(DEFAULT)0.41
3.3VanalogReference(EXTERNAL)0.62
1.1VanalogReference(INTERNAL)1.86

Can you also use the maximum ADC voltage of 1.1V in this case? The answer is yes, but you will restrict the value range of the temperature sensor. The maximum output voltage changes from 2.05V to 1.1V and we know that the scale factor of the sensor is 10mV/°C. Therefore the maximum temperature with a ADC voltage set to 1.1V is 1.1V/10mV/°C=110°C. The temperature range changes to 0°C…110°C which is for indoor use chases a good and the most precise solution.

The wiring is pretty easy and straightforward. If the flat side of the LM35 one wire temperature sensor is looking up to you, the left bin is the power pin you connect to the Arduino 5V pin. The right pin is ground, therefore connect the right pin to GND. And the middle pin is the data pin you can connect to every analog input pin. I connected the data pin to A0 on the Arduino Uno

You have to use an analog pin on your microcontroller board to read the analog value of the one wire temperature sensor. If you have an Arduino, you will not have any problem because the Arduino boards have quite some analog input pins. But if you have an ESP8266 microcontroller with only one analog input pin, you may have a problem when this one pin is already in use and you do not want to use an analog multiplexer.

If you want to know how to use an analog multiplexer in combination with your NodeMCU to read multiple analog values, look at this article

You find the datasheet from the used LM35 temperature sensor from Texas Instruments here.

After wiring the temperature sensor correctly we can use the following sketch to plot the corresponding temperature with the Serial Plotter of the Arduino IDE. We will set the baud rate to 9600. Make sure that the baud rate in the sketch and in your Serial Plotter are the same.

float tempc; //variable temperature (degree Celsius)
float tempf; //variable temperature (Fahreinheit)
float vout; //temporary variable sensor reading

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

void loop() {
vout=analogRead(A0); //Reading the value from sensor

//analogReference(DEFAULT);
//// convert analog values between 0 and 1023 with 5000mV ADC
//vout = (vout/1023) * 5000;

analogReference(EXTERNAL);
// convert analog values between 0 and 1023 with 3300mV ADC
vout = (vout/1023) * 3000;

//analogReference(INTERNAL);
//// convert analog values between 0 and 1023 with 1100mV ADC
//vout = (vout/1023) * 1100;

// for every degree the output voltage changes 10 mV
tempc=vout/10;

tempf=(vout*1.8)+32; // Converting to Fahrenheit

Serial.print("in DegreeC=");
Serial.print(" ");
Serial.print(tempc);
Serial.print("\t");
Serial.print("in Fahrenheit=");
Serial.print(" ");
Serial.print(tempf);
Serial.println();
delay(2000);
}

DHT11 and DHT22 Temperature and Humidity Sensor

You can buy the DHT11 and DHT22 temperature and humidity as a sensor or as a module. Regarding performance there is no difference if you buy the sensor itself or the module. There are only 2 differences between the sensor or the module. The module is basically the sensor printed onto a circuit board (PCB) in combination of a 10 k Ohm pull-up resistor between the signal and 5V connection. The second difference is that the sensor has a 4-pin package out of which only three pins will be used whereas the module has only the three relevant pins.

If you want to know what the function of a pull-up resistor is, than read this article.

The DHT sensors measure the temperature with a surface mounted NTC temperature sensor (thermistor). If you want to know how a thermistor works, here is an extra article about thermistors. Humidity is measured by the change in resistance between two electrodes and a moisture holding substrate between the two electrodes.

The following picture show how to connect a DHT11 or DHT22 temperature and humidity sensor to your Arduino and NodeMCU. One picture for the version with the up resistor and one version without the pull-up resistor on the PCB, where you have to add the resistor yourself.

DHT SensorDHT ModuleArduino Uno / NodeMCU
VCCVCC5V / VIN
DataDataDigital I/O Pin XXX
Nc
GNDGNDGND
DHT22 Pinout

To use the DHT11 or DHT22 sensor in your sketch, you have to download the library of the sensors. The corresponding library is called: “DHT.h”

You find here an article how to install an external library via the Arduino IDE.

After you installed the library successful you can include the library via: #include . This will call the external library and take care of your sketch. The following sketch will read the temperature and humidity of a DHT11 sensor, DHT22 sensor and DHT22 module every 10 second and print the value to the serial output.

#include "DHT.h"
 
#define DHT11PIN 7        // define the digital I/O pin
#define DHT22PIN 6        // define the digital I/O pin
#define DHT22modulePIN 5  // define the digital I/O pin
 
#define DHT11TYPE DHT11         // DHT 11 
#define DHT22TYPE DHT22         // DHT 22
#define DHT22moduleTYPE DHT22   // DHT 22 module

DHT dht11(DHT11PIN, DHT11TYPE);
DHT dht22(DHT22PIN, DHT22TYPE);
DHT dht22module(DHT22modulePIN, DHT22moduleTYPE);
 
void setup() {
  Serial.begin(9600); 
   
  dht11.begin();
  dht22.begin();
  dht22module.begin();
}
 
void loop() {
  // Read all temperature and humidity sensor data
  float h11 = dht11.readHumidity();
  float t11 = dht11.readTemperature();
  float h22 = dht22.readHumidity();
  float t22 = dht22.readTemperature();
  float h22module = dht22module.readHumidity();
  float t22module = dht22module.readTemperature();
 
  // check if returns are valid and print the sensor data
  if (isnan(t11) || isnan(h11)) {
    Serial.println("Failed to read from DHT #1");
  } else {
    Serial.print("Humidity 11: "); 
    Serial.print(h11);
    Serial.print(" %\t");
    Serial.print("Temperature 11: "); 
    Serial.print(t11);
    Serial.println(" *C");
  }
  if (isnan(t22) || isnan(h22)) {
    Serial.println("Failed to read from DHT #2");
  } else {
    Serial.print("Humidity 22: "); 
    Serial.print(h22);
    Serial.print(" %\t");
    Serial.print("Temperature 22: "); 
    Serial.print(t22);
    Serial.println(" *C");
  }
  if (isnan(t22module) || isnan(h22module)) {
    Serial.println("Failed to read from DHT #2");
  } else {
    Serial.print("Humidity 22module: "); 
    Serial.print(h22module);
    Serial.print(" %\t");
    Serial.print("Temperature 22module: "); 
    Serial.print(t22module);
    Serial.println(" *C");
  }
  Serial.println();   // print a free line to make the output nicer
  delay(10000);       // print new values every 10 seconds
}

The following picture shows the serial output of the script. You see that the humidity sensor of my DHT11 sensor is broken. The differences in the humidity (~2%) and temperature (~1.5*C) are within the normal range.

Comparision_Screenshot

How to choose the right temperature and humidity sensor?

The following table give you an overview about the specifications of the temperature and humidity sensors. I would always chose the DHT22 sensor because in every project I want to know the temperature I also want to the humidity. Moreover the temperature range and the accuracy are ways better than the DHT11 sensor.

 DHT11 (blue)DHT22 (white)LM35
Temperature range0°C…50°C-40°C…80°C-55°C…150°C
Temperature accuracy+- 2°C+- 0.5°C+- 0.5°C
Humidity range20%…90%0%…100%n.a.
Humidity accuracy+- 5%+- 3%n.a.
Sampling rate1Hz (one every 1 second)0.5Hz (once every 2 seconds= 
Operating voltage3V…5V3V…5V4V…30V
Current consumption2.5mA2.5mA60μA

Conclusion

I hope you enjoyed this article about temperature and humidity sensors. We learned a lot about the two different temperature sensors: one-wire temperature sensor and the temperature sensor with integrated humidity sensor DHT11 and DHT22.

Do you have any further questions about temperature and humidity sensors? Use the comment section below to ask your questions.